repo_id stringlengths 4 98 | size int64 611 5.02M | file_path stringlengths 1 276 | content stringlengths 611 5.02M | shard_id int64 0 109 | quality_score float32 0.5 1 | quality_prediction int8 1 1 | quality_confidence float32 0.5 1 | topic_primary stringclasses 1 value | topic_group stringclasses 1 value | topic_score float32 0.05 1 | topic_all stringclasses 96 values | quality2_score float32 0.5 1 | quality2_prediction int8 1 1 | quality2_confidence float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
phodal/serverless | 1,451 | track/serverless.yml | service: track
custom:
table: owntracks
provider:
name: aws
runtime: nodejs4.3
environment:
table: '${self:custom.table}'
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-1:*:*"
functions:
pub:
handler: handler.pub
events:
- http:
path: pub
method: post
geojson-points:
handler: handler.points
events:
- http:
path: '{tid}/geojson/points'
method: get
cors: true
geojson-linestring:
handler: handler.linestring
events:
- http:
path: '{tid}/geojson/linestring'
method: get
cors: true
resources:
Resources:
OwntracksDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
-
AttributeName: "tid"
AttributeType: "S"
-
AttributeName: "tst"
AttributeType: "N"
KeySchema:
-
AttributeName: "tid"
KeyType: "HASH"
-
AttributeName: "tst"
KeyType: "RANGE"
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: '${self:custom.table}'
| 0 | 0.860399 | 1 | 0.860399 | game-dev | MEDIA | 0.314603 | game-dev | 0.813618 | 1 | 0.813618 |
DenizenScript/Depenizen | 2,905 | src/main/java/com/denizenscript/depenizen/bukkit/bridges/PlayerPointsBridge.java | package com.denizenscript.depenizen.bukkit.bridges;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.tags.Attribute;
import com.denizenscript.denizencore.tags.ReplaceableTagEvent;
import com.denizenscript.denizencore.tags.TagManager;
import com.denizenscript.denizencore.tags.TagRunnable;
import com.denizenscript.depenizen.bukkit.commands.playerpoints.PlayerPointsCommand;
import com.denizenscript.depenizen.bukkit.properties.playerpoints.PlayerPointsPlayerProperties;
import com.denizenscript.depenizen.bukkit.Bridge;
import com.denizenscript.denizen.objects.PlayerTag;
import com.denizenscript.denizencore.objects.properties.PropertyParser;
import org.black_ixx.playerpoints.PlayerPoints;
import org.black_ixx.playerpoints.models.SortedPlayer;
import org.black_ixx.playerpoints.storage.StorageHandler;
import java.util.Collection;
import java.util.TreeSet;
import java.util.UUID;
public class PlayerPointsBridge extends Bridge {
public static PlayerPointsBridge instance;
@Override
public void init() {
instance = this;
DenizenCore.commandRegistry.registerCommand(PlayerPointsCommand.class);
PropertyParser.registerProperty(PlayerPointsPlayerProperties.class, PlayerTag.class);
TagManager.registerTagHandler(new TagRunnable.RootForm() {
@Override
public void run(ReplaceableTagEvent event) {
tagEvent(event);
}
}, "playerpoints");
}
public ListTag getLeaders() {
// This ridiculous mess copied from source of: `org.black_ixx.playerpoints.commands.LeadCommand`
Collection<String> players = ((PlayerPoints) plugin).getModuleForClass(StorageHandler.class).getPlayers();
TreeSet<SortedPlayer> sorted = new TreeSet<>();
for (String name : players) {
int points = ((PlayerPoints) plugin).getAPI().look(UUID.fromString(name));
sorted.add(new SortedPlayer(name, points));
}
ListTag result = new ListTag();
for (SortedPlayer player : sorted) {
result.addObject(new PlayerTag(UUID.fromString(player.getName())));
}
return result;
}
public void tagEvent(ReplaceableTagEvent event) {
Attribute attribute = event.getAttributes().fulfill(1);
// <--[tag]
// @attribute <playerpoints.leaders>
// @returns ListTag(PlayerTag)
// @plugin Depenizen, PlayerPoints
// @description
// Returns a list of all players known to PlayerPoints, sorted in order of point value.
// Use like, for example, '<playerpoints.leaders.get[1].to[10]>' to get the top 10.
// -->
if (attribute.startsWith("leaders")) {
event.setReplacedObject(getLeaders().getObjectAttribute(attribute.fulfill(1)));
}
}
}
| 0 | 0.870317 | 1 | 0.870317 | game-dev | MEDIA | 0.941316 | game-dev | 0.985485 | 1 | 0.985485 |
gscept/nebula-trifid | 2,280 | code/application/graphicsfeature/properties/inputproperty.h | #pragma once
//------------------------------------------------------------------------------
/**
@class Properties::InputProperty
An input property adds the ability to handle user input to an entity.
If an InputProperty is attached to an entity it can become the input
focus entity. Global input focus is managed by the Game::FocusManager
singleton.
If you want the concept of an input focus in your application you should
derive your own input property classes from the InputProperty class,
because then the FocusManager will be aware of it (otherwise it will
just ignore the entity).
(C) 2007 Radon Labs GmbH
(C) 2013-2016 Individual contributors, see AUTHORS file
*/
#include "game/property.h"
#include "graphicsfeature/graphicsattr/graphicsattributes.h"
//------------------------------------------------------------------------------
namespace GraphicsFeature
{
class InputProperty : public Game::Property
{
__DeclareClass(InputProperty);
__SetupExternalAttributes();
public:
/// constructor
InputProperty();
/// destructor
virtual ~InputProperty();
/// setup accepted messages
virtual void SetupAcceptedMessages();
/// setup callbacks for this property
virtual void SetupCallbacks();
/// called from Entity::ActivateProperties()
virtual void OnActivate();
/// called from Entity::DeactivateProperties()
virtual void OnDeactivate();
/// called from within Entity::OnStart() after OnLoad when the complete world exist
virtual void OnStart();
/// called when input focus is gained
virtual void OnObtainInputFocus();
/// called when input focus is lost
virtual void OnLoseInputFocus();
/// return true if currently has input focus
virtual bool HasFocus() const;
/// called on begin of frame
virtual void OnBeginFrame();
/// handle a single message
virtual void HandleMessage(const Ptr<Messaging::Message>& msg);
// handle camera zoom in
virtual void OnCameraZoomIn();
// handle camera zoom out
virtual void OnCameraZoomOut();
private:
bool lastFrameSendMovement;
};
__RegisterClass(InputProperty);
}; // namespace Property
//------------------------------------------------------------------------------
| 0 | 0.780606 | 1 | 0.780606 | game-dev | MEDIA | 0.746294 | game-dev | 0.636654 | 1 | 0.636654 |
KernelOverseer/KSICARDOOM | 3,014 | sources/players/ft_client_player.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_players.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abiri <abiri@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/06 13:58:37 by msidqi #+# #+# */
/* Updated: 2020/10/24 20:02:10 by abiri ### ########.fr */
/* */
/* ************************************************************************** */
#include "doom_nukem.h"
/*
** to do: make ft_bodies_input take input from different sources (keyboard, bot, conected user)
*/
int ft_remote_client_player_input(void *env, void *body)
{
unsigned char *c;
unsigned char *k;
t_doom_env *e;
t_body *b;
t_multiplayer_client *client;
e = (t_doom_env *)env;
b = (t_body *)body;
c = b->player->input;
k = e->keys;
c[PLAYER_FORWARD] = (k[SDL_SCANCODE_UP]) ?
k[SDL_SCANCODE_UP] : k[SDL_SCANCODE_W];
c[PLAYER_BACKWARDS] = (k[SDL_SCANCODE_DOWN]) ?
k[SDL_SCANCODE_DOWN] : k[SDL_SCANCODE_S];
c[PLAYER_TURN_LEFT] = k[SDL_SCANCODE_LEFT];
c[PLAYER_TURN_RIGHT] = k[SDL_SCANCODE_RIGHT];
c[PLAYER_CROUCH] = k[SDL_SCANCODE_LSHIFT];
c[PLAYER_RUN] = k[SDL_SCANCODE_RSHIFT];
c[PLAYER_STRAFE_LEFT] = k[SDL_SCANCODE_A];
c[PLAYER_STRAFE_RIGHT] = k[SDL_SCANCODE_D];
c[PLAYER_JUMP] = k[SDL_SCANCODE_SPACE];
client = b->player->data;
int i = 0;
int is_moved = 0;
SDL_GetRelativeMouseState(&b->player->mouse_rel.x, &b->player->mouse_rel.y);
ft_memcpy(&b->player->mouse_buttons, e->mouse_buttons,
sizeof(b->player->mouse_buttons));
while (i < SDL_KEY_COUNT)
{
if (k[i])
{
is_moved = 1;
break;
}
i++;
}
ft_client_sync_body_input_server(b, client);
ft_client_sync_body_server(b, client);
ft_client_sync_scene_server(e, client);
sync_camera(env, body);
e->main_inventory = b->player->inventory;
return (1);
}
/*
** init player with NULL for non controlled bodies
*/
t_body *ft_client_player_construct(t_vec3 pos, void *player,
t_multiplayer_client *client)
{
t_body *body;
body = ft_memalloc(sizeof(t_body));
*body = ft_default_body(pos);
body->flags ^= ((player == NULL) ? IS_CONTROLLED : 0);
body->player = player;
body->player->data = client;
ft_create_player_sprite(player);
ft_fill_player_sprite_textures(g_parsed_scene, player,
g_parsed_scene->textures_count - 8, 8);
((t_player*)player)->sprite->parent = body;
((t_player*)player)->sprite->parent_type = PARENT_TYPE_BODY;
((t_player*)player)->inventory = (t_inventory){0, 100, 100, {20, 0, 0, 0, 0}};
body->up.z = -CONF_WINDOW_HEIGHT / 2;
return(body);
}
| 0 | 0.79077 | 1 | 0.79077 | game-dev | MEDIA | 0.81772 | game-dev | 0.851341 | 1 | 0.851341 |
LiuOcean/Luban_Example | 7,955 | Unity_Example/Assets/Scripts/Third/YooAsset/Editor/AssetBundleReporter/VisualViewers/ReporterAssetListViewer.cs | #if UNITY_2019_4_OR_NEWER
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace YooAsset.Editor
{
internal class ReporterAssetListViewer
{
private enum ESortMode
{
AssetPath,
BundleName
}
private VisualTreeAsset _visualAsset;
private TemplateContainer _root;
private ToolbarButton _topBar1;
private ToolbarButton _topBar2;
private ToolbarButton _bottomBar1;
private ListView _assetListView;
private ListView _dependListView;
private BuildReport _buildReport;
private string _searchKeyWord;
private ESortMode _sortMode = ESortMode.AssetPath;
private bool _descendingSort = false;
/// <summary>
/// 初始化页面
/// </summary>
public void InitViewer()
{
// 加载布局文件
_visualAsset = EditorHelper.LoadWindowUXML<ReporterAssetListViewer>();
if (_visualAsset == null)
return;
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
// 顶部按钮栏
_topBar1 = _root.Q<ToolbarButton>("TopBar1");
_topBar2 = _root.Q<ToolbarButton>("TopBar2");
_topBar1.clicked += TopBar1_clicked;
_topBar2.clicked += TopBar2_clicked;
// 底部按钮栏
_bottomBar1 = _root.Q<ToolbarButton>("BottomBar1");
// 资源列表
_assetListView = _root.Q<ListView>("TopListView");
_assetListView.makeItem = MakeAssetListViewItem;
_assetListView.bindItem = BindAssetListViewItem;
#if UNITY_2020_1_OR_NEWER
_assetListView.onSelectionChange += AssetListView_onSelectionChange;
#else
_assetListView.onSelectionChanged += AssetListView_onSelectionChange;
#endif
// 依赖列表
_dependListView = _root.Q<ListView>("BottomListView");
_dependListView.makeItem = MakeDependListViewItem;
_dependListView.bindItem = BindDependListViewItem;
}
/// <summary>
/// 填充页面数据
/// </summary>
public void FillViewData(BuildReport buildReport, string searchKeyWord)
{
_buildReport = buildReport;
_searchKeyWord = searchKeyWord;
RefreshView();
}
private void RefreshView()
{
_assetListView.Clear();
_assetListView.ClearSelection();
_assetListView.itemsSource = FilterAndSortViewItems();
_assetListView.Rebuild();
RefreshSortingSymbol();
}
private List<ReportAssetInfo> FilterAndSortViewItems()
{
List<ReportAssetInfo> result = new List<ReportAssetInfo>(_buildReport.AssetInfos.Count);
// 过滤列表
foreach (var assetInfo in _buildReport.AssetInfos)
{
if (string.IsNullOrEmpty(_searchKeyWord) == false)
{
if (assetInfo.AssetPath.Contains(_searchKeyWord) == false)
continue;
}
result.Add(assetInfo);
}
// 排序列表
if (_sortMode == ESortMode.AssetPath)
{
if (_descendingSort)
return result.OrderByDescending(a => a.AssetPath).ToList();
else
return result.OrderBy(a => a.AssetPath).ToList();
}
else if (_sortMode == ESortMode.BundleName)
{
if (_descendingSort)
return result.OrderByDescending(a => a.MainBundleName).ToList();
else
return result.OrderBy(a => a.MainBundleName).ToList();
}
else
{
throw new System.NotImplementedException();
}
}
private void RefreshSortingSymbol()
{
// 刷新符号
_topBar1.text = $"Asset Path ({_assetListView.itemsSource.Count})";
_topBar2.text = "Main Bundle";
if (_sortMode == ESortMode.AssetPath)
{
if (_descendingSort)
_topBar1.text = $"Asset Path ({_assetListView.itemsSource.Count}) ↓";
else
_topBar1.text = $"Asset Path ({_assetListView.itemsSource.Count}) ↑";
}
else if (_sortMode == ESortMode.BundleName)
{
if (_descendingSort)
_topBar2.text = "Main Bundle ↓";
else
_topBar2.text = "Main Bundle ↑";
}
else
{
throw new System.NotImplementedException();
}
}
/// <summary>
/// 挂接到父类页面上
/// </summary>
public void AttachParent(VisualElement parent)
{
parent.Add(_root);
}
/// <summary>
/// 从父类页面脱离开
/// </summary>
public void DetachParent()
{
_root.RemoveFromHierarchy();
}
// 资源列表相关
private VisualElement MakeAssetListViewItem()
{
VisualElement element = new VisualElement();
element.style.flexDirection = FlexDirection.Row;
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
label.style.flexGrow = 1f;
label.style.width = 280;
element.Add(label);
}
{
var label = new Label();
label.name = "Label2";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
return element;
}
private void BindAssetListViewItem(VisualElement element, int index)
{
var sourceData = _assetListView.itemsSource as List<ReportAssetInfo>;
var assetInfo = sourceData[index];
var bundleInfo = _buildReport.GetBundleInfo(assetInfo.MainBundleName);
// Asset Path
var label1 = element.Q<Label>("Label1");
label1.text = assetInfo.AssetPath;
// Main Bundle
var label2 = element.Q<Label>("Label2");
label2.text = bundleInfo.BundleName;
}
private void AssetListView_onSelectionChange(IEnumerable<object> objs)
{
foreach (var item in objs)
{
ReportAssetInfo assetInfo = item as ReportAssetInfo;
FillDependListView(assetInfo);
}
}
private void TopBar1_clicked()
{
if (_sortMode != ESortMode.AssetPath)
{
_sortMode = ESortMode.AssetPath;
_descendingSort = false;
RefreshView();
}
else
{
_descendingSort = !_descendingSort;
RefreshView();
}
}
private void TopBar2_clicked()
{
if (_sortMode != ESortMode.BundleName)
{
_sortMode = ESortMode.BundleName;
_descendingSort = false;
RefreshView();
}
else
{
_descendingSort = !_descendingSort;
RefreshView();
}
}
// 依赖列表相关
private void FillDependListView(ReportAssetInfo assetInfo)
{
List<ReportBundleInfo> bundles = new List<ReportBundleInfo>();
var mainBundle = _buildReport.GetBundleInfo(assetInfo.MainBundleName);
bundles.Add(mainBundle);
foreach (string dependBundleName in assetInfo.DependBundles)
{
var dependBundle = _buildReport.GetBundleInfo(dependBundleName);
bundles.Add(dependBundle);
}
_dependListView.Clear();
_dependListView.ClearSelection();
_dependListView.itemsSource = bundles;
_dependListView.Rebuild();
_bottomBar1.text = $"Depend Bundles ({bundles.Count})";
}
private VisualElement MakeDependListViewItem()
{
VisualElement element = new VisualElement();
element.style.flexDirection = FlexDirection.Row;
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
label.style.flexGrow = 1f;
label.style.width = 280;
element.Add(label);
}
{
var label = new Label();
label.name = "Label2";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
element.Add(label);
}
{
var label = new Label();
label.name = "Label3";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 280;
element.Add(label);
}
return element;
}
private void BindDependListViewItem(VisualElement element, int index)
{
List<ReportBundleInfo> bundles = _dependListView.itemsSource as List<ReportBundleInfo>;
ReportBundleInfo bundleInfo = bundles[index];
// Bundle Name
var label1 = element.Q<Label>("Label1");
label1.text = bundleInfo.BundleName;
// Size
var label2 = element.Q<Label>("Label2");
label2.text = EditorUtility.FormatBytes(bundleInfo.FileSize);
// Hash
var label3 = element.Q<Label>("Label3");
label3.text = bundleInfo.FileHash;
}
}
}
#endif | 0 | 0.913486 | 1 | 0.913486 | game-dev | MEDIA | 0.512185 | game-dev,desktop-app | 0.981995 | 1 | 0.981995 |
chsami/Microbot | 4,252 | runelite-client/src/main/java/net/runelite/client/plugins/tithefarm/TitheFarmPlantOverlay.java | /*
* Copyright (c) 2018, Unmoon <https://github.com/Unmoon>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*/
package net.runelite.client.plugins.tithefarm;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.Perspective;
import net.runelite.api.Point;
import net.runelite.api.coords.LocalPoint;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.components.ProgressPieComponent;
import net.runelite.client.util.ColorUtil;
public class TitheFarmPlantOverlay extends Overlay
{
private final Client client;
private final TitheFarmPlugin plugin;
private final TitheFarmPluginConfig config;
private final Map<TitheFarmPlantState, Color> borders = new HashMap<>();
private final Map<TitheFarmPlantState, Color> fills = new HashMap<>();
@Inject
TitheFarmPlantOverlay(Client client, TitheFarmPlugin plugin, TitheFarmPluginConfig config)
{
setPosition(OverlayPosition.DYNAMIC);
setLayer(OverlayLayer.ABOVE_SCENE);
this.plugin = plugin;
this.config = config;
this.client = client;
}
/**
* Updates the timer colors.
*/
public void updateConfig()
{
borders.clear();
fills.clear();
final Color colorUnwateredBorder = config.getColorUnwatered();
final Color colorUnwatered = ColorUtil.colorWithAlpha(colorUnwateredBorder, (int) (colorUnwateredBorder.getAlpha() / 2.5));
borders.put(TitheFarmPlantState.UNWATERED, colorUnwateredBorder);
fills.put(TitheFarmPlantState.UNWATERED, colorUnwatered);
final Color colorWateredBorder = config.getColorWatered();
final Color colorWatered = ColorUtil.colorWithAlpha(colorWateredBorder, (int) (colorWateredBorder.getAlpha() / 2.5));
borders.put(TitheFarmPlantState.WATERED, colorWateredBorder);
fills.put(TitheFarmPlantState.WATERED, colorWatered);
}
@Override
public Dimension render(Graphics2D graphics)
{
for (TitheFarmPlant plant : plugin.getPlants())
{
if (plant.getState() == TitheFarmPlantState.DEAD || plant.getState() == TitheFarmPlantState.GROWN)
{
continue;
}
final LocalPoint localLocation = LocalPoint.fromWorld(client, plant.getWorldLocation());
if (localLocation == null)
{
continue;
}
final Point canvasLocation = Perspective.localToCanvas(client, localLocation, client.getPlane());
if (canvasLocation != null)
{
final ProgressPieComponent progressPieComponent = new ProgressPieComponent();
progressPieComponent.setPosition(canvasLocation);
progressPieComponent.setProgress(1 - plant.getPlantTimeRelative());
progressPieComponent.setBorderColor(borders.get(plant.getState()));
progressPieComponent.setFill(fills.get(plant.getState()));
progressPieComponent.render(graphics);
}
}
return null;
}
}
| 0 | 0.877665 | 1 | 0.877665 | game-dev | MEDIA | 0.696142 | game-dev,desktop-app | 0.980723 | 1 | 0.980723 |
bradharding/doomretro | 30,059 | xcode/SDL2.framework/Versions/A/Headers/SDL_joystick.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_joystick.h
*
* Include file for SDL joystick event handling
*
* The term "device_index" identifies currently plugged in joystick devices between 0 and SDL_NumJoysticks(), with the exact joystick
* behind a device_index changing as joysticks are plugged and unplugged.
*
* The term "instance_id" is the current instantiation of a joystick device in the system, if the joystick is removed and then re-inserted
* then it will get a new instance_id, instance_id's are monotonically increasing identifiers of a joystick plugged in.
*
* The term "player_index" is the number assigned to a player on a specific
* controller. For XInput controllers this returns the XInput user index.
* Many joysticks will not be able to supply this information.
*
* The term JoystickGUID is a stable 128-bit identifier for a joystick device that does not change over time, it identifies class of
* the device (a X360 wired controller for example). This identifier is platform dependent.
*/
#ifndef SDL_joystick_h_
#define SDL_joystick_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_joystick.h
*
* In order to use these functions, SDL_Init() must have been called
* with the ::SDL_INIT_JOYSTICK flag. This causes SDL to scan the system
* for joysticks, and load appropriate drivers.
*
* If you would like to receive joystick updates while the application
* is in the background, you should set the following hint before calling
* SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
*/
/**
* The joystick structure used to identify an SDL joystick
*/
struct _SDL_Joystick;
typedef struct _SDL_Joystick SDL_Joystick;
/* A structure that encodes the stable unique id for a joystick device */
typedef struct {
Uint8 data[16];
} SDL_JoystickGUID;
/**
* This is a unique ID for a joystick for the time it is connected to the system,
* and is never reused for the lifetime of the application. If the joystick is
* disconnected and reconnected, it will get a new ID.
*
* The ID value starts at 0 and increments from there. The value -1 is an invalid ID.
*/
typedef Sint32 SDL_JoystickID;
typedef enum
{
SDL_JOYSTICK_TYPE_UNKNOWN,
SDL_JOYSTICK_TYPE_GAMECONTROLLER,
SDL_JOYSTICK_TYPE_WHEEL,
SDL_JOYSTICK_TYPE_ARCADE_STICK,
SDL_JOYSTICK_TYPE_FLIGHT_STICK,
SDL_JOYSTICK_TYPE_DANCE_PAD,
SDL_JOYSTICK_TYPE_GUITAR,
SDL_JOYSTICK_TYPE_DRUM_KIT,
SDL_JOYSTICK_TYPE_ARCADE_PAD,
SDL_JOYSTICK_TYPE_THROTTLE
} SDL_JoystickType;
typedef enum
{
SDL_JOYSTICK_POWER_UNKNOWN = -1,
SDL_JOYSTICK_POWER_EMPTY, /* <= 5% */
SDL_JOYSTICK_POWER_LOW, /* <= 20% */
SDL_JOYSTICK_POWER_MEDIUM, /* <= 70% */
SDL_JOYSTICK_POWER_FULL, /* <= 100% */
SDL_JOYSTICK_POWER_WIRED,
SDL_JOYSTICK_POWER_MAX
} SDL_JoystickPowerLevel;
/* Set max recognized G-force from accelerometer
See src/joystick/uikit/SDL_sysjoystick.m for notes on why this is needed
*/
#define SDL_IPHONE_MAX_GFORCE 5.0
/* Function prototypes */
/**
* Locking for multi-threaded access to the joystick API
*
* If you are using the joystick API or handling events from multiple threads
* you should use these locking functions to protect access to the joysticks.
*
* In particular, you are guaranteed that the joystick list won't change, so
* the API functions that take a joystick index will be valid, and joystick
* and game controller events will not be delivered.
*/
extern DECLSPEC void SDLCALL SDL_LockJoysticks(void);
/**
* Unlocking for multi-threaded access to the joystick API
*
* If you are using the joystick API or handling events from multiple threads
* you should use these locking functions to protect access to the joysticks.
*
* In particular, you are guaranteed that the joystick list won't change, so
* the API functions that take a joystick index will be valid, and joystick
* and game controller events will not be delivered.
*/
extern DECLSPEC void SDLCALL SDL_UnlockJoysticks(void);
/**
* Count the number of joysticks attached to the system.
*
* \returns the number of attached joysticks on success or a negative error
* code on failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickName
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_NumJoysticks(void);
/**
* Get the implementation dependent name of a joystick.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system)
* \returns the name of the selected joystick. If no name can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \sa SDL_JoystickName
* \sa SDL_JoystickOpen
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickNameForIndex(int device_index);
/**
* Get the player index of a joystick, or -1 if it's not available This can be
* called before any joysticks are opened.
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetDevicePlayerIndex(int device_index);
/**
* Get the implementation-dependent GUID for the joystick at a given device
* index.
*
* This function can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the GUID of the selected joystick. If called on an invalid index,
* this function returns a zero GUID
*
* \sa SDL_JoystickGetGUID
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index);
/**
* Get the USB vendor ID of a joystick, if available.
*
* This can be called before any joysticks are opened. If the vendor ID isn't
* available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the USB vendor ID of the selected joystick. If called on an
* invalid index, this function returns zero
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceVendor(int device_index);
/**
* Get the USB product ID of a joystick, if available.
*
* This can be called before any joysticks are opened. If the product ID isn't
* available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the USB product ID of the selected joystick. If called on an
* invalid index, this function returns zero
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProduct(int device_index);
/**
* Get the product version of a joystick, if available.
*
* This can be called before any joysticks are opened. If the product version
* isn't available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the product version of the selected joystick. If called on an
* invalid index, this function returns zero
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProductVersion(int device_index);
/**
* Get the type of a joystick, if available.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the SDL_JoystickType of the selected joystick. If called on an
* invalid index, this function returns `SDL_JOYSTICK_TYPE_UNKNOWN`
*/
extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetDeviceType(int device_index);
/**
* Get the instance ID of a joystick.
*
* This can be called before any joysticks are opened. If the index is out of
* range, this function will return -1.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the instance id of the selected joystick. If called on an invalid
* index, this function returns zero
*/
extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickGetDeviceInstanceID(int device_index);
/**
* Open a joystick for use.
*
* The `device_index` argument refers to the N'th joystick presently
* recognized by SDL on the system. It is **NOT** the same as the instance ID
* used to identify the joystick in future events. See
* SDL_JoystickInstanceID() for more details about instance IDs.
*
* The joystick subsystem must be initialized before a joystick can be opened
* for use.
*
* \param device_index the index of the joystick to query
* \returns a joystick identifier or NULL if an error occurred; call
* SDL_GetError() for more information.
*
* \sa SDL_JoystickClose
* \sa SDL_JoystickInstanceID
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index);
/**
* Get the SDL_Joystick associated with an instance id.
*
* \param instance_id the instance id to get the SDL_Joystick for
* \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError()
* for more information.
*
* \since This function is available since SDL 2.0.4.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromInstanceID(SDL_JoystickID instance_id);
/**
* Get the SDL_Joystick associated with a player index.
*
* \param player_index the player index to get the SDL_Joystick for
* \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError()
* for more information.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromPlayerIndex(int player_index);
/**
* Attach a new virtual joystick.
*
* \returns the joystick's device index, or -1 if an error occurred.
*/
extern DECLSPEC int SDLCALL SDL_JoystickAttachVirtual(SDL_JoystickType type,
int naxes,
int nbuttons,
int nhats);
/**
* Detach a virtual joystick.
*
* \param device_index a value previously returned from
* SDL_JoystickAttachVirtual()
* \returns 0 on success, or -1 if an error occurred.
*/
extern DECLSPEC int SDLCALL SDL_JoystickDetachVirtual(int device_index);
/**
* Query whether or not the joystick at a given device index is virtual.
*
* \param device_index a joystick device index.
* \returns SDL_TRUE if the joystick is virtual, SDL_FALSE otherwise.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickIsVirtual(int device_index);
/**
* Set values on an opened, virtual-joystick's axis.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* \param joystick the virtual joystick on which to set state.
* \param axis the specific axis on the virtual joystick to set.
* \param value the new value for the specified axis.
* \returns 0 on success, -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualAxis(SDL_Joystick *joystick, int axis, Sint16 value);
/**
* Set values on an opened, virtual-joystick's button.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* \param joystick the virtual joystick on which to set state.
* \param button the specific button on the virtual joystick to set.
* \param value the new value for the specified button.
* \returns 0 on success, -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualButton(SDL_Joystick *joystick, int button, Uint8 value);
/**
* Set values on an opened, virtual-joystick's hat.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* \param joystick the virtual joystick on which to set state.
* \param hat the specific hat on the virtual joystick to set.
* \param value the new value for the specified hat.
* \returns 0 on success, -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualHat(SDL_Joystick *joystick, int hat, Uint8 value);
/**
* Get the implementation dependent name of a joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the name of the selected joystick. If no name can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNameForIndex
* \sa SDL_JoystickOpen
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickName(SDL_Joystick *joystick);
/**
* Get the player index of an opened joystick.
*
* For XInput controllers this returns the XInput user index. Many joysticks
* will not be able to supply this information.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the player index, or -1 if it's not available.
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetPlayerIndex(SDL_Joystick *joystick);
/**
* Set the player index of an opened joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \param player_index the player index to set.
*/
extern DECLSPEC void SDLCALL SDL_JoystickSetPlayerIndex(SDL_Joystick *joystick, int player_index);
/**
* Get the implementation-dependent GUID for the joystick.
*
* This function requires an open joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the GUID of the given joystick. If called on an invalid index,
* this function returns a zero GUID; call SDL_GetError() for more
* information.
*
* \sa SDL_JoystickGetDeviceGUID
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick *joystick);
/**
* Get the USB vendor ID of an opened joystick, if available.
*
* If the vendor ID isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the USB vendor ID of the selected joystick, or 0 if unavailable.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetVendor(SDL_Joystick *joystick);
/**
* Get the USB product ID of an opened joystick, if available.
*
* If the product ID isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the USB product ID of the selected joystick, or 0 if unavailable.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProduct(SDL_Joystick *joystick);
/**
* Get the product version of an opened joystick, if available.
*
* If the product version isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the product version of the selected joystick, or 0 if unavailable.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProductVersion(SDL_Joystick *joystick);
/**
* Get the serial number of an opened joystick, if available.
*
* Returns the serial number of the joystick, or NULL if it is not available.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the serial number of the selected joystick, or NULL if
* unavailable.
*/
extern DECLSPEC const char * SDLCALL SDL_JoystickGetSerial(SDL_Joystick *joystick);
/**
* Get the type of an opened joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the SDL_JoystickType of the selected joystick.
*/
extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetType(SDL_Joystick *joystick);
/**
* Get an ASCII string representation for a given SDL_JoystickGUID.
*
* You should supply at least 33 bytes for pszGUID.
*
* \param guid the SDL_JoystickGUID you wish to convert to string
* \param pszGUID buffer in which to write the ASCII string
* \param cbGUID the size of pszGUID
*
* \sa SDL_JoystickGetDeviceGUID
* \sa SDL_JoystickGetGUID
* \sa SDL_JoystickGetGUIDFromString
*/
extern DECLSPEC void SDLCALL SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID);
/**
* Convert a GUID string into a SDL_JoystickGUID structure.
*
* Performs no error checking. If this function is given a string containing
* an invalid GUID, the function will silently succeed, but the GUID generated
* will not be useful.
*
* \param pchGUID string containing an ASCII representation of a GUID
* \returns a SDL_JoystickGUID structure.
*
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUIDFromString(const char *pchGUID);
/**
* Get the status of a specified joystick.
*
* \param joystick the joystick to query
* \returns SDL_TRUE if the joystick has been opened, SDL_FALSE if it has not;
* call SDL_GetError() for more information.
*
* \sa SDL_JoystickClose
* \sa SDL_JoystickOpen
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAttached(SDL_Joystick *joystick);
/**
* Get the instance ID of an opened joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the instance ID of the specified joystick on success or a negative
* error code on failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickOpen
*/
extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickInstanceID(SDL_Joystick *joystick);
/**
* Get the number of general axis controls on a joystick.
*
* Often, the directional pad on a game controller will either look like 4
* separate buttons or a POV hat, and not axes, but all of this is up to the
* device and platform.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of axis controls/number of axes on success or a
* negative error code on failure; call SDL_GetError() for more
* information.
*
* \sa SDL_JoystickGetAxis
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick);
/**
* Get the number of trackballs on a joystick.
*
* Joystick trackballs have only relative motion events associated with them
* and their state cannot be polled.
*
* Most joysticks do not have trackballs.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of trackballs on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickGetBall
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick);
/**
* Get the number of POV hats on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of POV hats on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickGetHat
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick);
/**
* Get the number of buttons on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of buttons on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickGetButton
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick);
/**
* Update the current state of the open joysticks.
*
* This is called automatically by the event loop if any joystick events are
* enabled.
*
* \sa SDL_JoystickEventState
*/
extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void);
/**
* Enable/disable joystick event polling.
*
* If joystick events are disabled, you must call SDL_JoystickUpdate()
* yourself and manually check the state of the joystick when you want
* joystick information.
*
* It is recommended that you leave joystick event handling enabled.
*
* **WARNING**: Calling this function may delete all events currently in SDL's
* event queue.
*
* \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE`
* \returns 1 if enabled, 0 if disabled, or a negative error code on failure;
* call SDL_GetError() for more information.
*
* If `state` is `SDL_QUERY` then the current state is returned,
* otherwise the new processing state is returned.
*
* \sa SDL_GameControllerEventState
*/
extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state);
#define SDL_JOYSTICK_AXIS_MAX 32767
#define SDL_JOYSTICK_AXIS_MIN -32768
/**
* Get the current state of an axis control on a joystick.
*
* SDL makes no promises about what part of the joystick any given axis refers
* to. Your game should have some sort of configuration UI to let users
* specify what each axis should be bound to. Alternately, SDL's higher-level
* Game Controller API makes a great effort to apply order to this lower-level
* interface, so you know that a specific axis is the "left thumb stick," etc.
*
* The value returned by SDL_JoystickGetAxis() is a signed integer (-32768 to
* 32767) representing the current position of the axis. It may be necessary
* to impose certain tolerances on these values to account for jitter.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param axis the axis to query; the axis indices start at index 0
* \returns a 16-bit signed integer representing the current position of the
* axis or 0 on failure; call SDL_GetError() for more information.
*
* \sa SDL_JoystickNumAxes
*/
extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick,
int axis);
/**
* Get the initial state of an axis control on a joystick.
*
* The state is a value ranging from -32768 to 32767.
*
* The axis indices start at index 0.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param axis the axis to query; the axis indices start at index 0
* \param state Upon return, the initial value is supplied here.
* \return SDL_TRUE if this axis has any initial value, or SDL_FALSE if not.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAxisInitialState(SDL_Joystick *joystick,
int axis, Sint16 *state);
/**
* \name Hat positions
*/
/* @{ */
#define SDL_HAT_CENTERED 0x00
#define SDL_HAT_UP 0x01
#define SDL_HAT_RIGHT 0x02
#define SDL_HAT_DOWN 0x04
#define SDL_HAT_LEFT 0x08
#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP)
#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN)
#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP)
#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN)
/* @} */
/**
* Get the current state of a POV hat on a joystick.
*
* The returned value will be one of the following positions:
*
* - `SDL_HAT_CENTERED`
* - `SDL_HAT_UP`
* - `SDL_HAT_RIGHT`
* - `SDL_HAT_DOWN`
* - `SDL_HAT_LEFT`
* - `SDL_HAT_RIGHTUP`
* - `SDL_HAT_RIGHTDOWN`
* - `SDL_HAT_LEFTUP`
* - `SDL_HAT_LEFTDOWN`
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param hat the hat index to get the state from; indices start at index 0
* \returns the current hat position.
*
* \sa SDL_JoystickNumHats
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick,
int hat);
/**
* Get the ball axis change since the last poll.
*
* Trackballs can only return relative motion since the last call to
* SDL_JoystickGetBall(), these motion deltas are placed into `dx` and `dy`.
*
* Most joysticks do not have trackballs.
*
* \param joystick the SDL_Joystick to query
* \param ball the ball index to query; ball indices start at index 0
* \param dx stores the difference in the x axis position since the last poll
* \param dy stores the difference in the y axis position since the last poll
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \sa SDL_JoystickNumBalls
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick,
int ball, int *dx, int *dy);
/**
* Get the current state of a button on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param button the button index to get the state from; indices start at
* index 0
* \returns 1 if the specified button is pressed, 0 otherwise.
*
* \sa SDL_JoystickNumButtons
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick,
int button);
/**
* Start a rumble effect.
*
* Each call to this function cancels any previous rumble effect, and calling
* it with 0 intensity stops any rumbling.
*
* \param joystick The joystick to vibrate
* \param low_frequency_rumble The intensity of the low frequency (left)
* rumble motor, from 0 to 0xFFFF
* \param high_frequency_rumble The intensity of the high frequency (right)
* rumble motor, from 0 to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if rumble isn't supported on this joystick
*/
extern DECLSPEC int SDLCALL SDL_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms);
/**
* Start a rumble effect in the joystick's triggers
*
* Each call to this function cancels any previous trigger rumble effect, and
* calling it with 0 intensity stops any rumbling.
*
* Note that this function is for _trigger_ rumble; the first joystick to
* support this was the PlayStation 5's DualShock 5 controller. If you want
* the (more common) whole-controller rumble, use SDL_JoystickRumble()
* instead.
*
* \param joystick The joystick to vibrate
* \param left_rumble The intensity of the left trigger rumble motor, from 0
* to 0xFFFF
* \param right_rumble The intensity of the right trigger rumble motor, from 0
* to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if trigger rumble isn't supported on this joystick
*/
extern DECLSPEC int SDLCALL SDL_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms);
/**
* Query whether a joystick has an LED.
*
* An example of a joystick LED is the light on the back of a PlayStation 4's
* DualShock 4 controller.
*
* \param joystick The joystick to query
* \return SDL_TRUE if the joystick has a modifiable LED, SDL_FALSE otherwise.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasLED(SDL_Joystick *joystick);
/**
* Update a joystick's LED color.
*
* An example of a joystick LED is the light on the back of a PlayStation 4's
* DualShock 4 controller.
*
* \param joystick The joystick to update
* \param red The intensity of the red LED
* \param green The intensity of the green LED
* \param blue The intensity of the blue LED
* \returns 0 on success, -1 if this joystick does not have a modifiable LED
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue);
/**
* Send a joystick specific effect packet
*
* \param joystick The joystick to affect
* \param data The data to send to the joystick
* \param size The size of the data to send to the joystick
* \returns 0, or -1 if this joystick or driver doesn't support effect packets
*/
extern DECLSPEC int SDLCALL SDL_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size);
/**
* Close a joystick previously opened with SDL_JoystickOpen().
*
* \param joystick The joystick device to close
*
* \sa SDL_JoystickOpen
*/
extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick);
/**
* Get the battery level of a joystick as SDL_JoystickPowerLevel.
*
* \param joystick the SDL_Joystick to query
* \returns the current battery level as SDL_JoystickPowerLevel on success or
* `SDL_JOYSTICK_POWER_UNKNOWN` if it is unknown
*
* \since This function is available since SDL 2.0.4.
*/
extern DECLSPEC SDL_JoystickPowerLevel SDLCALL SDL_JoystickCurrentPowerLevel(SDL_Joystick *joystick);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_joystick_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.740098 | 1 | 0.740098 | game-dev | MEDIA | 0.945284 | game-dev,drivers | 0.627575 | 1 | 0.627575 |
FallingColors/HexMod | 1,273 | Common/src/main/java/at/petrak/hexcasting/api/casting/castables/OperationAction.kt | package at.petrak.hexcasting.api.casting.castables
import at.petrak.hexcasting.api.casting.arithmetic.engine.NoOperatorCandidatesException
import at.petrak.hexcasting.api.casting.eval.CastingEnvironment
import at.petrak.hexcasting.api.casting.eval.OperationResult
import at.petrak.hexcasting.api.casting.eval.vm.CastingImage
import at.petrak.hexcasting.api.casting.eval.vm.SpellContinuation
import at.petrak.hexcasting.api.casting.math.HexPattern
import at.petrak.hexcasting.api.casting.mishaps.MishapInvalidOperatorArgs
import at.petrak.hexcasting.common.lib.hex.HexArithmetics
/**
* Represents an Operator with the give pattern as its identifier, a special type of Action that calls a different function depending on the type of its arguments.
* This exists so that addons can easily define their own overloads to patterns like addition, subtraction, etc.
*/
data class OperationAction(val pattern: HexPattern) : Action {
override fun operate(env: CastingEnvironment, image: CastingImage, continuation: SpellContinuation): OperationResult {
return try {
HexArithmetics.getEngine().run(pattern, env, image, continuation)
} catch (e: NoOperatorCandidatesException) {
throw MishapInvalidOperatorArgs(e.args)
}
}
} | 0 | 0.713782 | 1 | 0.713782 | game-dev | MEDIA | 0.345109 | game-dev | 0.624048 | 1 | 0.624048 |
Froser/gamemachine | 5,288 | src/3rdparty/bullet3-2.87/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SIMPLE_BROADPHASE_H
#define BT_SIMPLE_BROADPHASE_H
#include "btOverlappingPairCache.h"
struct btSimpleBroadphaseProxy : public btBroadphaseProxy
{
int m_nextFree;
// int m_handleId;
btSimpleBroadphaseProxy() {};
btSimpleBroadphaseProxy(const btVector3& minpt,const btVector3& maxpt,int shapeType,void* userPtr, int collisionFilterGroup, int collisionFilterMask)
:btBroadphaseProxy(minpt,maxpt,userPtr,collisionFilterGroup,collisionFilterMask)
{
(void)shapeType;
}
SIMD_FORCE_INLINE void SetNextFree(int next) {m_nextFree = next;}
SIMD_FORCE_INLINE int GetNextFree() const {return m_nextFree;}
};
///The SimpleBroadphase is just a unit-test for btAxisSweep3, bt32BitAxisSweep3, or btDbvtBroadphase, so use those classes instead.
///It is a brute force aabb culling broadphase based on O(n^2) aabb checks
class btSimpleBroadphase : public btBroadphaseInterface
{
protected:
int m_numHandles; // number of active handles
int m_maxHandles; // max number of handles
int m_LastHandleIndex;
btSimpleBroadphaseProxy* m_pHandles; // handles pool
void* m_pHandlesRawPtr;
int m_firstFreeHandle; // free handles list
int allocHandle()
{
btAssert(m_numHandles < m_maxHandles);
int freeHandle = m_firstFreeHandle;
m_firstFreeHandle = m_pHandles[freeHandle].GetNextFree();
m_numHandles++;
if(freeHandle > m_LastHandleIndex)
{
m_LastHandleIndex = freeHandle;
}
return freeHandle;
}
void freeHandle(btSimpleBroadphaseProxy* proxy)
{
int handle = int(proxy-m_pHandles);
btAssert(handle >= 0 && handle < m_maxHandles);
if(handle == m_LastHandleIndex)
{
m_LastHandleIndex--;
}
proxy->SetNextFree(m_firstFreeHandle);
m_firstFreeHandle = handle;
proxy->m_clientObject = 0;
m_numHandles--;
}
btOverlappingPairCache* m_pairCache;
bool m_ownsPairCache;
int m_invalidPair;
inline btSimpleBroadphaseProxy* getSimpleProxyFromProxy(btBroadphaseProxy* proxy)
{
btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(proxy);
return proxy0;
}
inline const btSimpleBroadphaseProxy* getSimpleProxyFromProxy(btBroadphaseProxy* proxy) const
{
const btSimpleBroadphaseProxy* proxy0 = static_cast<const btSimpleBroadphaseProxy*>(proxy);
return proxy0;
}
///reset broadphase internal structures, to ensure determinism/reproducability
virtual void resetPool(btDispatcher* dispatcher);
void validate();
protected:
public:
btSimpleBroadphase(int maxProxies=16384,btOverlappingPairCache* overlappingPairCache=0);
virtual ~btSimpleBroadphase();
static bool aabbOverlap(btSimpleBroadphaseProxy* proxy0,btSimpleBroadphaseProxy* proxy1);
virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr , int collisionFilterGroup, int collisionFilterMask, btDispatcher* dispatcher);
virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher);
virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0),const btVector3& aabbMax=btVector3(0,0,0));
virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
btOverlappingPairCache* getOverlappingPairCache()
{
return m_pairCache;
}
const btOverlappingPairCache* getOverlappingPairCache() const
{
return m_pairCache;
}
bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
///getAabb returns the axis aligned bounding box in the 'global' coordinate frame
///will add some transform later
virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
{
aabbMin.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT);
aabbMax.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
}
virtual void printStats()
{
// printf("btSimpleBroadphase.h\n");
// printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles);
}
};
#endif //BT_SIMPLE_BROADPHASE_H
| 0 | 0.964598 | 1 | 0.964598 | game-dev | MEDIA | 0.908187 | game-dev | 0.981869 | 1 | 0.981869 |
dguenms/Dawn-of-Civilization | 92,474 | CvGameCoreDLL/CyEnumsInterface.cpp | #include "CvGameCoreDLL.h"
#include"CvEnums.h"
#include "CvGameCoreDLLUnDefNew.h"
# include <boost/python/enum.hpp>
#include "CvGameCoreDLLDefNew.h"
//
// Python interface for free enums
//
void CyEnumsPythonInterface()
{
OutputDebugString("Python Extension Module - CyEnumsPythonInterface\n");
python::enum_<GameStateTypes>("GameStateTypes")
.value("GAMESTATE_ON", GAMESTATE_ON)
.value("GAMESTATE_OVER", GAMESTATE_OVER)
.value("GAMESTATE_EXTENDED", GAMESTATE_EXTENDED)
;
python::enum_<PopupStates>("PopupStates")
.value("POPUPSTATE_IMMEDIATE", POPUPSTATE_IMMEDIATE)
.value("POPUPSTATE_QUEUED", POPUPSTATE_QUEUED)
.value("POPUPSTATE_MINIMIZED", POPUPSTATE_MINIMIZED)
;
python::enum_<CameraLookAtTypes>("CameraLookAtTypes")
.value("CAMERALOOKAT_NORMAL", CAMERALOOKAT_NORMAL)
.value("CAMERALOOKAT_CITY_ZOOM_IN", CAMERALOOKAT_CITY_ZOOM_IN)
.value("CAMERALOOKAT_BATTLE", CAMERALOOKAT_BATTLE)
.value("CAMERALOOKAT_BATTLE_ZOOM_IN", CAMERALOOKAT_BATTLE_ZOOM_IN)
.value("CAMERALOOKAT_IMMEDIATE", CAMERALOOKAT_IMMEDIATE)
;
python::enum_<CameraMovementSpeeds>("CameraMovementSpeeds")
.value("CAMERAMOVEMENTSPEED_NORMAL", CAMERAMOVEMENTSPEED_NORMAL)
.value("CAMERAMOVEMENTSPEED_SLOW", CAMERAMOVEMENTSPEED_SLOW)
.value("CAMERAMOVEMENTSPEED_FAST", CAMERAMOVEMENTSPEED_FAST)
;
python::enum_<ZoomLevelTypes>("ZoomLevelTypes")
.value("ZOOM_UNKNOWN", ZOOM_UNKNOWN)
.value("ZOOM_GLOBEVIEW", ZOOM_GLOBEVIEW)
.value("ZOOM_NORMAL", ZOOM_NORMAL)
.value("ZOOM_DETAIL", ZOOM_DETAIL)
;
python::enum_<DirectionTypes>("DirectionTypes")
.value("NO_DIRECTION", NO_DIRECTION)
.value("DIRECTION_NORTH", DIRECTION_NORTH)
.value("DIRECTION_NORTHEAST", DIRECTION_NORTHEAST)
.value("DIRECTION_EAST", DIRECTION_EAST)
.value("DIRECTION_SOUTHEAST", DIRECTION_SOUTHEAST)
.value("DIRECTION_SOUTH", DIRECTION_SOUTH)
.value("DIRECTION_SOUTHWEST", DIRECTION_SOUTHWEST)
.value("DIRECTION_WEST", DIRECTION_WEST)
.value("DIRECTION_NORTHWEST", DIRECTION_NORTHWEST)
.value("NUM_DIRECTION_TYPES", NUM_DIRECTION_TYPES)
;
python::enum_<CardinalDirectionTypes>("CardinalDirectionTypes")
.value("NO_CARDINALDIRECTION", NO_CARDINALDIRECTION)
.value("CARDINALDIRECTION_NORTH", CARDINALDIRECTION_NORTH)
.value("CARDINALDIRECTION_EAST", CARDINALDIRECTION_EAST)
.value("CARDINALDIRECTION_SOUTH", CARDINALDIRECTION_SOUTH)
.value("CARDINALDIRECTION_WEST", CARDINALDIRECTION_WEST)
.value("NUM_CARDINALDIRECTION_TYPES", NUM_CARDINALDIRECTION_TYPES)
;
python::enum_<ColorTypes>("ColorTypes")
.value("NO_COLOR", NO_COLOR)
;
python::enum_<PlayerColorTypes>("PlayerColorTypes")
.value("NO_PLAYERCOLOR", NO_PLAYERCOLOR)
;
python::enum_<PlotStyles>("PlotStyles")
.value("PLOT_STYLE_NONE", PLOT_STYLE_NONE)
.value("PLOT_STYLE_NUMPAD_1", PLOT_STYLE_NUMPAD_1)
.value("PLOT_STYLE_NUMPAD_2", PLOT_STYLE_NUMPAD_2)
.value("PLOT_STYLE_NUMPAD_3", PLOT_STYLE_NUMPAD_3)
.value("PLOT_STYLE_NUMPAD_4", PLOT_STYLE_NUMPAD_4)
.value("PLOT_STYLE_NUMPAD_6", PLOT_STYLE_NUMPAD_6)
.value("PLOT_STYLE_NUMPAD_7", PLOT_STYLE_NUMPAD_7)
.value("PLOT_STYLE_NUMPAD_8", PLOT_STYLE_NUMPAD_8)
.value("PLOT_STYLE_NUMPAD_9", PLOT_STYLE_NUMPAD_9)
.value("PLOT_STYLE_NUMPAD_1_ANGLED", PLOT_STYLE_NUMPAD_1_ANGLED)
.value("PLOT_STYLE_NUMPAD_2_ANGLED", PLOT_STYLE_NUMPAD_2_ANGLED)
.value("PLOT_STYLE_NUMPAD_3_ANGLED", PLOT_STYLE_NUMPAD_3_ANGLED)
.value("PLOT_STYLE_NUMPAD_4_ANGLED", PLOT_STYLE_NUMPAD_4_ANGLED)
.value("PLOT_STYLE_NUMPAD_6_ANGLED", PLOT_STYLE_NUMPAD_6_ANGLED)
.value("PLOT_STYLE_NUMPAD_7_ANGLED", PLOT_STYLE_NUMPAD_7_ANGLED)
.value("PLOT_STYLE_NUMPAD_8_ANGLED", PLOT_STYLE_NUMPAD_8_ANGLED)
.value("PLOT_STYLE_NUMPAD_9_ANGLED", PLOT_STYLE_NUMPAD_9_ANGLED)
.value("PLOT_STYLE_BOX_FILL", PLOT_STYLE_BOX_FILL)
.value("PLOT_STYLE_BOX_OUTLINE", PLOT_STYLE_BOX_OUTLINE)
.value("PLOT_STYLE_RIVER_SOUTH", PLOT_STYLE_RIVER_SOUTH)
.value("PLOT_STYLE_RIVER_EAST", PLOT_STYLE_RIVER_EAST)
.value("PLOT_STYLE_SIDE_ARROWS", PLOT_STYLE_SIDE_ARROWS)
.value("PLOT_STYLE_CIRCLE", PLOT_STYLE_CIRCLE)
.value("PLOT_STYLE_TARGET", PLOT_STYLE_TARGET)
.value("PLOT_STYLE_DOT_TARGET", PLOT_STYLE_DOT_TARGET)
.value("PLOT_STYLE_WAVES", PLOT_STYLE_WAVES)
.value("PLOT_STYLE_DOTS", PLOT_STYLE_DOTS)
.value("PLOT_STYLE_CIRCLES", PLOT_STYLE_CIRCLES)
;
python::enum_<PlotLandscapeLayers>("PlotLandscapeLayers")
.value("PLOT_LANDSCAPE_LAYER_ALL", PLOT_LANDSCAPE_LAYER_ALL)
.value("PLOT_LANDSCAPE_LAYER_BASE", PLOT_LANDSCAPE_LAYER_BASE)
.value("PLOT_LANDSCAPE_LAYER_RECOMMENDED_PLOTS", PLOT_LANDSCAPE_LAYER_RECOMMENDED_PLOTS)
.value("PLOT_LANDSCAPE_LAYER_WORLD_BUILDER", PLOT_LANDSCAPE_LAYER_WORLD_BUILDER)
.value("PLOT_LANDSCAPE_LAYER_NUMPAD_HELP", PLOT_LANDSCAPE_LAYER_NUMPAD_HELP)
.value("PLOT_LANDSCAPE_LAYER_REVEALED_PLOTS", PLOT_LANDSCAPE_LAYER_REVEALED_PLOTS)
;
python::enum_<AreaBorderLayers>("AreaBorderLayers")
.value("AREA_BORDER_LAYER_REVEALED_PLOTS", AREA_BORDER_LAYER_REVEALED_PLOTS)
.value("AREA_BORDER_LAYER_WORLD_BUILDER", AREA_BORDER_LAYER_WORLD_BUILDER)
.value("AREA_BORDER_LAYER_FOUNDING_BORDER", AREA_BORDER_LAYER_FOUNDING_BORDER)
.value("AREA_BORDER_LAYER_CITY_RADIUS", AREA_BORDER_LAYER_CITY_RADIUS)
.value("AREA_BORDER_LAYER_RANGED", AREA_BORDER_LAYER_RANGED)
.value("AREA_BORDER_LAYER_HIGHLIGHT_PLOT", AREA_BORDER_LAYER_HIGHLIGHT_PLOT)
.value("AREA_BORDER_LAYER_BLOCKADING", AREA_BORDER_LAYER_BLOCKADING)
.value("AREA_BORDER_LAYER_BLOCKADED", AREA_BORDER_LAYER_BLOCKADED)
.value("NUM_AREA_BORDER_LAYERS", NUM_AREA_BORDER_LAYERS)
;
python::enum_<InterfaceModeTypes>("InterfaceModeTypes")
.value("NO_INTERFACEMODE", NO_INTERFACEMODE)
.value("INTERFACEMODE_SELECTION", INTERFACEMODE_SELECTION)
.value("INTERFACEMODE_PING", INTERFACEMODE_PING)
.value("INTERFACEMODE_SIGN", INTERFACEMODE_SIGN)
.value("INTERFACEMODE_GRIP", INTERFACEMODE_GRIP)
.value("INTERFACEMODE_GLOBELAYER_INPUT", INTERFACEMODE_GLOBELAYER_INPUT)
.value("INTERFACEMODE_GO_TO", INTERFACEMODE_GO_TO)
.value("INTERFACEMODE_GO_TO_TYPE", INTERFACEMODE_GO_TO_TYPE)
.value("INTERFACEMODE_GO_TO_ALL", INTERFACEMODE_GO_TO_ALL)
.value("INTERFACEMODE_ROUTE_TO", INTERFACEMODE_ROUTE_TO)
.value("INTERFACEMODE_AIRLIFT", INTERFACEMODE_AIRLIFT)
.value("INTERFACEMODE_NUKE", INTERFACEMODE_NUKE)
.value("INTERFACEMODE_RECON", INTERFACEMODE_RECON)
.value("INTERFACEMODE_PARADROP", INTERFACEMODE_PARADROP)
.value("INTERFACEMODE_AIRBOMB", INTERFACEMODE_AIRBOMB)
.value("INTERFACEMODE_RANGE_ATTACK", INTERFACEMODE_RANGE_ATTACK)
.value("INTERFACEMODE_AIRSTRIKE", INTERFACEMODE_AIRSTRIKE)
.value("INTERFACEMODE_REBASE", INTERFACEMODE_REBASE)
.value("INTERFACEMODE_PYTHON_PICK_PLOT", INTERFACEMODE_PYTHON_PICK_PLOT)
.value("INTERFACEMODE_SAVE_PLOT_NIFS", INTERFACEMODE_SAVE_PLOT_NIFS)
// BUG - Sentry Actions - start
#ifdef _MOD_SENTRY
.value("INTERFACEMODE_GO_TO_SENTRY", INTERFACEMODE_GO_TO_SENTRY)
#endif
// BUG - Sentry Actions - end
.value("NUM_INTERFACEMODE_TYPES", NUM_INTERFACEMODE_TYPES)
;
python::enum_<InterfaceMessageTypes>("InterfaceMessageTypes")
.value("NO_MESSAGE_TYPE", NO_MESSAGE_TYPE)
.value("MESSAGE_TYPE_INFO", MESSAGE_TYPE_INFO)
.value("MESSAGE_TYPE_DISPLAY_ONLY", MESSAGE_TYPE_DISPLAY_ONLY)
.value("MESSAGE_TYPE_MAJOR_EVENT", MESSAGE_TYPE_MAJOR_EVENT)
.value("MESSAGE_TYPE_MINOR_EVENT", MESSAGE_TYPE_MINOR_EVENT)
.value("MESSAGE_TYPE_CHAT", MESSAGE_TYPE_CHAT)
.value("MESSAGE_TYPE_COMBAT_MESSAGE", MESSAGE_TYPE_COMBAT_MESSAGE)
.value("MESSAGE_TYPE_QUEST", MESSAGE_TYPE_QUEST)
.value("NUM_INTERFACE_MESSAGE_TYPES", NUM_INTERFACE_MESSAGE_TYPES)
;
python::enum_<MinimapModeTypes>("MinimapModeTypes")
.value("NO_MINIMAPMODE", NO_MINIMAPMODE)
.value("MINIMAPMODE_TERRITORY", MINIMAPMODE_TERRITORY)
.value("MINIMAPMODE_TERRAIN", MINIMAPMODE_TERRAIN)
.value("MINIMAPMODE_REPLAY", MINIMAPMODE_REPLAY)
.value("MINIMAPMODE_MILITARY", MINIMAPMODE_MILITARY)
.value("NUM_MINIMAPMODE_TYPES", NUM_MINIMAPMODE_TYPES)
;
python::enum_<EngineDirtyBits>("EngineDirtyBits")
.value("GlobeTexture_DIRTY_BIT", GlobeTexture_DIRTY_BIT)
.value("MinimapTexture_DIRTY_BIT", MinimapTexture_DIRTY_BIT)
.value("CultureBorders_DIRTY_BIT", CultureBorders_DIRTY_BIT)
.value("NUM_ENGINE_DIRTY_BITS", NUM_ENGINE_DIRTY_BITS)
;
python::enum_<InterfaceDirtyBits>("InterfaceDirtyBits")
.value("SelectionCamera_DIRTY_BIT", SelectionCamera_DIRTY_BIT)
.value("Fog_DIRTY_BIT", Fog_DIRTY_BIT)
.value("GlobeLayer_DIRTY_BIT", GlobeLayer_DIRTY_BIT)
.value("GlobeInfo_DIRTY_BIT", GlobeInfo_DIRTY_BIT)
.value("Waypoints_DIRTY_BIT", Waypoints_DIRTY_BIT)
.value("PercentButtons_DIRTY_BIT", PercentButtons_DIRTY_BIT)
.value("MiscButtons_DIRTY_BIT", MiscButtons_DIRTY_BIT)
.value("PlotListButtons_DIRTY_BIT", PlotListButtons_DIRTY_BIT)
.value("SelectionButtons_DIRTY_BIT", SelectionButtons_DIRTY_BIT)
.value("CitizenButtons_DIRTY_BIT", CitizenButtons_DIRTY_BIT)
.value("ResearchButtons_DIRTY_BIT", ResearchButtons_DIRTY_BIT)
.value("Event_DIRTY_BIT", Event_DIRTY_BIT)
.value("Center_DIRTY_BIT", Center_DIRTY_BIT)
.value("GameData_DIRTY_BIT", GameData_DIRTY_BIT)
.value("Score_DIRTY_BIT", Score_DIRTY_BIT)
.value("TurnTimer_DIRTY_BIT", TurnTimer_DIRTY_BIT)
.value("Help_DIRTY_BIT", Help_DIRTY_BIT)
.value("MinimapSection_DIRTY_BIT", MinimapSection_DIRTY_BIT)
.value("SelectionSound_DIRTY_BIT", SelectionSound_DIRTY_BIT)
.value("Cursor_DIRTY_BIT", Cursor_DIRTY_BIT)
.value("CityInfo_DIRTY_BIT", CityInfo_DIRTY_BIT)
.value("UnitInfo_DIRTY_BIT", UnitInfo_DIRTY_BIT)
.value("Popup_DIRTY_BIT", Popup_DIRTY_BIT)
.value("CityScreen_DIRTY_BIT", CityScreen_DIRTY_BIT)
.value("InfoPane_DIRTY_BIT", InfoPane_DIRTY_BIT)
.value("Flag_DIRTY_BIT", Flag_DIRTY_BIT)
.value("HighlightPlot_DIRTY_BIT", HighlightPlot_DIRTY_BIT)
.value("ColoredPlots_DIRTY_BIT", ColoredPlots_DIRTY_BIT)
.value("BlockadedPlots_DIRTY_BIT", BlockadedPlots_DIRTY_BIT)
.value("Financial_Screen_DIRTY_BIT", Financial_Screen_DIRTY_BIT)
.value("Foreign_Screen_DIRTY_BIT", Foreign_Screen_DIRTY_BIT)
.value("Soundtrack_DIRTY_BIT", Soundtrack_DIRTY_BIT)
.value("Domestic_Advisor_DIRTY_BIT", Domestic_Advisor_DIRTY_BIT)
.value("Espionage_Advisor_DIRTY_BIT", Espionage_Advisor_DIRTY_BIT)
.value("Advanced_Start_DIRTY_BIT", Advanced_Start_DIRTY_BIT)
.value("NUM_INTERFACE_DIRTY_BITS", NUM_INTERFACE_DIRTY_BITS)
;
python::enum_<CityTabTypes>("CityTabTypes")
.value("CITYTAB_UNITS", CITYTAB_UNITS)
.value("CITYTAB_BUILDINGS", CITYTAB_BUILDINGS)
.value("CITYTAB_WONDERS", CITYTAB_WONDERS)
.value("NUM_CITYTAB_TYPES", NUM_CITYTAB_TYPES)
;
python::enum_<WidgetTypes>("WidgetTypes")
.value("WIDGET_PLOT_LIST", WIDGET_PLOT_LIST)
.value("WIDGET_PLOT_LIST_SHIFT", WIDGET_PLOT_LIST_SHIFT)
.value("WIDGET_CITY_SCROLL", WIDGET_CITY_SCROLL)
.value("WIDGET_LIBERATE_CITY", WIDGET_LIBERATE_CITY)
.value("WIDGET_CITY_NAME", WIDGET_CITY_NAME)
.value("WIDGET_UNIT_NAME", WIDGET_UNIT_NAME)
.value("WIDGET_CREATE_GROUP", WIDGET_CREATE_GROUP)
.value("WIDGET_DELETE_GROUP", WIDGET_DELETE_GROUP)
.value("WIDGET_TRAIN", WIDGET_TRAIN)
.value("WIDGET_CONSTRUCT", WIDGET_CONSTRUCT)
.value("WIDGET_CREATE", WIDGET_CREATE)
.value("WIDGET_MAINTAIN", WIDGET_MAINTAIN)
.value("WIDGET_HURRY", WIDGET_HURRY)
.value("WIDGET_MENU_ICON", WIDGET_MENU_ICON)
.value("WIDGET_CONSCRIPT", WIDGET_CONSCRIPT)
.value("WIDGET_ACTION", WIDGET_ACTION)
.value("WIDGET_DISABLED_CITIZEN", WIDGET_DISABLED_CITIZEN)
.value("WIDGET_CITIZEN", WIDGET_CITIZEN)
.value("WIDGET_FREE_CITIZEN", WIDGET_FREE_CITIZEN)
.value("WIDGET_ANGRY_CITIZEN", WIDGET_ANGRY_CITIZEN)
.value("WIDGET_CHANGE_SPECIALIST", WIDGET_CHANGE_SPECIALIST)
.value("WIDGET_RESEARCH", WIDGET_RESEARCH)
.value("WIDGET_TECH_TREE", WIDGET_TECH_TREE)
.value("WIDGET_CHANGE_PERCENT", WIDGET_CHANGE_PERCENT)
.value("WIDGET_CITY_TAB", WIDGET_CITY_TAB)
.value("WIDGET_CONTACT_CIV", WIDGET_CONTACT_CIV)
.value("WIDGET_SCORE_BREAKDOWN", WIDGET_SCORE_BREAKDOWN)
.value("WIDGET_ZOOM_CITY", WIDGET_ZOOM_CITY)
.value("WIDGET_END_TURN", WIDGET_END_TURN)
.value("WIDGET_LAUNCH_VICTORY", WIDGET_LAUNCH_VICTORY)
.value("WIDGET_CONVERT", WIDGET_CONVERT)
.value("WIDGET_WB_SAVE_BUTTON", WIDGET_WB_SAVE_BUTTON)
.value("WIDGET_WB_LOAD_BUTTON", WIDGET_WB_LOAD_BUTTON)
.value("WIDGET_WB_ALL_PLOTS_BUTTON", WIDGET_WB_ALL_PLOTS_BUTTON)
.value("WIDGET_WB_LANDMARK_BUTTON", WIDGET_WB_LANDMARK_BUTTON)
.value("WIDGET_WB_ERASE_BUTTON", WIDGET_WB_ERASE_BUTTON)
.value("WIDGET_WB_EXIT_BUTTON", WIDGET_WB_EXIT_BUTTON)
.value("WIDGET_WB_UNIT_EDIT_BUTTON", WIDGET_WB_UNIT_EDIT_BUTTON)
.value("WIDGET_WB_CITY_EDIT_BUTTON", WIDGET_WB_CITY_EDIT_BUTTON)
.value("WIDGET_WB_NORMAL_PLAYER_TAB_MODE_BUTTON", WIDGET_WB_NORMAL_PLAYER_TAB_MODE_BUTTON)
.value("WIDGET_WB_NORMAL_MAP_TAB_MODE_BUTTON", WIDGET_WB_NORMAL_MAP_TAB_MODE_BUTTON)
.value("WIDGET_WB_REVEAL_TAB_MODE_BUTTON", WIDGET_WB_REVEAL_TAB_MODE_BUTTON)
.value("WIDGET_WB_DIPLOMACY_MODE_BUTTON", WIDGET_WB_DIPLOMACY_MODE_BUTTON)
.value("WIDGET_WB_REVEAL_ALL_BUTTON", WIDGET_WB_REVEAL_ALL_BUTTON)
.value("WIDGET_WB_UNREVEAL_ALL_BUTTON", WIDGET_WB_UNREVEAL_ALL_BUTTON)
.value("WIDGET_WB_REGENERATE_MAP", WIDGET_WB_REGENERATE_MAP)
.value("WIDGET_AUTOMATE_CITIZENS", WIDGET_AUTOMATE_CITIZENS)
.value("WIDGET_AUTOMATE_PRODUCTION", WIDGET_AUTOMATE_PRODUCTION)
.value("WIDGET_EMPHASIZE", WIDGET_EMPHASIZE)
.value("WIDGET_DIPLOMACY_RESPONSE", WIDGET_DIPLOMACY_RESPONSE)
.value("WIDGET_GENERAL", WIDGET_GENERAL)
.value("WIDGET_FILE_LISTBOX", WIDGET_FILE_LISTBOX)
.value("WIDGET_FILE_EDITBOX", WIDGET_FILE_EDITBOX)
.value("WIDGET_TRADE_ITEM", WIDGET_TRADE_ITEM)
.value("WIDGET_UNIT_MODEL", WIDGET_UNIT_MODEL)
.value("WIDGET_FLAG", WIDGET_FLAG)
.value("WIDGET_POPUP_QUEUE", WIDGET_POPUP_QUEUE)
.value("WIDGET_PYTHON", WIDGET_PYTHON)
.value("WIDGET_HELP_MAINTENANCE", WIDGET_HELP_MAINTENANCE)
.value("WIDGET_HELP_RELIGION", WIDGET_HELP_RELIGION)
.value("WIDGET_HELP_RELIGION_CITY", WIDGET_HELP_RELIGION_CITY)
.value("WIDGET_HELP_CORPORATION_CITY", WIDGET_HELP_CORPORATION_CITY)
.value("WIDGET_HELP_NATIONALITY", WIDGET_HELP_NATIONALITY)
.value("WIDGET_HELP_DEFENSE", WIDGET_HELP_DEFENSE)
.value("WIDGET_HELP_HEALTH", WIDGET_HELP_HEALTH)
.value("WIDGET_HELP_HAPPINESS", WIDGET_HELP_HAPPINESS)
.value("WIDGET_HELP_POPULATION", WIDGET_HELP_POPULATION)
.value("WIDGET_HELP_PRODUCTION", WIDGET_HELP_PRODUCTION)
.value("WIDGET_HELP_CULTURE", WIDGET_HELP_CULTURE)
.value("WIDGET_HELP_GREAT_PEOPLE", WIDGET_HELP_GREAT_PEOPLE)
.value("WIDGET_HELP_GREAT_GENERAL", WIDGET_HELP_GREAT_GENERAL)
.value("WIDGET_HELP_SELECTED", WIDGET_HELP_SELECTED)
.value("WIDGET_HELP_BUILDING", WIDGET_HELP_BUILDING)
.value("WIDGET_HELP_TRADE_ROUTE_CITY", WIDGET_HELP_TRADE_ROUTE_CITY)
.value("WIDGET_HELP_ESPIONAGE_COST", WIDGET_HELP_ESPIONAGE_COST)
.value("WIDGET_HELP_TECH_ENTRY", WIDGET_HELP_TECH_ENTRY)
.value("WIDGET_HELP_TECH_PREPREQ", WIDGET_HELP_TECH_PREPREQ)
.value("WIDGET_HELP_OBSOLETE", WIDGET_HELP_OBSOLETE)
.value("WIDGET_HELP_OBSOLETE_BONUS", WIDGET_HELP_OBSOLETE_BONUS)
.value("WIDGET_HELP_OBSOLETE_SPECIAL", WIDGET_HELP_OBSOLETE_SPECIAL)
.value("WIDGET_HELP_MOVE_BONUS", WIDGET_HELP_MOVE_BONUS)
.value("WIDGET_HELP_FREE_UNIT", WIDGET_HELP_FREE_UNIT)
.value("WIDGET_HELP_FEATURE_PRODUCTION", WIDGET_HELP_FEATURE_PRODUCTION)
.value("WIDGET_HELP_WORKER_RATE", WIDGET_HELP_WORKER_RATE)
.value("WIDGET_HELP_TRADE_ROUTES", WIDGET_HELP_TRADE_ROUTES)
.value("WIDGET_HELP_HEALTH_RATE", WIDGET_HELP_HEALTH_RATE)
.value("WIDGET_HELP_HAPPINESS_RATE", WIDGET_HELP_HAPPINESS_RATE)
.value("WIDGET_HELP_FREE_TECH", WIDGET_HELP_FREE_TECH)
.value("WIDGET_HELP_LOS_BONUS", WIDGET_HELP_LOS_BONUS)
.value("WIDGET_HELP_MAP_CENTER", WIDGET_HELP_MAP_CENTER)
.value("WIDGET_HELP_MAP_REVEAL", WIDGET_HELP_MAP_REVEAL)
.value("WIDGET_HELP_MAP_TRADE", WIDGET_HELP_MAP_TRADE)
.value("WIDGET_HELP_TECH_TRADE", WIDGET_HELP_TECH_TRADE)
.value("WIDGET_HELP_GOLD_TRADE", WIDGET_HELP_GOLD_TRADE)
.value("WIDGET_HELP_OPEN_BORDERS", WIDGET_HELP_OPEN_BORDERS)
.value("WIDGET_HELP_DEFENSIVE_PACT", WIDGET_HELP_DEFENSIVE_PACT)
.value("WIDGET_HELP_PERMANENT_ALLIANCE", WIDGET_HELP_PERMANENT_ALLIANCE)
.value("WIDGET_HELP_VASSAL_STATE", WIDGET_HELP_VASSAL_STATE)
.value("WIDGET_HELP_BUILD_BRIDGE", WIDGET_HELP_BUILD_BRIDGE)
.value("WIDGET_HELP_IRRIGATION", WIDGET_HELP_IRRIGATION)
.value("WIDGET_HELP_IGNORE_IRRIGATION", WIDGET_HELP_IGNORE_IRRIGATION)
.value("WIDGET_HELP_WATER_WORK", WIDGET_HELP_WATER_WORK)
.value("WIDGET_HELP_IMPROVEMENT", WIDGET_HELP_IMPROVEMENT)
.value("WIDGET_HELP_REMOVE", WIDGET_HELP_REMOVE)
.value("WIDGET_HELP_DOMAIN_EXTRA_MOVES", WIDGET_HELP_DOMAIN_EXTRA_MOVES)
.value("WIDGET_HELP_ADJUST", WIDGET_HELP_ADJUST)
.value("WIDGET_HELP_TERRAIN_TRADE", WIDGET_HELP_TERRAIN_TRADE)
.value("WIDGET_HELP_SPECIAL_BUILDING", WIDGET_HELP_SPECIAL_BUILDING)
.value("WIDGET_HELP_YIELD_CHANGE", WIDGET_HELP_YIELD_CHANGE)
.value("WIDGET_HELP_BONUS_REVEAL", WIDGET_HELP_BONUS_REVEAL)
.value("WIDGET_HELP_CIVIC_REVEAL", WIDGET_HELP_CIVIC_REVEAL)
.value("WIDGET_HELP_PROCESS_INFO", WIDGET_HELP_PROCESS_INFO)
.value("WIDGET_HELP_FOUND_RELIGION", WIDGET_HELP_FOUND_RELIGION)
.value("WIDGET_HELP_FOUND_CORPORATION", WIDGET_HELP_FOUND_CORPORATION)
.value("WIDGET_HELP_FINANCE_NUM_UNITS", WIDGET_HELP_FINANCE_NUM_UNITS)
.value("WIDGET_HELP_FINANCE_UNIT_COST", WIDGET_HELP_FINANCE_UNIT_COST)
.value("WIDGET_HELP_FINANCE_AWAY_SUPPLY", WIDGET_HELP_FINANCE_AWAY_SUPPLY)
.value("WIDGET_HELP_FINANCE_CITY_MAINT", WIDGET_HELP_FINANCE_CITY_MAINT)
.value("WIDGET_HELP_FINANCE_CIVIC_UPKEEP", WIDGET_HELP_FINANCE_CIVIC_UPKEEP)
.value("WIDGET_HELP_FINANCE_FOREIGN_INCOME", WIDGET_HELP_FINANCE_FOREIGN_INCOME)
.value("WIDGET_HELP_FINANCE_INFLATED_COSTS", WIDGET_HELP_FINANCE_INFLATED_COSTS)
.value("WIDGET_HELP_FINANCE_GROSS_INCOME", WIDGET_HELP_FINANCE_GROSS_INCOME)
.value("WIDGET_HELP_FINANCE_NET_GOLD", WIDGET_HELP_FINANCE_NET_GOLD)
.value("WIDGET_HELP_FINANCE_GOLD_RESERVE", WIDGET_HELP_FINANCE_GOLD_RESERVE)
.value("WIDGET_HELP_PROMOTION", WIDGET_HELP_PROMOTION)
// Leoreth
.value("WIDGET_HELP_STABILITY_EXPANSION", WIDGET_HELP_STABILITY_EXPANSION)
.value("WIDGET_HELP_STABILITY_ECONOMY", WIDGET_HELP_STABILITY_ECONOMY)
.value("WIDGET_HELP_STABILITY_DOMESTIC", WIDGET_HELP_STABILITY_DOMESTIC)
.value("WIDGET_HELP_STABILITY_FOREIGN", WIDGET_HELP_STABILITY_FOREIGN)
.value("WIDGET_HELP_STABILITY_MILITARY", WIDGET_HELP_STABILITY_MILITARY)
.value("WIDGET_HELP_STABILITY", WIDGET_HELP_STABILITY)
.value("WIDGET_HELP_GREAT_SPY", WIDGET_HELP_GREAT_SPY)
.value("WIDGET_HELP_BONUS_PLAYER_TRADE", WIDGET_HELP_BONUS_PLAYER_TRADE)
.value("WIDGET_HELP_BONUS_CITY", WIDGET_HELP_BONUS_CITY)
.value("WIDGET_CHOOSE_EVENT", WIDGET_CHOOSE_EVENT)
.value("WIDGET_PEDIA_JUMP_TO_TECH", WIDGET_PEDIA_JUMP_TO_TECH)
.value("WIDGET_PEDIA_JUMP_TO_CULTURE_LEVEL", WIDGET_PEDIA_JUMP_TO_CULTURE_LEVEL)
.value("WIDGET_PEDIA_JUMP_TO_UNIT", WIDGET_PEDIA_JUMP_TO_UNIT)
.value("WIDGET_PEDIA_JUMP_TO_BUILDING", WIDGET_PEDIA_JUMP_TO_BUILDING)
.value("WIDGET_PEDIA_JUMP_TO_DERIVED_TECH", WIDGET_PEDIA_JUMP_TO_DERIVED_TECH)
.value("WIDGET_PEDIA_JUMP_TO_REQUIRED_TECH", WIDGET_PEDIA_JUMP_TO_REQUIRED_TECH)
.value("WIDGET_PEDIA_BACK", WIDGET_PEDIA_BACK)
.value("WIDGET_PEDIA_FORWARD", WIDGET_PEDIA_FORWARD)
.value("WIDGET_PEDIA_JUMP_TO_BONUS", WIDGET_PEDIA_JUMP_TO_BONUS)
.value("WIDGET_PEDIA_MAIN", WIDGET_PEDIA_MAIN)
.value("WIDGET_PEDIA_JUMP_TO_PROMOTION", WIDGET_PEDIA_JUMP_TO_PROMOTION)
.value("WIDGET_PEDIA_JUMP_TO_UNIT_COMBAT", WIDGET_PEDIA_JUMP_TO_UNIT_COMBAT)
.value("WIDGET_PEDIA_JUMP_TO_IMPROVEMENT", WIDGET_PEDIA_JUMP_TO_IMPROVEMENT)
.value("WIDGET_PEDIA_JUMP_TO_ROUTE", WIDGET_PEDIA_JUMP_TO_ROUTE)
.value("WIDGET_PEDIA_JUMP_TO_CIVIC", WIDGET_PEDIA_JUMP_TO_CIVIC)
.value("WIDGET_PEDIA_JUMP_TO_CIV", WIDGET_PEDIA_JUMP_TO_CIV)
.value("WIDGET_PEDIA_JUMP_TO_LEADER", WIDGET_PEDIA_JUMP_TO_LEADER)
.value("WIDGET_PEDIA_JUMP_TO_SPECIALIST", WIDGET_PEDIA_JUMP_TO_SPECIALIST)
.value("WIDGET_PEDIA_JUMP_TO_PROJECT", WIDGET_PEDIA_JUMP_TO_PROJECT)
.value("WIDGET_PEDIA_JUMP_TO_TERRAIN", WIDGET_PEDIA_JUMP_TO_TERRAIN)
.value("WIDGET_PEDIA_JUMP_TO_FEATURE", WIDGET_PEDIA_JUMP_TO_FEATURE)
.value("WIDGET_PEDIA_JUMP_TO_PAGAN_RELIGION", WIDGET_PEDIA_JUMP_TO_PAGAN_RELIGION)
.value("WIDGET_TURN_EVENT", WIDGET_TURN_EVENT)
.value("WIDGET_FOREIGN_ADVISOR", WIDGET_FOREIGN_ADVISOR)
.value("WIDGET_REVOLUTION", WIDGET_REVOLUTION)
.value("WIDGET_PEDIA_DESCRIPTION", WIDGET_PEDIA_DESCRIPTION)
.value("WIDGET_PEDIA_DESCRIPTION_NO_HELP", WIDGET_PEDIA_DESCRIPTION_NO_HELP)
.value("WIDGET_DEAL_KILL", WIDGET_DEAL_KILL)
.value("WIDGET_MINIMAP_HIGHLIGHT", WIDGET_MINIMAP_HIGHLIGHT)
.value("WIDGET_PRODUCTION_MOD_HELP", WIDGET_PRODUCTION_MOD_HELP)
.value("WIDGET_LEADERHEAD", WIDGET_LEADERHEAD)
.value("WIDGET_LEADER_LINE", WIDGET_LEADER_LINE)
.value("WIDGET_COMMERCE_MOD_HELP", WIDGET_COMMERCE_MOD_HELP)
.value("WIDGET_CLOSE_SCREEN", WIDGET_CLOSE_SCREEN)
.value("WIDGET_PEDIA_JUMP_TO_RELIGION", WIDGET_PEDIA_JUMP_TO_RELIGION)
.value("WIDGET_PEDIA_JUMP_TO_CORPORATION", WIDGET_PEDIA_JUMP_TO_CORPORATION)
.value("WIDGET_GLOBELAYER", WIDGET_GLOBELAYER)
.value("WIDGET_GLOBELAYER_OPTION", WIDGET_GLOBELAYER_OPTION)
.value("WIDGET_GLOBELAYER_TOGGLE", WIDGET_GLOBELAYER_TOGGLE)
.value("WIDGET_FINANCE_ADVISOR", WIDGET_FINANCE_ADVISOR)
// BUG - Min/Max Commerce Rate - start
.value("WIDGET_SET_PERCENT", WIDGET_SET_PERCENT)
// BUG - Min/Max Commerce Rate - end
// BUG - Finance Advisor - start
.value("WIDGET_HELP_FINANCE_DOMESTIC_TRADE", WIDGET_HELP_FINANCE_DOMESTIC_TRADE)
.value("WIDGET_HELP_FINANCE_FOREIGN_TRADE", WIDGET_HELP_FINANCE_FOREIGN_TRADE)
.value("WIDGET_HELP_FINANCE_SPECIALISTS", WIDGET_HELP_FINANCE_SPECIALISTS)
// BUG - Finance Advisor - end
// BUG - Trade Denial - start
.value("WIDGET_PEDIA_JUMP_TO_BONUS_TRADE", WIDGET_PEDIA_JUMP_TO_BONUS_TRADE)
.value("WIDGET_PEDIA_JUMP_TO_TECH_TRADE", WIDGET_PEDIA_JUMP_TO_TECH_TRADE)
// BUG - Trade Denial - end
// BUG - Foreign Advisor INFO Trade - start
.value("WIDGET_TRADE_ROUTES", WIDGET_TRADE_ROUTES)
// BUG - Foreign Advisor INFO Trade - end
// BUG - Food Rate Hover - start
.value("WIDGET_FOOD_MOD_HELP", WIDGET_FOOD_MOD_HELP)
// BUG - Food Rate Hover - end
// BUG - Leaderhead Relations - start
.value("WIDGET_LEADERHEAD_RELATIONS", WIDGET_LEADERHEAD_RELATIONS)
// BUG - Leaderhead Relations - end
.value("WIDGET_HELP_WONDER_LIMIT", WIDGET_HELP_WONDER_LIMIT)
.value("WIDGET_HELP_SATELLITE_LIMIT", WIDGET_HELP_SATELLITE_LIMIT)
.value("WIDGET_FIRST_DISCOVERED", WIDGET_FIRST_DISCOVERED)
.value("NUM_WIDGET_TYPES", NUM_WIDGET_TYPES)
;
python::enum_<ButtonPopupTypes>("ButtonPopupTypes")
.value("BUTTONPOPUP_TEXT", BUTTONPOPUP_TEXT)
.value("BUTTONPOPUP_MAIN_MENU", BUTTONPOPUP_MAIN_MENU)
.value("BUTTONPOPUP_CONFIRM_MENU", BUTTONPOPUP_CONFIRM_MENU)
.value("BUTTONPOPUP_DECLAREWARMOVE", BUTTONPOPUP_DECLAREWARMOVE)
.value("BUTTONPOPUP_CONFIRMCOMMAND", BUTTONPOPUP_CONFIRMCOMMAND)
.value("BUTTONPOPUP_LOADUNIT", BUTTONPOPUP_LOADUNIT)
.value("BUTTONPOPUP_LEADUNIT", BUTTONPOPUP_LEADUNIT)
.value("BUTTONPOPUP_DOESPIONAGE", BUTTONPOPUP_DOESPIONAGE)
.value("BUTTONPOPUP_DOESPIONAGE_TARGET", BUTTONPOPUP_DOESPIONAGE_TARGET)
.value("BUTTONPOPUP_CHOOSETECH", BUTTONPOPUP_CHOOSETECH)
.value("BUTTONPOPUP_RAZECITY", BUTTONPOPUP_RAZECITY)
.value("BUTTONPOPUP_DISBANDCITY", BUTTONPOPUP_DISBANDCITY)
.value("BUTTONPOPUP_CHOOSEPRODUCTION", BUTTONPOPUP_CHOOSEPRODUCTION)
.value("BUTTONPOPUP_CHANGECIVIC", BUTTONPOPUP_CHANGECIVIC)
.value("BUTTONPOPUP_CHANGERELIGION", BUTTONPOPUP_CHANGERELIGION)
.value("BUTTONPOPUP_CHOOSEELECTION", BUTTONPOPUP_CHOOSEELECTION)
.value("BUTTONPOPUP_DIPLOVOTE", BUTTONPOPUP_DIPLOVOTE)
.value("BUTTONPOPUP_ALARM", BUTTONPOPUP_ALARM)
.value("BUTTONPOPUP_DEAL_CANCELED", BUTTONPOPUP_DEAL_CANCELED)
.value("BUTTONPOPUP_PYTHON", BUTTONPOPUP_PYTHON)
.value("BUTTONPOPUP_PYTHON_SCREEN", BUTTONPOPUP_PYTHON_SCREEN)
.value("BUTTONPOPUP_DETAILS", BUTTONPOPUP_DETAILS)
.value("BUTTONPOPUP_ADMIN", BUTTONPOPUP_ADMIN)
.value("BUTTONPOPUP_ADMIN_PASSWORD", BUTTONPOPUP_ADMIN_PASSWORD)
.value("BUTTONPOPUP_EXTENDED_GAME", BUTTONPOPUP_EXTENDED_GAME)
.value("BUTTONPOPUP_DIPLOMACY", BUTTONPOPUP_DIPLOMACY)
.value("BUTTONPOPUP_ADDBUDDY", BUTTONPOPUP_ADDBUDDY)
.value("BUTTONPOPUP_FORCED_DISCONNECT", BUTTONPOPUP_FORCED_DISCONNECT)
.value("BUTTONPOPUP_PITBOSS_DISCONNECT", BUTTONPOPUP_PITBOSS_DISCONNECT)
.value("BUTTONPOPUP_KICKED", BUTTONPOPUP_PITBOSS_DISCONNECT)
.value("BUTTONPOPUP_VASSAL_DEMAND_TRIBUTE", BUTTONPOPUP_VASSAL_DEMAND_TRIBUTE)
.value("BUTTONPOPUP_VASSAL_GRANT_TRIBUTE", BUTTONPOPUP_VASSAL_GRANT_TRIBUTE)
.value("BUTTONPOPUP_EVENT", BUTTONPOPUP_EVENT)
.value("BUTTONPOPUP_FREE_COLONY", BUTTONPOPUP_FREE_COLONY)
.value("BUTTONPOPUP_LAUNCH", BUTTONPOPUP_LAUNCH)
.value("BUTTONPOPUP_FOUND_RELIGION", BUTTONPOPUP_FOUND_RELIGION)
.value("NUM_BUTTONPOPUP_TYPES", NUM_BUTTONPOPUP_TYPES)
;
python::enum_<ClimateTypes>("ClimateTypes")
.value("NO_CLIMATE", NO_CLIMATE)
;
python::enum_<SeaLevelTypes>("SeaLevelTypes")
.value("NO_SEALEVEL", NO_SEALEVEL)
;
python::enum_<CustomMapOptionTypes>("CustomMapOptionTypes")
.value("NO_CUSTOM_MAPOPTION", NO_CUSTOM_MAPOPTION)
;
python::enum_<WorldSizeTypes>("WorldSizeTypes")
.value("NO_WORLDSIZE", NO_WORLDSIZE)
.value("WORLDSIZE_HUGE", WORLDSIZE_HUGE)
.value("NUM_WORLDSIZE_TYPES", NUM_WORLDSIZE_TYPES)
;
python::enum_<TerrainTypes>("TerrainTypes")
.value("NO_TERRAIN", NO_TERRAIN)
;
python::enum_<PlotTypes>("PlotTypes")
.value("NO_PLOT", NO_PLOT)
.value("PLOT_PEAK", PLOT_PEAK)
.value("PLOT_HILLS", PLOT_HILLS)
.value("PLOT_LAND", PLOT_LAND)
.value("PLOT_OCEAN", PLOT_OCEAN)
.value("NUM_PLOT_TYPES", NUM_PLOT_TYPES)
;
python::enum_<YieldTypes>("YieldTypes")
.value("NO_YIELD", NO_YIELD)
.value("YIELD_FOOD", YIELD_FOOD)
.value("YIELD_PRODUCTION", YIELD_PRODUCTION)
.value("YIELD_COMMERCE", YIELD_COMMERCE)
.value("NUM_YIELD_TYPES", NUM_YIELD_TYPES)
;
python::enum_<CommerceTypes>("CommerceTypes")
.value("COMMERCE_GOLD", COMMERCE_GOLD)
.value("COMMERCE_RESEARCH", COMMERCE_RESEARCH)
.value("COMMERCE_CULTURE", COMMERCE_CULTURE)
.value("COMMERCE_ESPIONAGE", COMMERCE_ESPIONAGE)
.value("NUM_COMMERCE_TYPES", NUM_COMMERCE_TYPES)
;
python::enum_<AdvisorTypes>("AdvisorTypes")
.value("NO_ADVISOR", NO_ADVISOR)
;
python::enum_<FlavorTypes>("FlavorTypes")
.value("NO_FLAVOR", NO_FLAVOR)
;
python::enum_<EmphasizeTypes>("EmphasizeTypes")
.value("NO_EMPHASIZE", NO_EMPHASIZE)
;
python::enum_<GameOptionTypes>("GameOptionTypes")
.value("NO_GAMEOPTION", NO_GAMEOPTION)
.value("GAMEOPTION_ADVANCED_START", GAMEOPTION_ADVANCED_START)
.value("GAMEOPTION_NO_CITY_RAZING", GAMEOPTION_NO_CITY_RAZING)
.value("GAMEOPTION_NO_CITY_FLIPPING", GAMEOPTION_NO_CITY_FLIPPING)
.value("GAMEOPTION_FLIPPING_AFTER_CONQUEST", GAMEOPTION_FLIPPING_AFTER_CONQUEST)
.value("GAMEOPTION_NO_BARBARIANS", GAMEOPTION_NO_BARBARIANS)
.value("GAMEOPTION_RAGING_BARBARIANS", GAMEOPTION_RAGING_BARBARIANS)
.value("GAMEOPTION_AGGRESSIVE_AI", GAMEOPTION_AGGRESSIVE_AI)
.value("GAMEOPTION_LEAD_ANY_CIV", GAMEOPTION_LEAD_ANY_CIV)
.value("GAMEOPTION_RANDOM_PERSONALITIES", GAMEOPTION_RANDOM_PERSONALITIES)
.value("GAMEOPTION_PICK_RELIGION", GAMEOPTION_PICK_RELIGION)
.value("GAMEOPTION_NO_TECH_TRADING", GAMEOPTION_NO_TECH_TRADING)
.value("GAMEOPTION_NO_TECH_BROKERING", GAMEOPTION_NO_TECH_BROKERING)
.value("GAMEOPTION_PERMANENT_ALLIANCES", GAMEOPTION_PERMANENT_ALLIANCES)
.value("GAMEOPTION_ALWAYS_WAR", GAMEOPTION_ALWAYS_WAR)
.value("GAMEOPTION_ALWAYS_PEACE", GAMEOPTION_ALWAYS_PEACE)
.value("GAMEOPTION_ONE_CITY_CHALLENGE", GAMEOPTION_ONE_CITY_CHALLENGE)
.value("GAMEOPTION_NO_CHANGING_WAR_PEACE", GAMEOPTION_NO_CHANGING_WAR_PEACE)
.value("GAMEOPTION_NEW_RANDOM_SEED", GAMEOPTION_NEW_RANDOM_SEED)
.value("GAMEOPTION_LOCK_MODS", GAMEOPTION_LOCK_MODS)
.value("GAMEOPTION_COMPLETE_KILLS", GAMEOPTION_COMPLETE_KILLS)
.value("GAMEOPTION_NO_VASSAL_STATES", GAMEOPTION_NO_VASSAL_STATES)
.value("GAMEOPTION_NO_GOODY_HUTS", GAMEOPTION_NO_GOODY_HUTS)
.value("GAMEOPTION_NO_EVENTS", GAMEOPTION_NO_EVENTS)
.value("GAMEOPTION_NO_ESPIONAGE", GAMEOPTION_NO_ESPIONAGE)
// BUG - Global Warming Mod - start
#ifdef _MOD_GWARM
.value("GAMEOPTION_RISING_SEAS", GAMEOPTION_RISING_SEAS)
#endif
// BUG - Global Warming Mod - end
.value("NUM_GAMEOPTION_TYPES", NUM_GAMEOPTION_TYPES)
;
python::enum_<MultiplayerOptionTypes>("MultiplayerOptionTypes")
.value("NO_MPOPTION", NO_MPOPTION)
.value("MPOPTION_SIMULTANEOUS_TURNS", MPOPTION_SIMULTANEOUS_TURNS)
.value("MPOPTION_TAKEOVER_AI", MPOPTION_TAKEOVER_AI)
.value("MPOPTION_SHUFFLE_TEAMS", MPOPTION_SHUFFLE_TEAMS)
.value("MPOPTION_ANONYMOUS", MPOPTION_ANONYMOUS)
.value("MPOPTION_TURN_TIMER", MPOPTION_TURN_TIMER)
.value("NUM_MPOPTION_TYPES", NUM_MPOPTION_TYPES)
;
python::enum_<SpecialOptionTypes>("SpecialOptionTypes")
.value("NO_SPECIALOPTION", NO_SPECIALOPTION)
.value("SPECIALOPTION_REPORT_STATS", SPECIALOPTION_REPORT_STATS)
.value("NUM_SPECIALOPTION_TYPES", NUM_SPECIALOPTION_TYPES)
;
python::enum_<PlayerOptionTypes>("PlayerOptionTypes")
.value("NO_PLAYEROPTION", NO_PLAYEROPTION)
.value("PLAYEROPTION_ADVISOR_POPUPS", PLAYEROPTION_ADVISOR_POPUPS)
.value("PLAYEROPTION_ADVISOR_HELP", PLAYEROPTION_ADVISOR_HELP)
.value("PLAYEROPTION_WAIT_END_TURN", PLAYEROPTION_WAIT_END_TURN)
.value("PLAYEROPTION_MINIMIZE_POP_UPS", PLAYEROPTION_MINIMIZE_POP_UPS)
.value("PLAYEROPTION_SHOW_FRIENDLY_MOVES", PLAYEROPTION_SHOW_FRIENDLY_MOVES)
.value("PLAYEROPTION_SHOW_ENEMY_MOVES", PLAYEROPTION_SHOW_ENEMY_MOVES)
.value("PLAYEROPTION_QUICK_MOVES", PLAYEROPTION_QUICK_MOVES)
.value("PLAYEROPTION_QUICK_ATTACK", PLAYEROPTION_QUICK_ATTACK)
.value("PLAYEROPTION_QUICK_DEFENSE", PLAYEROPTION_QUICK_DEFENSE)
.value("PLAYEROPTION_STACK_ATTACK", PLAYEROPTION_STACK_ATTACK)
.value("PLAYEROPTION_AUTO_PROMOTION", PLAYEROPTION_AUTO_PROMOTION)
.value("PLAYEROPTION_START_AUTOMATED", PLAYEROPTION_START_AUTOMATED)
.value("PLAYEROPTION_SAFE_AUTOMATION", PLAYEROPTION_SAFE_AUTOMATION)
.value("PLAYEROPTION_NUMPAD_HELP", PLAYEROPTION_NUMPAD_HELP)
.value("PLAYEROPTION_NO_UNIT_CYCLING", PLAYEROPTION_NO_UNIT_CYCLING)
.value("PLAYEROPTION_NO_UNIT_RECOMMENDATIONS", PLAYEROPTION_NO_UNIT_RECOMMENDATIONS)
.value("PLAYEROPTION_RIGHT_CLICK_MENU", PLAYEROPTION_RIGHT_CLICK_MENU)
.value("PLAYEROPTION_LEAVE_FORESTS", PLAYEROPTION_LEAVE_FORESTS)
.value("PLAYEROPTION_MISSIONARIES_AUTOMATED", PLAYEROPTION_MISSIONARIES_AUTOMATED)
.value("PLAYEROPTION_MODDER_1", PLAYEROPTION_HIDE_AIR_CIRCLING)
.value("PLAYEROPTION_MODDER_2", PLAYEROPTION_MODDER_2)
.value("PLAYEROPTION_MODDER_3", PLAYEROPTION_MODDER_3)
.value("NUM_PLAYEROPTION_TYPES", NUM_PLAYEROPTION_TYPES)
;
python::enum_<GraphicOptionTypes>("GraphicOptionTypes")
.value("NO_GRAPHICOPTION", NO_GRAPHICOPTION)
.value("GRAPHICOPTION_SINGLE_UNIT_GRAPHICS", GRAPHICOPTION_SINGLE_UNIT_GRAPHICS)
.value("GRAPHICOPTION_HEALTH_BARS", GRAPHICOPTION_HEALTH_BARS)
.value("GRAPHICOPTION_CITY_DETAIL", GRAPHICOPTION_CITY_DETAIL)
.value("GRAPHICOPTION_NO_COMBAT_ZOOM", GRAPHICOPTION_NO_COMBAT_ZOOM)
.value("GRAPHICOPTION_NO_ENEMY_GLOW", GRAPHICOPTION_NO_ENEMY_GLOW)
.value("GRAPHICOPTION_FROZEN_ANIMATIONS", GRAPHICOPTION_FROZEN_ANIMATIONS)
.value("GRAPHICOPTION_EFFECTS_DISABLED", GRAPHICOPTION_EFFECTS_DISABLED)
.value("GRAPHICOPTION_GLOBE_VIEW_BUILDINGS_DISABLED", GRAPHICOPTION_GLOBE_VIEW_BUILDINGS_DISABLED)
.value("GRAPHICOPTION_FULLSCREEN", GRAPHICOPTION_FULLSCREEN)
.value("GRAPHICOPTION_LOWRES_TEXTURES", GRAPHICOPTION_LOWRES_TEXTURES)
.value("GRAPHICOPTION_HIRES_TERRAIN", GRAPHICOPTION_HIRES_TERRAIN)
.value("GRAPHICOPTION_NO_MOVIES", GRAPHICOPTION_NO_MOVIES)
.value("GRAPHICOPTION_CITY_RADIUS", GRAPHICOPTION_CITY_RADIUS)
.value("NUM_GRAPHICOPTION_TYPES", NUM_GRAPHICOPTION_TYPES)
;
python::enum_<ForceControlTypes>("ForceControlTypes")
.value("NO_FORCECONTROL", NO_FORCECONTROL)
.value("FORCECONTROL_SPEED", FORCECONTROL_SPEED)
.value("FORCECONTROL_HANDICAP", FORCECONTROL_HANDICAP)
.value("FORCECONTROL_OPTIONS", FORCECONTROL_OPTIONS)
.value("FORCECONTROL_VICTORIES", FORCECONTROL_VICTORIES)
.value("FORCECONTROL_MAX_TURNS", FORCECONTROL_MAX_TURNS)
.value("FORCECONTROL_MAX_CITY_ELIMINATIONS", FORCECONTROL_MAX_CITY_ELIMINATION)
.value("FORCECONTROL_ADVANCED_START", FORCECONTROL_ADVANCED_START)
.value("NUM_FORCECONTROL_TYPES", NUM_FORCECONTROL_TYPES)
;
python::enum_<VictoryTypes>("VictoryTypes")
.value("NO_VICTORY", NO_VICTORY)
.value("VICTORY_SCORE", VICTORY_SCORE)
.value("VICTORY_TIME", VICTORY_TIME)
.value("VICTORY_CONQUEST", VICTORY_CONQUEST)
.value("VICTORY_DOMINATION", VICTORY_DOMINATION)
.value("VICTORY_CULTURAL", VICTORY_CULTURAL)
.value("VICTORY_SPACE_RACE", VICTORY_SPACE_RACE)
.value("VICTORY_DIPLOMATIC", VICTORY_DIPLOMATIC)
.value("VICTORY_HISTORICAL", VICTORY_HISTORICAL)
.value("VICTORY_RELIGIOUS", VICTORY_RELIGIOUS)
;
python::enum_<FeatureTypes>("FeatureTypes")
.value("NO_FEATURE", NO_FEATURE)
;
python::enum_<BonusTypes>("BonusTypes")
.value("NO_BONUS", NO_BONUS)
;
python::enum_<BonusClassTypes>("BonusClassTypes")
.value("NO_BONUSCLASS", NO_BONUSCLASS)
;
python::enum_<ImprovementTypes>("ImprovementTypes")
.value("NO_IMPROVEMENT", NO_IMPROVEMENT)
;
python::enum_<RouteTypes>("RouteTypes")
.value("NO_ROUTE", NO_ROUTE)
;
python::enum_<RiverTypes>("RiverTypes")
.value("NO_RIVER", NO_RIVER)
;
python::enum_<GoodyTypes>("GoodyTypes")
.value("NO_GOODY", NO_GOODY)
;
python::enum_<BuildTypes>("BuildTypes")
.value("NO_BUILD", NO_BUILD)
;
python::enum_<SymbolTypes>("SymbolTypes")
.value("NO_SYMBOL", NO_SYMBOL)
;
python::enum_<FontSymbols>("FontSymbols")
.value("HAPPY_CHAR", HAPPY_CHAR)
.value("UNHAPPY_CHAR", UNHAPPY_CHAR)
.value("HEALTHY_CHAR", HEALTHY_CHAR)
.value("UNHEALTHY_CHAR", UNHEALTHY_CHAR)
.value("BULLET_CHAR", BULLET_CHAR)
.value("STRENGTH_CHAR", STRENGTH_CHAR)
.value("MOVES_CHAR", MOVES_CHAR)
.value("RELIGION_CHAR", RELIGION_CHAR)
.value("STAR_CHAR", STAR_CHAR)
.value("SILVER_STAR_CHAR", SILVER_STAR_CHAR)
.value("TRADE_CHAR", TRADE_CHAR)
.value("DEFENSE_CHAR", DEFENSE_CHAR)
.value("GREAT_PEOPLE_CHAR", GREAT_PEOPLE_CHAR)
.value("BAD_GOLD_CHAR", BAD_GOLD_CHAR)
.value("BAD_FOOD_CHAR", BAD_FOOD_CHAR)
.value("EATEN_FOOD_CHAR", EATEN_FOOD_CHAR)
.value("GOLDEN_AGE_CHAR", GOLDEN_AGE_CHAR)
.value("ANGRY_POP_CHAR", ANGRY_POP_CHAR)
.value("OPEN_BORDERS_CHAR", OPEN_BORDERS_CHAR)
.value("DEFENSIVE_PACT_CHAR", DEFENSIVE_PACT_CHAR)
.value("MAP_CHAR", MAP_CHAR)
.value("OCCUPATION_CHAR", OCCUPATION_CHAR)
.value("POWER_CHAR", POWER_CHAR)
.value("COLLAPSING_CHAR", COLLAPSING_CHAR)
.value("UNSTABLE_CHAR", UNSTABLE_CHAR)
.value("SHAKY_CHAR", SHAKY_CHAR)
.value("STABLE_CHAR", STABLE_CHAR)
.value("SOLID_CHAR", SOLID_CHAR)
.value("PLAGUE_CHAR", PLAGUE_CHAR)
.value("UP_CHAR", UP_CHAR)
.value("EQUAL_CHAR", EQUAL_CHAR)
.value("DOWN_CHAR", DOWN_CHAR)
.value("SUCCESS_CHAR", SUCCESS_CHAR)
.value("FAILURE_CHAR", FAILURE_CHAR)
.value("SCALES_CHAR", SCALES_CHAR)
.value("AIRPORT_CHAR", AIRPORT_CHAR)
.value("CLEAN_POWER_CHAR", CLEAN_POWER_CHAR)
.value("SATELLITE_CHAR", SATELLITE_CHAR)
.value("MAX_NUM_SYMBOLS", MAX_NUM_SYMBOLS)
;
python::enum_<HandicapTypes>("HandicapTypes")
.value("NO_HANDICAP", NO_HANDICAP)
;
python::enum_<GameSpeedTypes>("GameSpeedTypes")
.value("NO_GAMESPEED", NO_GAMESPEED)
;
python::enum_<TurnTimerTypes>("TurnTimerTypes")
.value("NO_TURNTIMER", NO_TURNTIMER)
;
python::enum_<EraTypes>("EraTypes")
.value("NO_ERA", NO_ERA)
;
python::enum_<CivilizationTypes>("CivilizationTypes")
.value("NO_CIVILIZATION", NO_CIVILIZATION)
;
python::enum_<LeaderHeadTypes>("LeaderHeadTypes")
.value("NO_LEADER", NO_LEADER)
;
python::enum_<ArtStyleTypes>("ArtStyleTypes")
.value("NO_ARTSTYLE", NO_ARTSTYLE)
;
python::enum_<UnitArtStyleTypes>("UnitArtStyleTypes")
.value("NO_UNIT_ARTSTYLE", NO_UNIT_ARTSTYLE)
;
python::enum_<CitySizeTypes>("CitySizeTypes")
.value("NO_CITYSIZE", NO_CITYSIZE)
.value("CITYSIZE_SMALL", CITYSIZE_SMALL)
.value("CITYSIZE_MEDIUM", CITYSIZE_MEDIUM)
.value("CITYSIZE_LARGE", CITYSIZE_LARGE)
.value("NUM_CITYSIZE_TYPES", NUM_CITYSIZE_TYPES)
;
python::enum_<FootstepAudioTypes>("FootstepAudioTypes")
.value("NO_FOOTSTEPAUDIO", NO_FOOTSTEPAUDIO)
;
python::enum_<FootstepAudioTags>("FootstepAudioTags")
.value("NO_FOOTSTEPAUDIO_TAG", NO_FOOTSTEPAUDIO_TAG)
;
python::enum_<ChatTargetTypes>("ChatTargetTypes")
.value("NO_CHATTARGET", NO_CHATTARGET)
.value("CHATTARGET_ALL", CHATTARGET_ALL)
.value("CHATTARGET_TEAM", CHATTARGET_TEAM)
;
python::enum_<VoiceTargetTypes>("VoiceTargetTypes")
.value("NO_VOICETARGET", NO_VOICETARGET)
.value("VOICETARGET_DIPLO", VOICETARGET_DIPLO)
.value("VOICETARGET_TEAM", VOICETARGET_TEAM)
.value("VOICETARGET_ALL", VOICETARGET_ALL)
.value("NUM_VOICETARGETS", NUM_VOICETARGETS)
;
python::enum_<TeamTypes>("TeamTypes")
.value("NO_TEAM", NO_TEAM)
;
python::enum_<PlayerTypes>("PlayerTypes")
.value("NO_PLAYER", NO_PLAYER)
;
python::enum_<TraitTypes>("TraitTypes")
.value("NO_TRAIT", NO_TRAIT)
;
python::enum_<OrderTypes>("OrderTypes")
.value("NO_ORDER", NO_ORDER)
.value("ORDER_TRAIN", ORDER_TRAIN)
.value("ORDER_CONSTRUCT", ORDER_CONSTRUCT)
.value("ORDER_CREATE", ORDER_CREATE)
.value("ORDER_MAINTAIN", ORDER_MAINTAIN)
.value("NUM_ORDER_TYPES", NUM_ORDER_TYPES)
;
python::enum_<TaskTypes>("TaskTypes")
.value("TASK_RAZE", TASK_RAZE)
.value("TASK_DISBAND", TASK_DISBAND)
.value("TASK_GIFT", TASK_GIFT)
.value("TASK_SET_AUTOMATED_CITIZENS", TASK_SET_AUTOMATED_CITIZENS)
.value("TASK_SET_AUTOMATED_PRODUCTION", TASK_SET_AUTOMATED_PRODUCTION)
.value("TASK_SET_EMPHASIZE", TASK_SET_EMPHASIZE)
.value("TASK_CHANGE_SPECIALIST", TASK_CHANGE_SPECIALIST)
.value("TASK_CHANGE_WORKING_PLOT", TASK_CHANGE_WORKING_PLOT)
.value("TASK_CLEAR_WORKING_OVERRIDE", TASK_CLEAR_WORKING_OVERRIDE)
.value("TASK_HURRY", TASK_HURRY)
.value("TASK_CONSCRIPT", TASK_HURRY)
.value("TASK_CLEAR_ORDERS", TASK_CLEAR_ORDERS)
.value("TASK_RALLY_PLOT", TASK_RALLY_PLOT)
.value("TASK_CLEAR_RALLY_PLOT", TASK_CLEAR_RALLY_PLOT)
.value("TASK_LIBERATE", TASK_LIBERATE)
.value("NUM_TASK_TYPES", NUM_TASK_TYPES)
;
python::enum_<BuildingClassTypes>("BuildingClassTypes")
.value("NO_BUILDINGCLASS", NO_BUILDINGCLASS)
;
python::enum_<BuildingTypes>("BuildingTypes")
.value("NO_BUILDING", NO_BUILDING)
;
python::enum_<SpecialBuildingTypes>("SpecialBuildingTypes")
.value("NO_SPECIALBUILDING", NO_SPECIALBUILDING)
;
python::enum_<ProjectTypes>("ProjectTypes")
.value("NO_PROJECT", NO_PROJECT)
;
python::enum_<ProcessTypes>("ProcessTypes")
.value("NO_PROCESS", NO_PROCESS)
;
python::enum_<VoteTypes>("VoteTypes")
.value("NO_VOTE", NO_VOTE)
;
python::enum_<PlayerVoteTypes>("PlayerVoteTypes")
.value("NO_PLAYER_VOTE_CHECKED", NO_PLAYER_VOTE_CHECKED)
.value("PLAYER_VOTE_NEVER", PLAYER_VOTE_NEVER)
.value("PLAYER_VOTE_ABSTAIN", PLAYER_VOTE_ABSTAIN)
.value("PLAYER_VOTE_NO", PLAYER_VOTE_NO)
.value("PLAYER_VOTE_YES", PLAYER_VOTE_YES)
.value("NO_PLAYER_VOTE", NO_PLAYER_VOTE)
;
python::enum_<InfoBarTypes>("InfoBarTypes")
.value("INFOBAR_STORED", INFOBAR_STORED)
.value("INFOBAR_RATE", INFOBAR_RATE)
.value("INFOBAR_RATE_EXTRA", INFOBAR_RATE_EXTRA)
.value("INFOBAR_EMPTY", INFOBAR_EMPTY)
.value("NUM_INFOBAR_TYPES", NUM_INFOBAR_TYPES)
;
python::enum_<HealthBarTypes>("HealthBarTypes")
.value("HEALTHBAR_ALIVE_ATTACK", HEALTHBAR_ALIVE_ATTACK)
.value("HEALTHBAR_ALIVE_DEFEND", HEALTHBAR_ALIVE_DEFEND)
.value("HEALTHBAR_DEAD", HEALTHBAR_DEAD)
.value("NUM_HEALTHBAR_TYPES", NUM_HEALTHBAR_TYPES)
;
python::enum_<ConceptTypes>("ConceptTypes")
.value("NO_CONCEPT", NO_CONCEPT)
;
python::enum_<NewConceptTypes>("NewConceptTypes")
.value("NO_NEW_CONCEPT", NO_NEW_CONCEPT)
;
python::enum_<CalendarTypes>("CalendarTypes")
.value("CALENDAR_DEFAULT", CALENDAR_DEFAULT)
.value("CALENDAR_BI_YEARLY", CALENDAR_BI_YEARLY)
.value("CALENDAR_YEARS", CALENDAR_YEARS)
.value("CALENDAR_TURNS", CALENDAR_TURNS)
.value("CALENDAR_SEASONS", CALENDAR_SEASONS)
.value("CALENDAR_MONTHS", CALENDAR_MONTHS)
.value("CALENDAR_WEEKS", CALENDAR_WEEKS)
;
python::enum_<SeasonTypes>("SeasonTypes")
.value("NO_SEASON", NO_SEASON)
;
python::enum_<MonthTypes>("MonthTypes")
.value("NO_MONTH", NO_MONTH)
;
python::enum_<DenialTypes>("DenialTypes")
.value("NO_DENIAL", NO_DENIAL)
.value("DENIAL_UNKNOWN", DENIAL_UNKNOWN)
.value("DENIAL_NEVER", DENIAL_NEVER)
.value("DENIAL_TOO_MUCH", DENIAL_TOO_MUCH)
.value("DENIAL_MYSTERY", DENIAL_MYSTERY)
.value("DENIAL_JOKING", DENIAL_JOKING)
.value("DENIAL_ANGER_CIVIC", DENIAL_ANGER_CIVIC)
.value("DENIAL_FAVORITE_CIVIC", DENIAL_FAVORITE_CIVIC)
.value("DENIAL_MINORITY_RELIGION", DENIAL_MINORITY_RELIGION)
.value("DENIAL_CONTACT_THEM", DENIAL_CONTACT_THEM)
.value("DENIAL_VICTORY", DENIAL_VICTORY)
.value("DENIAL_ATTITUDE", DENIAL_ATTITUDE)
.value("DENIAL_ATTITUDE_THEM", DENIAL_ATTITUDE_THEM)
.value("DENIAL_TECH_WHORE", DENIAL_TECH_WHORE)
.value("DENIAL_TECH_MONOPOLY", DENIAL_TECH_MONOPOLY)
.value("DENIAL_POWER_US", DENIAL_POWER_US)
.value("DENIAL_POWER_YOU", DENIAL_POWER_YOU)
.value("DENIAL_POWER_THEM", DENIAL_POWER_THEM)
.value("DENIAL_TOO_MANY_WARS", DENIAL_TOO_MANY_WARS)
.value("DENIAL_NO_GAIN", DENIAL_NO_GAIN)
.value("DENIAL_NOT_ALLIED", DENIAL_NOT_ALLIED)
.value("DENIAL_RECENT_CANCEL", DENIAL_RECENT_CANCEL)
.value("DENIAL_WORST_ENEMY", DENIAL_WORST_ENEMY)
.value("DENIAL_POWER_YOUR_ENEMIES", DENIAL_POWER_YOUR_ENEMIES)
.value("DENIAL_TOO_FAR", DENIAL_TOO_FAR)
;
python::enum_<DomainTypes>("DomainTypes")
.value("DOMAIN_SEA", DOMAIN_SEA)
.value("DOMAIN_AIR", DOMAIN_AIR)
.value("DOMAIN_LAND", DOMAIN_LAND)
.value("DOMAIN_IMMOBILE", DOMAIN_IMMOBILE)
.value("NUM_DOMAIN_TYPES", NUM_DOMAIN_TYPES)
;
python::enum_<UnitClassTypes>("UnitClassTypes")
.value("NO_UNITCLASS", NO_UNITCLASS)
;
python::enum_<UnitTypes>("UnitTypes")
.value("NO_UNIT", NO_UNIT)
;
python::enum_<SpecialUnitTypes>("SpecialUnitTypes")
.value("NO_SPECIALUNIT", NO_SPECIALUNIT)
;
python::enum_<UnitCombatTypes>("UnitCombatTypes")
.value("NO_UNITCOMBAT", NO_UNITCOMBAT)
.value("UNITCOMBAT_RECON", UNITCOMBAT_RECON)
.value("UNITCOMBAT_ARCHER", UNITCOMBAT_ARCHER)
.value("UNITCOMBAT_HEAVY_CAVALRY", UNITCOMBAT_HEAVY_CAVALRY)
.value("UNITCOMBAT_LIGHT_CAVALRY", UNITCOMBAT_LIGHT_CAVALRY)
.value("UNITCOMBAT_MELEE", UNITCOMBAT_MELEE)
.value("UNITCOMBAT_SIEGE", UNITCOMBAT_SIEGE)
.value("UNITCOMBAT_GUN", UNITCOMBAT_GUN)
.value("UNITCOMBAT_ARMOR", UNITCOMBAT_ARMOR)
.value("UNITCOMBAT_HELICOPTER", UNITCOMBAT_HELICOPTER)
.value("UNITCOMBAT_NAVAL", UNITCOMBAT_NAVAL)
.value("UNITCOMBAT_AIR", UNITCOMBAT_AIR)
.value("UNITCOMBAT_SPY", UNITCOMBAT_SPY)
;
python::enum_<UnitAITypes>("UnitAITypes")
.value("NO_UNITAI", NO_UNITAI)
.value("UNITAI_UNKNOWN", UNITAI_UNKNOWN)
.value("UNITAI_ANIMAL", UNITAI_ANIMAL)
.value("UNITAI_SETTLE", UNITAI_SETTLE)
.value("UNITAI_WORKER", UNITAI_WORKER)
.value("UNITAI_ATTACK", UNITAI_ATTACK)
.value("UNITAI_ATTACK_CITY", UNITAI_ATTACK_CITY)
.value("UNITAI_COLLATERAL", UNITAI_COLLATERAL)
.value("UNITAI_PILLAGE", UNITAI_PILLAGE)
.value("UNITAI_RESERVE", UNITAI_RESERVE)
.value("UNITAI_COUNTER", UNITAI_COUNTER)
.value("UNITAI_CITY_DEFENSE", UNITAI_CITY_DEFENSE)
.value("UNITAI_CITY_COUNTER", UNITAI_CITY_COUNTER)
.value("UNITAI_CITY_SPECIAL", UNITAI_CITY_SPECIAL)
.value("UNITAI_EXPLORE", UNITAI_EXPLORE)
.value("UNITAI_MISSIONARY", UNITAI_MISSIONARY)
.value("UNITAI_PROPHET", UNITAI_PROPHET)
.value("UNITAI_ARTIST", UNITAI_ARTIST)
.value("UNITAI_SCIENTIST", UNITAI_SCIENTIST)
.value("UNITAI_GENERAL", UNITAI_GENERAL)
.value("UNITAI_MERCHANT", UNITAI_MERCHANT)
.value("UNITAI_ENGINEER", UNITAI_ENGINEER)
.value("UNITAI_SPY", UNITAI_SPY)
.value("UNITAI_ICBM", UNITAI_ICBM)
.value("UNITAI_WORKER_SEA", UNITAI_WORKER_SEA)
.value("UNITAI_ATTACK_SEA", UNITAI_ATTACK_SEA)
.value("UNITAI_RESERVE_SEA", UNITAI_RESERVE_SEA)
.value("UNITAI_ESCORT_SEA", UNITAI_ESCORT_SEA)
.value("UNITAI_EXPLORE_SEA", UNITAI_EXPLORE_SEA)
.value("UNITAI_ASSAULT_SEA", UNITAI_ASSAULT_SEA)
.value("UNITAI_SETTLER_SEA", UNITAI_SETTLER_SEA)
.value("UNITAI_MISSIONARY_SEA", UNITAI_MISSIONARY_SEA)
.value("UNITAI_SPY_SEA", UNITAI_SPY_SEA)
.value("UNITAI_CARRIER_SEA", UNITAI_CARRIER_SEA)
.value("UNITAI_MISSILE_CARRIER_SEA", UNITAI_MISSILE_CARRIER_SEA)
.value("UNITAI_PIRATE_SEA", UNITAI_PIRATE_SEA)
.value("UNITAI_ATTACK_AIR", UNITAI_ATTACK_AIR)
.value("UNITAI_DEFENSE_AIR", UNITAI_DEFENSE_AIR)
.value("UNITAI_CARRIER_AIR", UNITAI_CARRIER_AIR)
.value("UNITAI_MISSILE_AIR", UNITAI_MISSILE_AIR)
.value("UNITAI_PARADROP", UNITAI_PARADROP)
.value("UNITAI_ATTACK_CITY_LEMMING", UNITAI_ATTACK_CITY_LEMMING)
.value("NUM_UNITAI_TYPES", NUM_UNITAI_TYPES)
;
python::enum_<InvisibleTypes>("InvisibleTypes")
.value("NO_INVISIBLE", NO_INVISIBLE)
;
python::enum_<VoteSourceTypes>("VoteSourceTypes")
.value("NO_VOTESOURCE", NO_VOTESOURCE)
;
python::enum_<ProbabilityTypes>("ProbabilityTypes")
.value("NO_PROBABILITY", NO_PROBABILITY)
.value("PROBABILITY_LOW", PROBABILITY_LOW)
.value("PROBABILITY_REAL", PROBABILITY_REAL)
.value("PROBABILITY_HIGH", PROBABILITY_HIGH)
;
python::enum_<ActivityTypes>("ActivityTypes")
.value("NO_ACTIVITY", NO_ACTIVITY)
.value("ACTIVITY_AWAKE", ACTIVITY_AWAKE)
.value("ACTIVITY_HOLD", ACTIVITY_HOLD)
.value("ACTIVITY_SLEEP", ACTIVITY_SLEEP)
.value("ACTIVITY_HEAL", ACTIVITY_HEAL)
.value("ACTIVITY_SENTRY", ACTIVITY_SENTRY)
.value("ACTIVITY_INTERCEPT", ACTIVITY_INTERCEPT)
.value("ACTIVITY_MISSION", ACTIVITY_MISSION)
.value("ACTIVITY_PATROL", ACTIVITY_PATROL)
.value("ACTIVITY_PLUNDER", ACTIVITY_PLUNDER)
// BUG - Sentry Actions - start
#ifdef _MOD_SENTRY
.value("ACTIVITY_SENTRY_WHILE_HEAL", ACTIVITY_SENTRY_WHILE_HEAL)
.value("ACTIVITY_SENTRY_NAVAL_UNITS", ACTIVITY_SENTRY_NAVAL_UNITS)
.value("ACTIVITY_SENTRY_LAND_UNITS", ACTIVITY_SENTRY_LAND_UNITS)
#endif
// BUG - Sentry Actions - end
.value("NUM_ACTIVITY_TYPES", NUM_ACTIVITY_TYPES)
;
python::enum_<AutomateTypes>("AutomateTypes")
.value("NO_AUTOMATE", NO_AUTOMATE)
.value("AUTOMATE_BUILD", AUTOMATE_BUILD)
.value("AUTOMATE_NETWORK", AUTOMATE_NETWORK)
.value("AUTOMATE_CITY", AUTOMATE_CITY)
.value("AUTOMATE_EXPLORE", AUTOMATE_EXPLORE)
.value("AUTOMATE_RELIGION", AUTOMATE_RELIGION)
.value("NUM_AUTOMATE_TYPES", NUM_AUTOMATE_TYPES)
;
python::enum_<MissionTypes>("MissionTypes")
.value("NO_MISSION", NO_MISSION)
.value("MISSION_MOVE_TO", MISSION_MOVE_TO)
.value("MISSION_ROUTE_TO", MISSION_ROUTE_TO)
.value("MISSION_MOVE_TO_UNIT", MISSION_MOVE_TO_UNIT)
.value("MISSION_SKIP", MISSION_SKIP)
.value("MISSION_SLEEP", MISSION_SLEEP)
.value("MISSION_FORTIFY", MISSION_FORTIFY)
.value("MISSION_PLUNDER", MISSION_PLUNDER)
.value("MISSION_AIRPATROL", MISSION_AIRPATROL)
.value("MISSION_SEAPATROL", MISSION_SEAPATROL)
.value("MISSION_HEAL", MISSION_HEAL)
.value("MISSION_SENTRY", MISSION_SENTRY)
.value("MISSION_AIRLIFT", MISSION_AIRLIFT)
.value("MISSION_NUKE", MISSION_NUKE)
.value("MISSION_RECON", MISSION_RECON)
.value("MISSION_PARADROP", MISSION_PARADROP)
.value("MISSION_AIRBOMB", MISSION_AIRBOMB)
.value("MISSION_RANGE_ATTACK", MISSION_RANGE_ATTACK)
.value("MISSION_BOMBARD", MISSION_BOMBARD)
.value("MISSION_PILLAGE", MISSION_PILLAGE)
.value("MISSION_SABOTAGE", MISSION_SABOTAGE)
.value("MISSION_DESTROY", MISSION_DESTROY)
.value("MISSION_STEAL_PLANS", MISSION_STEAL_PLANS)
.value("MISSION_FOUND", MISSION_FOUND)
.value("MISSION_SPREAD", MISSION_SPREAD)
.value("MISSION_SPREAD_CORPORATION", MISSION_SPREAD_CORPORATION)
.value("MISSION_JOIN", MISSION_JOIN)
.value("MISSION_CONSTRUCT", MISSION_CONSTRUCT)
.value("MISSION_DISCOVER", MISSION_DISCOVER)
.value("MISSION_HURRY", MISSION_HURRY)
.value("MISSION_TRADE", MISSION_TRADE)
.value("MISSION_GREAT_WORK", MISSION_GREAT_WORK)
.value("MISSION_INFILTRATE", MISSION_INFILTRATE)
.value("MISSION_LEAD", MISSION_LEAD)
.value("MISSION_ESPIONAGE", MISSION_ESPIONAGE)
.value("MISSION_RESOLVE_CRISIS", MISSION_RESOLVE_CRISIS)
.value("MISSION_REFORM_GOVERNMENT", MISSION_REFORM_GOVERNMENT)
.value("MISSION_DIPLOMATIC_MISSION", MISSION_DIPLOMATIC_MISSION)
.value("MISSION_PERSECUTE", MISSION_PERSECUTE)
.value("MISSION_GREAT_MISSION", MISSION_GREAT_MISSION)
// BUG - Sentry Actions - start
#ifdef _MOD_SENTRY
.value("MISSION_SENTRY_WHILE_HEAL", MISSION_SENTRY_WHILE_HEAL)
.value("MISSION_SENTRY_NAVAL_UNITS", MISSION_SENTRY_NAVAL_UNITS)
.value("MISSION_SENTRY_LAND_UNITS", MISSION_SENTRY_LAND_UNITS)
.value("MISSION_MOVE_TO_SENTRY", MISSION_MOVE_TO_SENTRY)
#endif
// BUG - Sentry Actions - end
.value("MISSION_GOLDEN_AGE", MISSION_GOLDEN_AGE)
.value("MISSION_BUILD", MISSION_BUILD)
.value("MISSION_BEGIN_COMBAT", MISSION_BEGIN_COMBAT )
.value("MISSION_END_COMBAT", MISSION_END_COMBAT )
.value("MISSION_AIRSTRIKE", MISSION_AIRSTRIKE )
.value("MISSION_SURRENDER", MISSION_SURRENDER )
.value("MISSION_CAPTURED", MISSION_CAPTURED )
.value("MISSION_IDLE", MISSION_IDLE )
.value("MISSION_DIE", MISSION_DIE )
.value("MISSION_DAMAGE", MISSION_DAMAGE )
.value("MISSION_MULTI_SELECT", MISSION_MULTI_SELECT )
.value("MISSION_MULTI_DESELECT", MISSION_MULTI_DESELECT )
.value("NUM_MISSION_TYPES", NUM_MISSION_TYPES )
;
python::enum_<MissionAITypes>("MissionAITypes")
.value("NO_MISSIONAI", NO_MISSIONAI)
.value("MISSIONAI_SHADOW", MISSIONAI_SHADOW)
.value("MISSIONAI_GROUP", MISSIONAI_GROUP)
.value("MISSIONAI_LOAD_ASSAULT", MISSIONAI_LOAD_ASSAULT)
.value("MISSIONAI_LOAD_SETTLER", MISSIONAI_LOAD_SETTLER)
.value("MISSIONAI_LOAD_SPECIAL", MISSIONAI_LOAD_SPECIAL)
.value("MISSIONAI_GUARD_CITY", MISSIONAI_GUARD_CITY)
.value("MISSIONAI_GUARD_BONUS", MISSIONAI_GUARD_BONUS)
.value("MISSIONAI_GUARD_TRADE_NET", MISSIONAI_GUARD_TRADE_NET)
.value("MISSIONAI_GUARD_SPY", MISSIONAI_GUARD_SPY)
.value("MISSIONAI_ATTACK_SPY", MISSIONAI_ATTACK_SPY)
.value("MISSIONAI_SPREAD", MISSIONAI_SPREAD)
.value("MISSIONAI_SPREAD_CORPORATION", MISSIONAI_SPREAD_CORPORATION)
.value("MISSIONAI_CONSTRUCT", MISSIONAI_CONSTRUCT)
.value("MISSIONAI_HURRY", MISSIONAI_HURRY)
.value("MISSIONAI_GREAT_WORK", MISSIONAI_GREAT_WORK)
.value("MISSIONAI_EXPLORE", MISSIONAI_EXPLORE)
.value("MISSIONAI_BLOCKADE", MISSIONAI_BLOCKADE)
.value("MISSIONAI_PILLAGE", MISSIONAI_PILLAGE)
.value("MISSIONAI_FOUND", MISSIONAI_FOUND)
.value("MISSIONAI_BUILD", MISSIONAI_BUILD)
.value("MISSIONAI_ASSAULT", MISSIONAI_ASSAULT)
.value("MISSIONAI_CARRIER", MISSIONAI_CARRIER)
.value("MISSIONAI_PICKUP", MISSIONAI_PICKUP)
.value("MISSIONAI_CIRCUMNAVIGATE", MISSIONAI_CIRCUMNAVIGATE)
;
// any additions need to be reflected in GlobalTypes.xml
python::enum_<CommandTypes>("CommandTypes")
.value("NO_COMMAND", NO_COMMAND)
.value("COMMAND_PROMOTION", COMMAND_PROMOTION)
.value("COMMAND_UPGRADE", COMMAND_UPGRADE)
.value("COMMAND_AUTOMATE", COMMAND_AUTOMATE)
.value("COMMAND_WAKE", COMMAND_WAKE)
.value("COMMAND_CANCEL", COMMAND_CANCEL)
.value("COMMAND_CANCEL_ALL", COMMAND_CANCEL_ALL)
.value("COMMAND_STOP_AUTOMATION", COMMAND_STOP_AUTOMATION)
.value("COMMAND_DELETE", COMMAND_DELETE)
.value("COMMAND_GIFT", COMMAND_GIFT)
.value("COMMAND_LOAD", COMMAND_LOAD)
.value("COMMAND_LOAD_UNIT", COMMAND_LOAD_UNIT)
.value("COMMAND_UNLOAD", COMMAND_UNLOAD)
.value("COMMAND_UNLOAD_ALL", COMMAND_UNLOAD_ALL)
.value("COMMAND_HOTKEY", COMMAND_HOTKEY)
.value("NUM_COMMAND_TYPES", NUM_COMMAND_TYPES)
;
python::enum_<ControlTypes>("ControlTypes")
.value("NO_CONTROL", NO_CONTROL)
.value("CONTROL_CENTERONSELECTION", CONTROL_CENTERONSELECTION)
.value("CONTROL_SELECTYUNITTYPE", CONTROL_SELECTYUNITTYPE)
.value("CONTROL_SELECTYUNITALL", CONTROL_SELECTYUNITALL)
.value("CONTROL_SELECTCITY", CONTROL_SELECTCITY)
.value("CONTROL_SELECTCAPITAL", CONTROL_SELECTCAPITAL)
.value("CONTROL_NEXTCITY", CONTROL_NEXTCITY)
.value("CONTROL_PREVCITY", CONTROL_PREVCITY)
.value("CONTROL_NEXTUNIT", CONTROL_NEXTUNIT)
.value("CONTROL_PREVUNIT", CONTROL_PREVUNIT)
.value("CONTROL_CYCLEUNIT", CONTROL_CYCLEUNIT)
.value("CONTROL_CYCLEUNIT_ALT", CONTROL_CYCLEUNIT_ALT)
.value("CONTROL_CYCLEWORKER", CONTROL_CYCLEWORKER)
.value("CONTROL_LASTUNIT", CONTROL_LASTUNIT)
.value("CONTROL_ENDTURN", CONTROL_ENDTURN)
.value("CONTROL_ENDTURN_ALT", CONTROL_ENDTURN_ALT)
.value("CONTROL_FORCEENDTURN", CONTROL_FORCEENDTURN)
.value("CONTROL_AUTOMOVES", CONTROL_AUTOMOVES)
.value("CONTROL_PING", CONTROL_PING)
.value("CONTROL_SIGN", CONTROL_SIGN)
.value("CONTROL_GRID", CONTROL_GRID)
.value("CONTROL_BARE_MAP", CONTROL_BARE_MAP)
.value("CONTROL_YIELDS", CONTROL_YIELDS)
.value("CONTROL_RESOURCE_ALL", CONTROL_RESOURCE_ALL)
.value("CONTROL_UNIT_ICONS", CONTROL_UNIT_ICONS)
.value("CONTROL_GLOBELAYER", CONTROL_GLOBELAYER)
.value("CONTROL_SCORES", CONTROL_SCORES)
.value("CONTROL_LOAD_GAME", CONTROL_LOAD_GAME)
.value("CONTROL_OPTIONS_SCREEN", CONTROL_OPTIONS_SCREEN)
.value("CONTROL_RETIRE", CONTROL_RETIRE)
.value("CONTROL_SAVE_GROUP", CONTROL_SAVE_GROUP)
.value("CONTROL_SAVE_NORMAL", CONTROL_SAVE_NORMAL)
.value("CONTROL_QUICK_SAVE", CONTROL_QUICK_SAVE)
.value("CONTROL_QUICK_LOAD", CONTROL_QUICK_LOAD)
.value("CONTROL_ORTHO_CAMERA", CONTROL_ORTHO_CAMERA)
.value("CONTROL_CYCLE_CAMERA_FLYING_MODES", CONTROL_CYCLE_CAMERA_FLYING_MODES)
.value("CONTROL_ISOMETRIC_CAMERA_LEFT", CONTROL_ISOMETRIC_CAMERA_LEFT)
.value("CONTROL_ISOMETRIC_CAMERA_RIGHT", CONTROL_ISOMETRIC_CAMERA_RIGHT)
.value("CONTROL_FLYING_CAMERA", CONTROL_FLYING_CAMERA)
.value("CONTROL_MOUSE_FLYING_CAMERA", CONTROL_MOUSE_FLYING_CAMERA)
.value("CONTROL_TOP_DOWN_CAMERA", CONTROL_TOP_DOWN_CAMERA)
.value("CONTROL_CIVILOPEDIA", CONTROL_CIVILOPEDIA)
.value("CONTROL_RELIGION_SCREEN", CONTROL_RELIGION_SCREEN)
.value("CONTROL_CORPORATION_SCREEN", CONTROL_CORPORATION_SCREEN)
.value("CONTROL_CIVICS_SCREEN", CONTROL_CIVICS_SCREEN)
.value("CONTROL_FOREIGN_SCREEN", CONTROL_FOREIGN_SCREEN)
.value("CONTROL_FINANCIAL_SCREEN", CONTROL_FINANCIAL_SCREEN)
.value("CONTROL_MILITARY_SCREEN", CONTROL_MILITARY_SCREEN)
.value("CONTROL_TECH_CHOOSER", CONTROL_TECH_CHOOSER)
.value("CONTROL_TURN_LOG", CONTROL_TURN_LOG)
.value("CONTROL_CHAT_ALL", CONTROL_CHAT_ALL)
.value("CONTROL_CHAT_TEAM", CONTROL_CHAT_TEAM)
.value("CONTROL_DOMESTIC_SCREEN", CONTROL_DOMESTIC_SCREEN)
.value("CONTROL_VICTORY_SCREEN", CONTROL_VICTORY_SCREEN)
.value("CONTROL_INFO", CONTROL_INFO)
.value("CONTROL_GLOBE_VIEW", CONTROL_GLOBE_VIEW)
.value("CONTROL_DETAILS", CONTROL_DETAILS)
.value("CONTROL_ADMIN_DETAILS", CONTROL_ADMIN_DETAILS)
.value("CONTROL_HALL_OF_FAME", CONTROL_HALL_OF_FAME)
.value("CONTROL_WORLD_BUILDER", CONTROL_WORLD_BUILDER)
.value("CONTROL_DIPLOMACY", CONTROL_DIPLOMACY)
.value("CONTROL_SELECT_HEALTHY", CONTROL_SELECT_HEALTHY)
.value("CONTROL_ESPIONAGE_SCREEN", CONTROL_ESPIONAGE_SCREEN)
.value("CONTROL_FREE_COLONY", CONTROL_FREE_COLONY)
.value("CONTROL_STABILITY_OVERLAY", CONTROL_STABILITY_OVERLAY) // edead
.value("NUM_CONTROL_TYPES", NUM_CONTROL_TYPES)
;
python::enum_<PromotionTypes>("PromotionTypes")
.value("NO_PROMOTION", NO_PROMOTION)
;
python::enum_<TechTypes>("TechTypes")
.value("NO_TECH", NO_TECH)
;
python::enum_<SpecialistTypes>("SpecialistTypes")
.value("NO_SPECIALIST", NO_SPECIALIST)
;
python::enum_<ReligionTypes>("ReligionTypes")
.value("NO_RELIGION", NO_RELIGION)
;
python::enum_<CorporationTypes>("CorporationTypes")
.value("NO_CORPORATION", NO_CORPORATION)
;
python::enum_<HurryTypes>("HurryTypes")
.value("NO_HURRY", NO_HURRY)
;
python::enum_<UpkeepTypes>("UpkeepTypes")
.value("NO_UPKEEP", NO_UPKEEP)
;
python::enum_<CultureLevelTypes>("CultureLevelTypes")
.value("NO_CULTURELEVEL", NO_CULTURELEVEL)
;
python::enum_<CivicOptionTypes>("CivicOptionTypes")
.value("NO_CIVICOPTION", NO_CIVICOPTION)
;
python::enum_<CivicTypes>("CivicTypes")
.value("NO_CIVIC", NO_CIVIC)
;
python::enum_<WarPlanTypes>("WarPlanTypes")
.value("NO_WARPLAN", NO_WARPLAN)
.value("WARPLAN_ATTACKED_RECENT", WARPLAN_ATTACKED_RECENT)
.value("WARPLAN_ATTACKED", WARPLAN_ATTACKED)
.value("WARPLAN_PREPARING_LIMITED", WARPLAN_PREPARING_LIMITED)
.value("WARPLAN_PREPARING_TOTAL", WARPLAN_PREPARING_TOTAL)
.value("WARPLAN_LIMITED", WARPLAN_LIMITED)
.value("WARPLAN_TOTAL", WARPLAN_TOTAL)
.value("WARPLAN_DOGPILE", WARPLAN_DOGPILE)
;
python::enum_<AreaAITypes>("AreaAITypes")
.value("NO_AREAAI", NO_AREAAI)
.value("AREAAI_OFFENSIVE", AREAAI_OFFENSIVE)
.value("AREAAI_DEFENSIVE", AREAAI_DEFENSIVE)
.value("AREAAI_MASSING", AREAAI_MASSING)
.value("AREAAI_ASSAULT", AREAAI_ASSAULT)
.value("AREAAI_NEUTRAL", AREAAI_NEUTRAL)
;
python::enum_<EndTurnButtonStates>("EndTurnButtonStates")
.value("END_TURN_GO", END_TURN_GO)
.value("END_TURN_OVER_HIGHLIGHT", END_TURN_OVER_HIGHLIGHT)
.value("END_TURN_OVER_DARK", END_TURN_OVER_DARK)
.value("NUM_END_TURN_STATES", NUM_END_TURN_STATES)
;
python::enum_<FogOfWarModeTypes>("FogOfWarModeTypes")
.value("FOGOFWARMODE_OFF", FOGOFWARMODE_OFF)
.value("FOGOFWARMODE_UNEXPLORED", FOGOFWARMODE_UNEXPLORED)
.value("NUM_FOGOFWARMODE_TYPES", NUM_FOGOFWARMODE_TYPES)
;
python::enum_<AnimationTypes>("AnimationTypes")
.value("NONE_ANIMATION", NONE_ANIMATION)
.value("BONUSANIMATION_UNIMPROVED", BONUSANIMATION_UNIMPROVED)
.value("BONUSANIMATION_NOT_WORKED", BONUSANIMATION_NOT_WORKED)
.value("BONUSANIMATION_WORKED", BONUSANIMATION_WORKED)
.value("IMPROVEMENTANIMATION_OFF", IMPROVEMENTANIMATION_OFF)
.value("IMPROVEMENTANIMATION_ON", IMPROVEMENTANIMATION_ON)
.value("IMPROVEMENTANIMATION_OFF_EXTRA", IMPROVEMENTANIMATION_OFF_EXTRA)
.value("IMPROVEMENTANIMATION_ON_EXTRA_1", IMPROVEMENTANIMATION_ON_EXTRA_1)
.value("IMPROVEMENTANIMATION_ON_EXTRA_2", IMPROVEMENTANIMATION_ON_EXTRA_2)
.value("IMPROVEMENTANIMATION_ON_EXTRA_3", IMPROVEMENTANIMATION_ON_EXTRA_3)
.value("IMPROVEMENTANIMATION_ON_EXTRA_4", IMPROVEMENTANIMATION_ON_EXTRA_4)
;
python::enum_<EntityEventTypes>("EntityEventTypes")
.value( "ENTITY_EVENT_NONE", ENTITY_EVENT_NONE )
;
python::enum_<AnimationPathTypes>("AnimationPathTypes")
.value( "ANIMATIONPATH_NONE", ANIMATIONPATH_NONE )
.value( "ANIMATIONPATH_IDLE", ANIMATIONPATH_IDLE )
.value( "ANIMATIONPATH_MOVE", ANIMATIONPATH_MOVE )
.value( "ANIMATIONPATH_RANDOMIZE_ANIMATION_SET", ANIMATIONPATH_RANDOMIZE_ANIMATION_SET )
.value( "ANIMATIONPATH_NUKE_STRIKE", ANIMATIONPATH_NUKE_STRIKE )
.value( "ANIMATIONPATH_MELEE_STRIKE", ANIMATIONPATH_MELEE_STRIKE )
.value( "ANIMATIONPATH_MELEE_HURT", ANIMATIONPATH_MELEE_HURT )
.value( "ANIMATIONPATH_MELEE_DIE", ANIMATIONPATH_MELEE_DIE )
.value( "ANIMATIONPATH_MELEE_FORTIFIED", ANIMATIONPATH_MELEE_FORTIFIED )
.value( "ANIMATIONPATH_MELEE_DIE_FADE", ANIMATIONPATH_MELEE_DIE_FADE )
.value( "ANIMATIONPATH_RANGED_STRIKE", ANIMATIONPATH_RANGED_STRIKE )
.value( "ANIMATIONPATH_RANGED_DIE", ANIMATIONPATH_RANGED_DIE )
.value( "ANIMATIONPATH_RANGED_FORTIFIED", ANIMATIONPATH_RANGED_FORTIFIED )
.value( "ANIMATIONPATH_RANGED_RUNHIT", ANIMATIONPATH_RANGED_RUNHIT )
.value( "ANIMATIONPATH_RANGED_RUNDIE", ANIMATIONPATH_RANGED_RUNDIE )
.value( "ANIMATIONPATH_RANGED_DIE_FADE", ANIMATIONPATH_RANGED_DIE_FADE )
.value( "ANIMATIONPATH_LEADER_COMMAND", ANIMATIONPATH_LEADER_COMMAND )
.value( "ANIMATIONPATH_AIRFADEIN", ANIMATIONPATH_AIRFADEIN )
.value( "ANIMATIONPATH_AIRFADEOUT", ANIMATIONPATH_AIRFADEOUT )
.value( "ANIMATIONPATH_AIRSTRIKE", ANIMATIONPATH_AIRSTRIKE )
.value( "ANIMATIONPATH_AIRBOMB", ANIMATIONPATH_AIRBOMB )
;
python::enum_<AnimationCategoryTypes>("AnimationCategoryTypes")
.value("ANIMCAT_NONE", ANIMCAT_NONE)
;
python::enum_<CursorTypes>("CursorTypes")
.value("NO_CURSOR", NO_CURSOR)
;
python::enum_<TradeableItems>("TradeableItems")
.value("NO_TRADEABLE_ITEMS", TRADE_ITEM_NONE)
.value("TRADE_GOLD", TRADE_GOLD)
.value("TRADE_GOLD_PER_TURN", TRADE_GOLD_PER_TURN)
.value("TRADE_MAPS", TRADE_MAPS)
.value("TRADE_VASSAL", TRADE_VASSAL)
.value("TRADE_SURRENDER", TRADE_SURRENDER)
.value("TRADE_OPEN_BORDERS", TRADE_OPEN_BORDERS)
.value("TRADE_DEFENSIVE_PACT", TRADE_DEFENSIVE_PACT)
.value("TRADE_PERMANENT_ALLIANCE", TRADE_PERMANENT_ALLIANCE)
.value("TRADE_PEACE_TREATY", TRADE_PEACE_TREATY)
.value("NUM_BASIC_ITEMS", NUM_BASIC_ITEMS)
.value("TRADE_TECHNOLOGIES", TRADE_TECHNOLOGIES)
.value("TRADE_RESOURCES", TRADE_RESOURCES)
.value("TRADE_CITIES", TRADE_CITIES)
.value("TRADE_PEACE", TRADE_PEACE)
.value("TRADE_WAR", TRADE_WAR)
.value("TRADE_EMBARGO", TRADE_EMBARGO)
.value("TRADE_CIVIC", TRADE_CIVIC)
.value("TRADE_SLAVE", TRADE_SLAVE) // edead (Leoreth)
.value("TRADE_RELIGION", TRADE_RELIGION)
.value("NUM_TRADEABLE_HEADINGS", NUM_TRADEABLE_HEADINGS)
.value("NUM_TRADEABLE_ITEMS", NUM_TRADEABLE_ITEMS)
;
python::enum_<DiploEventTypes>("DiploEventTypes")
.value("NO_DIPLOEVENT", NO_DIPLOEVENT)
.value("DIPLOEVENT_CONTACT", DIPLOEVENT_CONTACT)
.value("DIPLOEVENT_AI_CONTACT", DIPLOEVENT_AI_CONTACT)
.value("DIPLOEVENT_FAILED_CONTACT", DIPLOEVENT_FAILED_CONTACT)
.value("DIPLOEVENT_GIVE_HELP", DIPLOEVENT_GIVE_HELP)
.value("DIPLOEVENT_REFUSED_HELP", DIPLOEVENT_REFUSED_HELP)
.value("DIPLOEVENT_ACCEPT_DEMAND", DIPLOEVENT_ACCEPT_DEMAND)
.value("DIPLOEVENT_REJECTED_DEMAND", DIPLOEVENT_REJECTED_DEMAND)
.value("DIPLOEVENT_DEMAND_WAR", DIPLOEVENT_DEMAND_WAR)
.value("DIPLOEVENT_CONVERT", DIPLOEVENT_CONVERT)
.value("DIPLOEVENT_NO_CONVERT", DIPLOEVENT_NO_CONVERT)
.value("DIPLOEVENT_REVOLUTION", DIPLOEVENT_REVOLUTION)
.value("DIPLOEVENT_NO_REVOLUTION", DIPLOEVENT_NO_REVOLUTION)
.value("DIPLOEVENT_JOIN_WAR", DIPLOEVENT_JOIN_WAR)
.value("DIPLOEVENT_NO_JOIN_WAR", DIPLOEVENT_NO_JOIN_WAR)
.value("DIPLOEVENT_STOP_TRADING", DIPLOEVENT_STOP_TRADING)
.value("DIPLOEVENT_NO_STOP_TRADING", DIPLOEVENT_NO_STOP_TRADING)
.value("DIPLOEVENT_ASK_HELP", DIPLOEVENT_ASK_HELP)
.value("DIPLOEVENT_MADE_DEMAND", DIPLOEVENT_MADE_DEMAND)
.value("DIPLOEVENT_RESEARCH_TECH", DIPLOEVENT_RESEARCH_TECH)
.value("DIPLOEVENT_TARGET_CITY", DIPLOEVENT_TARGET_CITY)
.value("DIPLOEVENT_MADE_DEMAND_VASSAL", DIPLOEVENT_MADE_DEMAND_VASSAL)
.value("NUM_DIPLOEVENT_TYPES", NUM_DIPLOEVENT_TYPES)
;
python::enum_<DiploCommentTypes>("DiploCommentTypes")
.value("NO_DIPLOCOMMENT", NO_DIPLOCOMMENT)
;
python::enum_<NetContactTypes>("NetContactTypes")
.value("NO_NETCONTACT", NO_NETCONTACT)
.value("NETCONTACT_INITIAL", NETCONTACT_INITIAL)
.value("NETCONTACT_RESPONSE", NETCONTACT_RESPONSE)
.value("NETCONTACT_ESTABLISHED", NETCONTACT_ESTABLISHED)
.value("NETCONTACT_BUSY", NETCONTACT_BUSY)
.value("NUM_NETCONTACT_TYPES", NUM_NETCONTACT_TYPES)
;
python::enum_<ContactTypes>("ContactTypes")
.value("CONTACT_RELIGION_PRESSURE", CONTACT_RELIGION_PRESSURE)
.value("CONTACT_CIVIC_PRESSURE", CONTACT_CIVIC_PRESSURE)
.value("CONTACT_JOIN_WAR", CONTACT_JOIN_WAR)
.value("CONTACT_STOP_TRADING", CONTACT_STOP_TRADING)
.value("CONTACT_GIVE_HELP", CONTACT_GIVE_HELP)
.value("CONTACT_ASK_FOR_HELP", CONTACT_ASK_FOR_HELP)
.value("CONTACT_DEMAND_TRIBUTE", CONTACT_DEMAND_TRIBUTE)
.value("CONTACT_OPEN_BORDERS", CONTACT_OPEN_BORDERS)
.value("CONTACT_DEFENSIVE_PACT", CONTACT_DEFENSIVE_PACT)
.value("CONTACT_PERMANENT_ALLIANCE", CONTACT_PERMANENT_ALLIANCE)
.value("CONTACT_PEACE_TREATY", CONTACT_PEACE_TREATY)
.value("CONTACT_TRADE_TECH", CONTACT_TRADE_TECH)
.value("CONTACT_TRADE_BONUS", CONTACT_TRADE_BONUS)
.value("CONTACT_TRADE_MAP", CONTACT_TRADE_MAP)
.value("NUM_CONTACT_TYPES", NUM_CONTACT_TYPES)
;
python::enum_<MemoryTypes>("MemoryTypes")
.value("MEMORY_DECLARED_WAR", MEMORY_DECLARED_WAR)
.value("MEMORY_DECLARED_WAR_ON_FRIEND", MEMORY_DECLARED_WAR_ON_FRIEND)
.value("MEMORY_HIRED_WAR_ALLY", MEMORY_HIRED_WAR_ALLY)
.value("MEMORY_NUKED_US", MEMORY_NUKED_US)
.value("MEMORY_NUKED_FRIEND", MEMORY_NUKED_FRIEND)
.value("MEMORY_RAZED_CITY", MEMORY_RAZED_CITY)
.value("MEMORY_RAZED_HOLY_CITY", MEMORY_RAZED_HOLY_CITY)
.value("MEMORY_SPY_CAUGHT", MEMORY_SPY_CAUGHT)
.value("MEMORY_GIVE_HELP", MEMORY_GIVE_HELP)
.value("MEMORY_REFUSED_HELP", MEMORY_REFUSED_HELP)
.value("MEMORY_ACCEPT_DEMAND", MEMORY_ACCEPT_DEMAND)
.value("MEMORY_REJECTED_DEMAND", MEMORY_REJECTED_DEMAND)
.value("MEMORY_ACCEPTED_RELIGION", MEMORY_ACCEPTED_RELIGION)
.value("MEMORY_DENIED_RELIGION", MEMORY_DENIED_RELIGION)
.value("MEMORY_ACCEPTED_CIVIC", MEMORY_ACCEPTED_CIVIC)
.value("MEMORY_DENIED_CIVIC", MEMORY_DENIED_CIVIC)
.value("MEMORY_ACCEPTED_JOIN_WAR", MEMORY_ACCEPTED_JOIN_WAR)
.value("MEMORY_DENIED_JOIN_WAR", MEMORY_DENIED_JOIN_WAR)
.value("MEMORY_ACCEPTED_STOP_TRADING", MEMORY_ACCEPTED_STOP_TRADING)
.value("MEMORY_DENIED_STOP_TRADING", MEMORY_DENIED_STOP_TRADING)
.value("MEMORY_STOPPED_TRADING", MEMORY_STOPPED_TRADING)
.value("MEMORY_STOPPED_TRADING_RECENT", MEMORY_STOPPED_TRADING_RECENT)
.value("MEMORY_HIRED_TRADE_EMBARGO", MEMORY_HIRED_TRADE_EMBARGO)
.value("MEMORY_MADE_DEMAND", MEMORY_MADE_DEMAND)
.value("MEMORY_MADE_DEMAND_RECENT", MEMORY_MADE_DEMAND_RECENT)
.value("MEMORY_CANCELLED_OPEN_BORDERS", MEMORY_CANCELLED_OPEN_BORDERS)
.value("MEMORY_TRADED_TECH_TO_US", MEMORY_TRADED_TECH_TO_US)
.value("MEMORY_RECEIVED_TECH_FROM_ANY", MEMORY_RECEIVED_TECH_FROM_ANY)
.value("MEMORY_VOTED_AGAINST_US", MEMORY_VOTED_AGAINST_US)
.value("MEMORY_VOTED_FOR_US", MEMORY_VOTED_FOR_US)
.value("MEMORY_EVENT_GOOD_TO_US", MEMORY_EVENT_GOOD_TO_US)
.value("MEMORY_EVENT_BAD_TO_US", MEMORY_EVENT_BAD_TO_US)
.value("MEMORY_LIBERATED_CITIES", MEMORY_LIBERATED_CITIES)
.value("NUM_MEMORY_TYPES", NUM_MEMORY_TYPES)
;
python::enum_<AttitudeTypes>("AttitudeTypes")
.value("NO_ATTITUDE", NO_ATTITUDE)
.value("ATTITUDE_FURIOUS", ATTITUDE_FURIOUS)
.value("ATTITUDE_ANNOYED", ATTITUDE_ANNOYED)
.value("ATTITUDE_CAUTIOUS", ATTITUDE_CAUTIOUS)
.value("ATTITUDE_PLEASED", ATTITUDE_PLEASED)
.value("ATTITUDE_FRIENDLY", ATTITUDE_FRIENDLY)
.value("NUM_ATTITUDE_TYPES", NUM_ATTITUDE_TYPES)
;
python::enum_<LeaderheadAction>("LeaderheadAction")
.value( "NO_LEADERANIM", NO_LEADERANIM )
.value( "LEADERANIM_GREETING", LEADERANIM_GREETING )
.value( "LEADERANIM_FRIENDLY", LEADERANIM_FRIENDLY )
.value( "LEADERANIM_PLEASED", LEADERANIM_PLEASED )
.value( "LEADERANIM_CAUTIOUS", LEADERANIM_CAUTIOUS )
.value( "LEADERANIM_ANNOYED", LEADERANIM_ANNOYED )
.value( "LEADERANIM_FURIOUS", LEADERANIM_FURIOUS )
.value( "LEADERANIM_DISAGREE", LEADERANIM_DISAGREE )
.value( "LEADERANIM_AGREE", LEADERANIM_AGREE )
.value( "NUM_LEADERANIM_TYPES", NUM_LEADERANIM_TYPES )
;
python::enum_<DiplomacyPowerTypes>("DiplomacyPowerTypes")
.value("NO_DIPLOMACYPOWER", NO_DIPLOMACYPOWER)
.value("DIPLOMACYPOWER_WEAKER", DIPLOMACYPOWER_WEAKER)
.value("DIPLOMACYPOWER_EQUAL", DIPLOMACYPOWER_EQUAL)
.value("DIPLOMACYPOWER_STRONGER", DIPLOMACYPOWER_STRONGER)
.value("NUM_DIPLOMACYPOWER_TYPES", NUM_DIPLOMACYPOWER_TYPES)
;
python::enum_<FeatTypes>("FeatTypes")
.value("FEAT_UNITCOMBAT_ARCHER", FEAT_UNITCOMBAT_ARCHER)
.value("FEAT_UNITCOMBAT_MOUNTED", FEAT_UNITCOMBAT_MOUNTED)
.value("FEAT_UNITCOMBAT_MELEE", FEAT_UNITCOMBAT_MELEE)
.value("FEAT_UNITCOMBAT_SIEGE", FEAT_UNITCOMBAT_SIEGE)
.value("FEAT_UNITCOMBAT_GUN", FEAT_UNITCOMBAT_GUN)
.value("FEAT_UNITCOMBAT_ARMOR", FEAT_UNITCOMBAT_ARMOR)
.value("FEAT_UNITCOMBAT_HELICOPTER", FEAT_UNITCOMBAT_HELICOPTER)
.value("FEAT_UNITCOMBAT_NAVAL", FEAT_UNITCOMBAT_NAVAL)
.value("FEAT_UNIT_PRIVATEER", FEAT_UNIT_PRIVATEER)
.value("FEAT_UNIT_SPY", FEAT_UNIT_SPY)
.value("FEAT_NATIONAL_WONDER", FEAT_NATIONAL_WONDER)
.value("FEAT_TRADE_ROUTE", FEAT_TRADE_ROUTE)
.value("FEAT_COPPER_CONNECTED", FEAT_COPPER_CONNECTED)
.value("FEAT_HORSE_CONNECTED", FEAT_HORSE_CONNECTED)
.value("FEAT_IRON_CONNECTED", FEAT_IRON_CONNECTED)
.value("FEAT_LUXURY_CONNECTED", FEAT_LUXURY_CONNECTED)
.value("FEAT_FOOD_CONNECTED", FEAT_FOOD_CONNECTED)
.value("FEAT_POPULATION_HALF_MILLION", FEAT_POPULATION_HALF_MILLION)
.value("FEAT_POPULATION_1_MILLION", FEAT_POPULATION_1_MILLION)
.value("FEAT_POPULATION_2_MILLION", FEAT_POPULATION_2_MILLION)
.value("FEAT_POPULATION_5_MILLION", FEAT_POPULATION_5_MILLION)
.value("FEAT_POPULATION_10_MILLION", FEAT_POPULATION_10_MILLION)
.value("FEAT_POPULATION_20_MILLION", FEAT_POPULATION_20_MILLION)
.value("FEAT_POPULATION_50_MILLION", FEAT_POPULATION_50_MILLION)
.value("FEAT_POPULATION_100_MILLION", FEAT_POPULATION_100_MILLION)
.value("FEAT_POPULATION_200_MILLION", FEAT_POPULATION_200_MILLION)
.value("FEAT_POPULATION_500_MILLION", FEAT_POPULATION_500_MILLION)
.value("FEAT_POPULATION_1_BILLION", FEAT_POPULATION_1_BILLION)
.value("FEAT_POPULATION_2_BILLION", FEAT_POPULATION_2_BILLION)
.value("FEAT_CORPORATION_ENABLED", FEAT_CORPORATION_ENABLED)
.value("FEAT_PAD", FEAT_PAD)
.value("NUM_FEAT_TYPES", NUM_FEAT_TYPES)
;
python::enum_<SaveGameTypes>("SaveGameTypes")
.value("SAVEGAME_NONE", SAVEGAME_NONE)
.value("SAVEGAME_AUTO", SAVEGAME_AUTO)
.value("SAVEGAME_RECOVERY", SAVEGAME_RECOVERY)
.value("SAVEGAME_QUICK", SAVEGAME_QUICK)
.value("SAVEGAME_NORMAL", SAVEGAME_NORMAL)
.value("SAVEGAME_GROUP", SAVEGAME_GROUP)
.value("SAVEGAME_DROP_QUIT", SAVEGAME_DROP_QUIT)
.value("SAVEGAME_DROP_CONTINUE", SAVEGAME_DROP_CONTINUE)
.value("SAVEGAME_PBEM", SAVEGAME_PBEM)
.value("SAVEGAME_REPLAY", SAVEGAME_REPLAY)
.value("NUM_SAVEGAME_TYPES", NUM_SAVEGAME_TYPES)
;
python::enum_<GameType>("GameType")
.value("GAME_NONE", GAME_NONE)
.value("GAME_SP_NEW", GAME_SP_NEW)
.value("GAME_SP_SCENARIO", GAME_SP_SCENARIO)
.value("GAME_SP_LOAD", GAME_SP_LOAD)
.value("GAME_MP_NEW", GAME_MP_NEW)
.value("GAME_MP_SCENARIO", GAME_MP_SCENARIO)
.value("GAME_MP_LOAD", GAME_MP_LOAD)
.value("GAME_HOTSEAT_NEW", GAME_HOTSEAT_NEW)
.value("GAME_HOTSEAT_SCENARIO", GAME_HOTSEAT_SCENARIO)
.value("GAME_HOTSEAT_LOAD", GAME_HOTSEAT_LOAD)
.value("GAME_PBEM_NEW", GAME_PBEM_NEW)
.value("GAME_PBEM_SCENARIO", GAME_PBEM_SCENARIO)
.value("GAME_PBEM_LOAD", GAME_PBEM_LOAD)
.value("GAME_REPLAY", GAME_REPLAY)
.value("NUM_GAMETYPES", NUM_GAMETYPES)
;
python::enum_<GameMode>("GameMode")
.value("NO_GAMEMODE", NO_GAMEMODE)
.value("GAMEMODE_NORMAL", GAMEMODE_NORMAL)
.value("GAMEMODE_PITBOSS", GAMEMODE_PITBOSS)
.value("NUM_GAMEMODES", NUM_GAMEMODES)
;
python::enum_<InterfaceVisibility>("InterfaceVisibility")
.value("INTERFACE_SHOW", INTERFACE_SHOW)
.value("INTERFACE_HIDE", INTERFACE_HIDE)
.value("INTERFACE_HIDE_ALL", INTERFACE_HIDE_ALL)
.value("INTERFACE_MINIMAP_ONLY", INTERFACE_MINIMAP_ONLY)
.value("INTERFACE_ADVANCED_START", INTERFACE_ADVANCED_START)
;
python::enum_<GenericButtonSizes>("GenericButtonSizes")
.value("BUTTON_SIZE_46", BUTTON_SIZE_46)
.value("BUTTON_SIZE_32", BUTTON_SIZE_32)
.value("BUTTON_SIZE_24", BUTTON_SIZE_24)
.value("BUTTON_SIZE_16", BUTTON_SIZE_16)
.value("BUTTON_SIZE_CUSTOM", BUTTON_SIZE_CUSTOM)
;
python::enum_<WorldBuilderPopupTypes>("WorldBuilderPopupTypes")
.value("WBPOPUP_NONE", WBPOPUP_NONE)
.value("WBPOPUP_START", WBPOPUP_START)
.value("WBPOPUP_CITY", WBPOPUP_CITY)
.value("WBPOPUP_UNIT", WBPOPUP_UNIT)
.value("WBPOPUP_PLAYER", WBPOPUP_PLAYER)
.value("WBPOPUP_PLOT", WBPOPUP_PLOT)
.value("WBPOPUP_TERRAIN", WBPOPUP_TERRAIN)
.value("WBPOPUP_FEATURE", WBPOPUP_FEATURE)
.value("WBPOPUP_IMPROVEMENT", WBPOPUP_IMPROVEMENT)
.value("WBPOPUP_GAME", WBPOPUP_GAME)
.value("NUM_WBPOPUP", NUM_WBPOPUP)
;
python::enum_<EventType>("EventType")
.value("EVT_LBUTTONDOWN", EVT_LBUTTONDOWN)
.value("EVT_LBUTTONDBLCLICK", EVT_LBUTTONDBLCLICK)
.value("EVT_RBUTTONDOWN", EVT_RBUTTONDOWN)
.value("EVT_BACK", EVT_BACK)
.value("EVT_FORWARD", EVT_FORWARD)
.value("EVT_KEYDOWN", EVT_KEYDOWN)
.value("EVT_KEYUP", EVT_KEYUP)
;
python::enum_<LoadType>("LoadType")
.value("LOAD_NORMAL", LOAD_NORMAL)
.value("LOAD_INIT", LOAD_INIT)
.value("LOAD_SETUP", LOAD_SETUP)
.value("LOAD_GAMETYPE", LOAD_GAMETYPE)
.value("LOAD_REPLAY", LOAD_REPLAY)
;
python::enum_<FontTypes>("FontTypes")
.value("TITLE_FONT", TITLE_FONT)
.value("GAME_FONT", GAME_FONT)
.value("SMALL_FONT", SMALL_FONT)
.value("MENU_FONT", MENU_FONT)
.value("MENU_HIGHLIGHT_FONT", MENU_HIGHLIGHT_FONT)
;
python::enum_<PanelStyles>("PanelStyles")
.value("PANEL_STYLE_STANDARD",PANEL_STYLE_STANDARD)
.value("PANEL_STYLE_SOLID",PANEL_STYLE_SOLID)
.value("PANEL_STYLE_EMPTY",PANEL_STYLE_EMPTY)
.value("PANEL_STYLE_FLAT",PANEL_STYLE_FLAT)
.value("PANEL_STYLE_IN",PANEL_STYLE_IN)
.value("PANEL_STYLE_OUT",PANEL_STYLE_OUT)
.value("PANEL_STYLE_EXTERNAL",PANEL_STYLE_EXTERNAL)
.value("PANEL_STYLE_DEFAULT",PANEL_STYLE_DEFAULT)
.value("PANEL_STYLE_CIVILPEDIA",PANEL_STYLE_CIVILPEDIA)
.value("PANEL_STYLE_STONE",PANEL_STYLE_STONE)
.value("PANEL_STYLE_BLUELARGE",PANEL_STYLE_BLUELARGE)
.value("PANEL_STYLE_UNITSTAT",PANEL_STYLE_UNITSTAT)
.value("PANEL_STYLE_BLUE50",PANEL_STYLE_BLUE50)
.value("PANEL_STYLE_TOPBAR",PANEL_STYLE_TOPBAR)
.value("PANEL_STYLE_BOTTOMBAR",PANEL_STYLE_BOTTOMBAR)
.value("PANEL_STYLE_TECH",PANEL_STYLE_TECH)
.value("PANEL_STYLE_GAMEHUD_LEFT",PANEL_STYLE_GAMEHUD_LEFT)
.value("PANEL_STYLE_GAMEHUD_RIGHT",PANEL_STYLE_GAMEHUD_RIGHT)
.value("PANEL_STYLE_GAMEHUD_CENTER",PANEL_STYLE_GAMEHUD_CENTER)
.value("PANEL_STYLE_GAMEHUD_STATS",PANEL_STYLE_GAMEHUD_STATS)
.value("PANEL_STYLE_GAME_MAP",PANEL_STYLE_GAME_MAP)
.value("PANEL_STYLE_GAME_TOPBAR",PANEL_STYLE_GAME_TOPBAR)
.value("PANEL_STYLE_HUD_HELP", PANEL_STYLE_HUD_HELP)
.value("PANEL_STYLE_CITY_LEFT",PANEL_STYLE_CITY_LEFT)
.value("PANEL_STYLE_CITY_RIGHT",PANEL_STYLE_CITY_RIGHT)
.value("PANEL_STYLE_CITY_TOP",PANEL_STYLE_CITY_TOP)
.value("PANEL_STYLE_CITY_TANSHADE",PANEL_STYLE_CITY_TANSHADE)
.value("PANEL_STYLE_CITY_INFO",PANEL_STYLE_CITY_INFO)
.value("PANEL_STYLE_CITY_TANTL",PANEL_STYLE_CITY_TANTL)
.value("PANEL_STYLE_CITY_TANTR",PANEL_STYLE_CITY_TANTR)
.value("PANEL_STYLE_CITY_COLUMNL",PANEL_STYLE_CITY_COLUMNL)
.value("PANEL_STYLE_CITY_COLUMNC",PANEL_STYLE_CITY_COLUMNC)
.value("PANEL_STYLE_CITY_COLUMNR",PANEL_STYLE_CITY_COLUMNR)
.value("PANEL_STYLE_CITY_TITLE",PANEL_STYLE_CITY_TITLE)
.value("PANEL_STYLE_DAWN",PANEL_STYLE_DAWN)
.value("PANEL_STYLE_DAWNTOP",PANEL_STYLE_DAWNTOP)
.value("PANEL_STYLE_DAWNBOTTOM",PANEL_STYLE_DAWNBOTTOM)
.value("PANEL_STYLE_MAIN",PANEL_STYLE_MAIN)
.value("PANEL_STYLE_MAIN_BLACK25",PANEL_STYLE_MAIN_BLACK25)
.value("PANEL_STYLE_MAIN_BLACK50",PANEL_STYLE_MAIN_BLACK50)
.value("PANEL_STYLE_MAIN_WHITE",PANEL_STYLE_MAIN_WHITE)
.value("PANEL_STYLE_MAIN_WHITETAB",PANEL_STYLE_MAIN_WHITETAB)
.value("PANEL_STYLE_MAIN_TAN",PANEL_STYLE_MAIN_TAN)
.value("PANEL_STYLE_MAIN_TAN15",PANEL_STYLE_MAIN_TAN15)
.value("PANEL_STYLE_MAIN_TANL",PANEL_STYLE_MAIN_TANL)
.value("PANEL_STYLE_MAIN_TANR",PANEL_STYLE_MAIN_TANR)
.value("PANEL_STYLE_MAIN_TANT",PANEL_STYLE_MAIN_TANT)
.value("PANEL_STYLE_MAIN_TANB",PANEL_STYLE_MAIN_TANB)
.value("PANEL_STYLE_MAIN_BOTTOMBAR",PANEL_STYLE_MAIN_BOTTOMBAR)
.value("PANEL_STYLE_MAIN_SELECT",PANEL_STYLE_MAIN_SELECT)
;
python::enum_<ButtonStyles>("ButtonStyles")
.value("BUTTON_STYLE_STANDARD", BUTTON_STYLE_STANDARD)
.value("BUTTON_STYLE_ETCHED", BUTTON_STYLE_ETCHED)
.value("BUTTON_STYLE_FLAT", BUTTON_STYLE_FLAT)
.value("BUTTON_STYLE_IMAGE", BUTTON_STYLE_IMAGE)
.value("BUTTON_STYLE_LABEL", BUTTON_STYLE_LABEL)
.value("BUTTON_STYLE_LINK", BUTTON_STYLE_LINK)
.value("BUTTON_STYLE_SQUARE", BUTTON_STYLE_SQUARE)
.value("BUTTON_STYLE_TOOL", BUTTON_STYLE_TOOL)
.value("BUTTON_STYLE_DEFAULT", BUTTON_STYLE_DEFAULT)
.value("BUTTON_STYLE_CIRCLE", BUTTON_STYLE_CIRCLE)
.value("BUTTON_STYLE_CITY_B01", BUTTON_STYLE_CITY_B01)
.value("BUTTON_STYLE_CITY_B02TL", BUTTON_STYLE_CITY_B02TL)
.value("BUTTON_STYLE_CITY_B02TR", BUTTON_STYLE_CITY_B02TR)
.value("BUTTON_STYLE_CITY_B02BL", BUTTON_STYLE_CITY_B02BL)
.value("BUTTON_STYLE_CITY_B02BR", BUTTON_STYLE_CITY_B02BR)
.value("BUTTON_STYLE_CITY_B03TL", BUTTON_STYLE_CITY_B03TL)
.value("BUTTON_STYLE_CITY_B03TC", BUTTON_STYLE_CITY_B03TC)
.value("BUTTON_STYLE_CITY_B03TR", BUTTON_STYLE_CITY_B03TR)
.value("BUTTON_STYLE_CITY_B03BL", BUTTON_STYLE_CITY_B03BL)
.value("BUTTON_STYLE_CITY_B03BC", BUTTON_STYLE_CITY_B03BC)
.value("BUTTON_STYLE_CITY_B03BR", BUTTON_STYLE_CITY_B03BR)
.value("BUTTON_STYLE_CITY_FLAT", BUTTON_STYLE_CITY_FLAT)
.value("BUTTON_STYLE_CITY_PLUS", BUTTON_STYLE_CITY_PLUS)
.value("BUTTON_STYLE_CITY_MINUS", BUTTON_STYLE_CITY_MINUS)
.value("BUTTON_STYLE_ARROW_LEFT", BUTTON_STYLE_ARROW_LEFT)
.value("BUTTON_STYLE_ARROW_RIGHT", BUTTON_STYLE_ARROW_RIGHT)
;
python::enum_<TableStyles>("TableStyles")
.value("TABLE_STYLE_STANDARD", TABLE_STYLE_STANDARD)
.value("TABLE_STYLE_EMPTY", TABLE_STYLE_EMPTY)
.value("TABLE_STYLE_ALTEMPTY", TABLE_STYLE_ALTEMPTY)
.value("TABLE_STYLE_CITY", TABLE_STYLE_CITY)
.value("TABLE_STYLE_EMPTYSELECTINACTIVE", TABLE_STYLE_EMPTYSELECTINACTIVE)
.value("TABLE_STYLE_ALTDEFAULT", TABLE_STYLE_ALTDEFAULT)
.value("TABLE_STYLE_STAGINGROOM", TABLE_STYLE_STAGINGROOM)
;
python::enum_<EventContextTypes>("EventContextTypes")
.value("NO_EVENTCONTEXT", NO_EVENTCONTEXT)
.value("EVENTCONTEXT_SELF", EVENTCONTEXT_SELF)
.value("EVENTCONTEXT_ALL", EVENTCONTEXT_ALL)
;
python::enum_<TabGroupTypes>("TabGroupTypes")
.value("NO_TABGROUP", NO_TABGROUP)
.value("TABGROUP_GAME", TABGROUP_GAME)
.value("TABGROUP_INPUT", TABGROUP_INPUT)
.value("TABGROUP_GRAPHICS", TABGROUP_GRAPHICS)
.value("TABGROUP_AUDIO", TABGROUP_AUDIO)
.value("TABGROUP_CLOCK", TABGROUP_CLOCK)
.value("NUM_TABGROUPS", NUM_TABGROUPS)
;
python::enum_<ReplayMessageTypes>("ReplayMessageTypes")
.value("NO_REPLAY_MESSAGE", NO_REPLAY_MESSAGE)
.value("REPLAY_MESSAGE_MAJOR_EVENT", REPLAY_MESSAGE_MAJOR_EVENT)
.value("REPLAY_MESSAGE_CITY_FOUNDED", REPLAY_MESSAGE_CITY_FOUNDED)
.value("REPLAY_MESSAGE_PLOT_OWNER_CHANGE", REPLAY_MESSAGE_PLOT_OWNER_CHANGE)
.value("REPLAY_MESSAGE_CIV_ASSIGNED", REPLAY_MESSAGE_CIV_ASSIGNED)
.value("NUM_REPLAY_MESSAGE_TYPES", NUM_REPLAY_MESSAGE_TYPES)
;
python::enum_<AudioTag>("AudioTag")
.value("AUDIOTAG_NONE", AUDIOTAG_NONE)
.value("AUDIOTAG_SOUNDID", AUDIOTAG_SOUNDID)
.value("AUDIOTAG_CONTEXTID", AUDIOTAG_CONTEXTID)
.value("AUDIOTAG_SOUNDTYPE", AUDIOTAG_SOUNDTYPE)
.value("AUDIOTAG_2DSCRIPT", AUDIOTAG_2DSCRIPT)
.value("AUDIOTAG_3DSCRIPT", AUDIOTAG_3DSCRIPT)
.value("AUDIOTAG_SOUNDSCAPE", AUDIOTAG_SOUNDSCAPE)
.value("AUDIOTAG_POSITION", AUDIOTAG_POSITION)
.value("AUDIOTAG_SCRIPTTYPE", AUDIOTAG_SCRIPTTYPE)
.value("AUDIOTAG_LOADTYPE", AUDIOTAG_LOADTYPE)
.value("AUDIOTAG_COUNT", AUDIOTAG_COUNT)
;
python::enum_<CivilopediaPageTypes>("CivilopediaPageTypes")
.value("NO_CIVILOPEDIA_PAGE", NO_CIVILOPEDIA_PAGE)
.value("CIVILOPEDIA_PAGE_TECH", CIVILOPEDIA_PAGE_TECH)
.value("CIVILOPEDIA_PAGE_UNIT", CIVILOPEDIA_PAGE_UNIT)
.value("CIVILOPEDIA_PAGE_BUILDING", CIVILOPEDIA_PAGE_BUILDING)
.value("CIVILOPEDIA_PAGE_WONDER", CIVILOPEDIA_PAGE_WONDER)
.value("CIVILOPEDIA_PAGE_BONUS", CIVILOPEDIA_PAGE_BONUS)
.value("CIVILOPEDIA_PAGE_IMPROVEMENT", CIVILOPEDIA_PAGE_IMPROVEMENT)
.value("CIVILOPEDIA_PAGE_PROMOTION", CIVILOPEDIA_PAGE_PROMOTION)
.value("CIVILOPEDIA_PAGE_UNIT_GROUP", CIVILOPEDIA_PAGE_UNIT_GROUP)
.value("CIVILOPEDIA_PAGE_CIV", CIVILOPEDIA_PAGE_CIV)
.value("CIVILOPEDIA_PAGE_LEADER", CIVILOPEDIA_PAGE_LEADER)
.value("CIVILOPEDIA_PAGE_RELIGION", CIVILOPEDIA_PAGE_RELIGION)
.value("CIVILOPEDIA_PAGE_CORPORATION", CIVILOPEDIA_PAGE_CORPORATION)
.value("CIVILOPEDIA_PAGE_CIVIC", CIVILOPEDIA_PAGE_CIVIC)
.value("CIVILOPEDIA_PAGE_PROJECT", CIVILOPEDIA_PAGE_PROJECT)
.value("CIVILOPEDIA_PAGE_CONCEPT", CIVILOPEDIA_PAGE_CONCEPT)
.value("CIVILOPEDIA_PAGE_CONCEPT_NEW", CIVILOPEDIA_PAGE_CONCEPT_NEW)
.value("CIVILOPEDIA_PAGE_SPECIALIST", CIVILOPEDIA_PAGE_SPECIALIST)
.value("CIVILOPEDIA_PAGE_TERRAIN", CIVILOPEDIA_PAGE_TERRAIN)
.value("CIVILOPEDIA_PAGE_FEATURE", CIVILOPEDIA_PAGE_FEATURE)
.value("CIVILOPEDIA_PAGE_HINTS", CIVILOPEDIA_PAGE_HINTS)
.value("NUM_CIVILOPEDIA_PAGE_TYPES", NUM_CIVILOPEDIA_PAGE_TYPES)
;
python::enum_<ActionSubTypes>("ActionSubTypes")
.value("NO_ACTIONSUBTYPE", NO_ACTIONSUBTYPE)
.value("ACTIONSUBTYPE_INTERFACEMODE", ACTIONSUBTYPE_INTERFACEMODE)
.value("ACTIONSUBTYPE_COMMAND", ACTIONSUBTYPE_COMMAND)
.value("ACTIONSUBTYPE_BUILD", ACTIONSUBTYPE_BUILD)
.value("ACTIONSUBTYPE_PROMOTION", ACTIONSUBTYPE_PROMOTION)
.value("ACTIONSUBTYPE_UNIT", ACTIONSUBTYPE_UNIT)
.value("ACTIONSUBTYPE_RELIGION", ACTIONSUBTYPE_RELIGION)
.value("ACTIONSUBTYPE_SPECIALIST", ACTIONSUBTYPE_SPECIALIST)
.value("ACTIONSUBTYPE_BUILDING", ACTIONSUBTYPE_BUILDING)
.value("ACTIONSUBTYPE_CONTROL", ACTIONSUBTYPE_CONTROL)
.value("ACTIONSUBTYPE_AUTOMATE", ACTIONSUBTYPE_AUTOMATE)
.value("ACTIONSUBTYPE_MISSION", ACTIONSUBTYPE_MISSION)
.value("NUM_ACTIONSUBTYPES", NUM_ACTIONSUBTYPES)
;
python::enum_<GameMessageTypes>("GameMessageTypes")
.value("GAMEMESSAGE_NETWORK_READY", GAMEMESSAGE_NETWORK_READY)
.value("GAMEMESSAGE_SAVE_GAME_FLAG", GAMEMESSAGE_SAVE_GAME_FLAG)
.value("GAMEMESSAGE_SAVE_FLAG_ACK", GAMEMESSAGE_SAVE_FLAG_ACK)
.value("GAMEMESSAGE_VERIFY_VERSION", GAMEMESSAGE_VERIFY_VERSION)
.value("GAMEMESSAGE_VERSION_NACK", GAMEMESSAGE_VERSION_NACK)
.value("GAMEMESSAGE_VERSION_WARNING", GAMEMESSAGE_VERSION_WARNING)
.value("GAMEMESSAGE_GAME_TYPE", GAMEMESSAGE_GAME_TYPE)
.value("GAMEMESSAGE_ID_ASSIGNMENT", GAMEMESSAGE_ID_ASSIGNMENT)
.value("GAMEMESSAGE_FILE_INFO", GAMEMESSAGE_FILE_INFO)
.value("GAMEMESSAGE_PICK_YOUR_CIV", GAMEMESSAGE_PICK_YOUR_CIV)
.value("GAMEMESSAGE_CIV_CHOICE", GAMEMESSAGE_CIV_CHOICE)
.value("GAMEMESSAGE_CONFIRM_CIV_CLAIM", GAMEMESSAGE_CONFIRM_CIV_CLAIM)
.value("GAMEMESSAGE_CLAIM_INFO", GAMEMESSAGE_CLAIM_INFO)
.value("GAMEMESSAGE_CIV_CHOICE_ACK", GAMEMESSAGE_CIV_CHOICE_ACK)
.value("GAMEMESSAGE_CIV_CHOICE_NACK", GAMEMESSAGE_CIV_CHOICE_NACK)
.value("GAMEMESSAGE_CIV_CHOSEN", GAMEMESSAGE_CIV_CHOSEN)
.value("GAMEMESSAGE_INTERIM_NOTICE", GAMEMESSAGE_INTERIM_NOTICE)
.value("GAMEMESSAGE_INIT_INFO", GAMEMESSAGE_INIT_INFO)
.value("GAMEMESSAGE_MAPSCRIPT_CHECK", GAMEMESSAGE_MAPSCRIPT_CHECK)
.value("GAMEMESSAGE_MAPSCRIPT_ACK", GAMEMESSAGE_MAPSCRIPT_ACK)
.value("GAMEMESSAGE_LOAD_GAME", GAMEMESSAGE_LOAD_GAME)
.value("GAMEMESSAGE_PLAYER_ID", GAMEMESSAGE_PLAYER_ID)
.value("GAMEMESSAGE_SLOT_REASSIGNMENT", GAMEMESSAGE_SLOT_REASSIGNMENT)
.value("GAMEMESSAGE_PLAYER_INFO", GAMEMESSAGE_PLAYER_INFO)
.value("GAMEMESSAGE_GAME_INFO", GAMEMESSAGE_GAME_INFO)
.value("GAMEMESSAGE_REASSIGN_PLAYER", GAMEMESSAGE_REASSIGN_PLAYER)
.value("GAMEMESSAGE_PITBOSS_INFO", GAMEMESSAGE_PITBOSS_INFO)
.value("GAMEMESSAGE_LAUNCHING_INFO", GAMEMESSAGE_LAUNCHING_INFO)
.value("GAMEMESSAGE_INIT_GAME", GAMEMESSAGE_INIT_GAME)
.value("GAMEMESSAGE_INIT_PLAYERS", GAMEMESSAGE_INIT_PLAYERS)
.value("GAMEMESSAGE_AUTH_REQUEST", GAMEMESSAGE_AUTH_REQUEST)
.value("GAMEMESSAGE_AUTH_RESPONSE", GAMEMESSAGE_AUTH_RESPONSE)
.value("GAMEMESSAGE_SYNCH_START", GAMEMESSAGE_SYNCH_START)
.value("GAMEMESSAGE_PLAYER_OPTION", GAMEMESSAGE_PLAYER_OPTION)
.value("GAMEMESSAGE_EXTENDED_GAME", GAMEMESSAGE_EXTENDED_GAME)
.value("GAMEMESSAGE_AUTO_MOVES", GAMEMESSAGE_AUTO_MOVES)
.value("GAMEMESSAGE_TURN_COMPLETE", GAMEMESSAGE_TURN_COMPLETE)
.value("GAMEMESSAGE_JOIN_GROUP", GAMEMESSAGE_JOIN_GROUP)
.value("GAMEMESSAGE_PUSH_MISSION", GAMEMESSAGE_PUSH_MISSION)
.value("GAMEMESSAGE_AUTO_MISSION", GAMEMESSAGE_AUTO_MISSION)
.value("GAMEMESSAGE_DO_COMMAND", GAMEMESSAGE_DO_COMMAND)
.value("GAMEMESSAGE_PUSH_ORDER", GAMEMESSAGE_PUSH_ORDER)
.value("GAMEMESSAGE_POP_ORDER", GAMEMESSAGE_POP_ORDER)
.value("GAMEMESSAGE_DO_TASK", GAMEMESSAGE_DO_TASK)
.value("GAMEMESSAGE_RESEARCH", GAMEMESSAGE_RESEARCH)
.value("GAMEMESSAGE_PERCENT_CHANGE", GAMEMESSAGE_PERCENT_CHANGE)
.value("GAMEMESSAGE_ESPIONAGE_CHANGE", GAMEMESSAGE_ESPIONAGE_CHANGE)
.value("GAMEMESSAGE_CONVERT", GAMEMESSAGE_CONVERT)
.value("GAMEMESSAGE_CHAT", GAMEMESSAGE_CHAT)
.value("GAMEMESSAGE_PING", GAMEMESSAGE_PING)
.value("GAMEMESSAGE_SIGN", GAMEMESSAGE_SIGN)
.value("GAMEMESSAGE_LINE_ENTITY", GAMEMESSAGE_LINE_ENTITY)
.value("GAMEMESSAGE_SIGN_DELETE", GAMEMESSAGE_SIGN_DELETE)
.value("GAMEMESSAGE_LINE_ENTITY_DELETE", GAMEMESSAGE_LINE_ENTITY_DELETE)
.value("GAMEMESSAGE_LINE_GROUP_DELETE", GAMEMESSAGE_LINE_GROUP_DELETE)
.value("GAMEMESSAGE_PAUSE", GAMEMESSAGE_PAUSE)
.value("GAMEMESSAGE_MP_KICK", GAMEMESSAGE_MP_KICK)
.value("GAMEMESSAGE_MP_RETIRE", GAMEMESSAGE_MP_RETIRE)
.value("GAMEMESSAGE_CLOSE_CONNECTION", GAMEMESSAGE_CLOSE_CONNECTION)
.value("GAMEMESSAGE_NEVER_JOINED", GAMEMESSAGE_NEVER_JOINED)
.value("GAMEMESSAGE_MP_DROP_INIT", GAMEMESSAGE_MP_DROP_INIT)
.value("GAMEMESSAGE_MP_DROP_VOTE", GAMEMESSAGE_MP_DROP_VOTE)
.value("GAMEMESSAGE_MP_DROP_UPDATE", GAMEMESSAGE_MP_DROP_UPDATE)
.value("GAMEMESSAGE_MP_DROP_RESULT", GAMEMESSAGE_MP_DROP_RESULT)
.value("GAMEMESSAGE_MP_DROP_SAVE", GAMEMESSAGE_MP_DROP_SAVE)
.value("GAMEMESSAGE_TOGGLE_TRADE", GAMEMESSAGE_TOGGLE_TRADE)
.value("GAMEMESSAGE_IMPLEMENT_OFFER", GAMEMESSAGE_IMPLEMENT_OFFER)
.value("GAMEMESSAGE_CHANGE_WAR", GAMEMESSAGE_CHANGE_WAR)
.value("GAMEMESSAGE_CHANGE_VASSAL", GAMEMESSAGE_CHANGE_VASSAL)
.value("GAMEMESSAGE_CHOOSE_ELECTION", GAMEMESSAGE_CHOOSE_ELECTION)
.value("GAMEMESSAGE_DIPLO_VOTE", GAMEMESSAGE_DIPLO_VOTE)
.value("GAMEMESSAGE_APPLY_EVENT", GAMEMESSAGE_APPLY_EVENT)
.value("GAMEMESSAGE_CONTACT_CIV", GAMEMESSAGE_CONTACT_CIV)
.value("GAMEMESSAGE_DIPLO_CHAT", GAMEMESSAGE_DIPLO_CHAT)
.value("GAMEMESSAGE_SEND_OFFER", GAMEMESSAGE_SEND_OFFER)
.value("GAMEMESSAGE_DIPLO_EVENT", GAMEMESSAGE_DIPLO_EVENT)
.value("GAMEMESSAGE_RENEGOTIATE", GAMEMESSAGE_RENEGOTIATE)
.value("GAMEMESSAGE_RENEGOTIATE_ITEM", GAMEMESSAGE_RENEGOTIATE_ITEM)
.value("GAMEMESSAGE_EXIT_TRADE", GAMEMESSAGE_EXIT_TRADE)
.value("GAMEMESSAGE_KILL_DEAL", GAMEMESSAGE_KILL_DEAL)
.value("GAMEMESSAGE_SAVE_GAME", GAMEMESSAGE_SAVE_GAME)
.value("GAMEMESSAGE_UPDATE_CIVICS", GAMEMESSAGE_UPDATE_CIVICS)
.value("GAMEMESSAGE_CLEAR_TABLE", GAMEMESSAGE_CLEAR_TABLE)
.value("GAMEMESSAGE_POPUP_PROCESSED", GAMEMESSAGE_POPUP_PROCESSED)
.value("GAMEMESSAGE_DIPLOMACY_PROCESSED", GAMEMESSAGE_DIPLOMACY_PROCESSED)
.value("GAMEMESSAGE_HOT_JOIN_NOTICE", GAMEMESSAGE_HOT_JOIN_NOTICE)
.value("GAMEMESSAGE_HOT_DROP_NOTICE", GAMEMESSAGE_HOT_DROP_NOTICE)
.value("GAMEMESSAGE_DIPLOMACY", GAMEMESSAGE_DIPLOMACY)
.value("GAMEMESSAGE_POPUP", GAMEMESSAGE_POPUP)
.value("GAMEMESSAGE_EVENT_TRIGGERED", GAMEMESSAGE_EVENT_TRIGGERED)
.value("GAMEMESSAGE_EMPIRE_SPLIT", GAMEMESSAGE_EMPIRE_SPLIT)
.value("GAMEMESSAGE_LAUNCH_SPACESHIP", GAMEMESSAGE_LAUNCH_SPACESHIP)
.value("GAMEMESSAGE_ADVANCED_START_ACTION", GAMEMESSAGE_ADVANCED_START_ACTION)
.value("GAMEMESSAGE_FOUND_RELIGION", GAMEMESSAGE_FOUND_RELIGION)
.value("GAMEMESSAGE_MOD_NET_MESSAGE", GAMEMESSAGE_MOD_NET_MESSAGE)
;
python::enum_<PopupControlLayout>("PopupControlLayout")
.value("POPUP_LAYOUT_LEFT", POPUP_LAYOUT_LEFT)
.value("POPUP_LAYOUT_CENTER", POPUP_LAYOUT_CENTER)
.value("POPUP_LAYOUT_RIGHT", POPUP_LAYOUT_RIGHT)
.value("POPUP_LAYOUT_STRETCH", POPUP_LAYOUT_STRETCH)
.value("POPUP_LAYOUT_NUMLAYOUTS", POPUP_LAYOUT_NUMLAYOUTS)
;
python::enum_<JustificationTypes>("JustificationTypes")
.value("DLL_FONT_LEFT_JUSTIFY", DLL_FONT_LEFT_JUSTIFY)
.value("DLL_FONT_RIGHT_JUSTIFY", DLL_FONT_RIGHT_JUSTIFY)
.value("DLL_FONT_CENTER_JUSTIFY", DLL_FONT_CENTER_JUSTIFY)
.value("DLL_FONT_CENTER_VERTICALLY", DLL_FONT_CENTER_VERTICALLY)
.value("DLL_FONT_ADDITIVE", DLL_FONT_ADDITIVE)
;
python::enum_<ToolTipAlignTypes>("ToolTipAlignTypes")
.value("TOOLTIP_TOP_LEFT", TOOLTIP_TOP_LEFT)
.value("TOOLTIP_TOP_INLEFT", TOOLTIP_TOP_INLEFT)
.value("TOOLTIP_TOP_CENTER", TOOLTIP_TOP_CENTER)
.value("TOOLTIP_TOP_INRIGHT", TOOLTIP_TOP_INRIGHT)
.value("TOOLTIP_TOP_RIGHT", TOOLTIP_TOP_RIGHT)
.value("TOOLTIP_INTOP_RIGHT", TOOLTIP_INTOP_RIGHT)
.value("TOOLTIP_CENTER_RIGHT", TOOLTIP_CENTER_RIGHT)
.value("TOOLTIP_INBOTTOM_RIGHT", TOOLTIP_INBOTTOM_RIGHT)
.value("TOOLTIP_BOTTOM_RIGHT", TOOLTIP_BOTTOM_RIGHT)
.value("TOOLTIP_BOTTOM_INRIGHT", TOOLTIP_BOTTOM_INRIGHT)
.value("TOOLTIP_BOTTOM_CENTER", TOOLTIP_BOTTOM_CENTER)
.value("TOOLTIP_BOTTOM_INLEFT", TOOLTIP_BOTTOM_INLEFT)
.value("TOOLTIP_BOTTOM_LEFT", TOOLTIP_BOTTOM_LEFT)
.value("TOOLTIP_INBOTTOM_LEFT", TOOLTIP_INBOTTOM_LEFT)
.value("TOOLTIP_CENTER_LEFT", TOOLTIP_CENTER_LEFT)
.value("TOOLTIP_INTOP_LEFT", TOOLTIP_INTOP_LEFT)
;
python::enum_<ActivationTypes>("ActivationTypes")
.value("ACTIVATE_NORMAL", ACTIVATE_NORMAL)
.value("ACTIVATE_CHILDFOCUS", ACTIVATE_CHILDFOCUS)
.value("ACTIVATE_MIMICPARENT", ACTIVATE_MIMICPARENT)
.value("ACTIVATE_MIMICPARENTFOCUS", ACTIVATE_MIMICPARENTFOCUS)
;
python::enum_<HitTestTypes>("HitTestTypes")
.value("HITTEST_DEFAULT", HITTEST_DEFAULT)
.value("HITTEST_NOHIT", HITTEST_NOHIT)
.value("HITTEST_SOLID", HITTEST_SOLID)
.value("HITTEST_ON", HITTEST_ON)
.value("HITTEST_CHILDREN", HITTEST_CHILDREN)
;
python::enum_<GraphicLevelTypes>("GraphicLevelTypes")
.value("GRAPHICLEVEL_HIGH", GRAPHICLEVEL_HIGH)
.value("GRAPHICLEVEL_MEDIUM", GRAPHICLEVEL_MEDIUM)
.value("GRAPHICLEVEL_LOW", GRAPHICLEVEL_LOW)
.value("GRAPHICLEVEL_CURRENT", GRAPHICLEVEL_CURRENT)
.value("NUM_GRAPHICLEVELS", NUM_GRAPHICLEVELS)
;
python::enum_<EventTypes>("EventTypes")
.value("NO_EVENT", NO_EVENT)
;
python::enum_<EventTriggerTypes>("EventTriggerTypes")
.value("NO_EVENTTRIGGER", NO_EVENTTRIGGER)
;
python::enum_<EspionageMissionTypes>("EspionageMissionTypes")
.value("NO_ESPIONAGEMISSION", NO_ESPIONAGEMISSION)
;
python::enum_<AdvancedStartActionTypes>("AdvancedStartActionTypes")
.value("NO_ADVANCEDSTARTACTION", NO_ADVANCEDSTARTACTION)
.value("ADVANCEDSTARTACTION_EXIT", ADVANCEDSTARTACTION_EXIT)
.value("ADVANCEDSTARTACTION_UNIT", ADVANCEDSTARTACTION_UNIT)
.value("ADVANCEDSTARTACTION_CITY", ADVANCEDSTARTACTION_CITY)
.value("ADVANCEDSTARTACTION_POP", ADVANCEDSTARTACTION_POP)
.value("ADVANCEDSTARTACTION_CULTURE", ADVANCEDSTARTACTION_CULTURE)
.value("ADVANCEDSTARTACTION_BUILDING", ADVANCEDSTARTACTION_BUILDING)
.value("ADVANCEDSTARTACTION_IMPROVEMENT", ADVANCEDSTARTACTION_IMPROVEMENT)
.value("ADVANCEDSTARTACTION_ROUTE", ADVANCEDSTARTACTION_ROUTE)
.value("ADVANCEDSTARTACTION_TECH", ADVANCEDSTARTACTION_TECH)
.value("ADVANCEDSTARTACTION_VISIBILITY", ADVANCEDSTARTACTION_VISIBILITY)
.value("ADVANCEDSTARTACTION_AUTOMATE", ADVANCEDSTARTACTION_AUTOMATE)
;
python::enum_<ReligionSpreadTypes>("ReligionSpreadTypes")
.value("RELIGION_SPREAD_NONE", RELIGION_SPREAD_NONE)
.value("RELIGION_SPREAD_MINORITY", RELIGION_SPREAD_MINORITY)
.value("RELIGION_SPREAD_NORMAL", RELIGION_SPREAD_NORMAL)
.value("RELIGION_SPREAD_FAST", RELIGION_SPREAD_FAST)
;
python::enum_<RegionSpreadTypes>("RegionSpreadTypes")
.value("REGION_SPREAD_NONE", REGION_SPREAD_NONE)
.value("REGION_SPREAD_MINORITY", REGION_SPREAD_MINORITY)
.value("REGION_SPREAD_PERIPHERY", REGION_SPREAD_PERIPHERY)
.value("REGION_SPREAD_HISTORICAL", REGION_SPREAD_HISTORICAL)
.value("REGION_SPREAD_CORE", REGION_SPREAD_CORE)
.value("NUM_REGION_SPREAD_TYPES", NUM_REGION_SPREAD_TYPES)
;
python::enum_<HistoryTypes>("HistoryTypes")
.value("HISTORY_SCORE", HISTORY_SCORE)
.value("HISTORY_ECONOMY", HISTORY_ECONOMY)
.value("HISTORY_INDUSTRY", HISTORY_INDUSTRY)
.value("HISTORY_AGRICULTURE", HISTORY_AGRICULTURE)
.value("HISTORY_POWER", HISTORY_POWER)
.value("HISTORY_CULTURE", HISTORY_CULTURE)
.value("HISTORY_ESPIONAGE", HISTORY_ESPIONAGE)
.value("HISTORY_TECHNOLOGY", HISTORY_TECHNOLOGY)
.value("HISTORY_POPULATION", HISTORY_POPULATION)
.value("HISTORY_LAND", HISTORY_LAND)
.value("NUM_HISTORY_TYPES", NUM_HISTORY_TYPES)
;
}
| 0 | 0.591828 | 1 | 0.591828 | game-dev | MEDIA | 0.684113 | game-dev | 0.782244 | 1 | 0.782244 |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | 8,817 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/bow/NaturesBow.java | package com.shatteredpixel.shatteredpixeldungeon.items.weapon.bow;
import com.shatteredpixel.shatteredpixeldungeon.SPDSettings;
import com.shatteredpixel.shatteredpixeldungeon.ShatteredPixelDungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Roots;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.plants.Blindweed;
import com.shatteredpixel.shatteredpixeldungeon.plants.Firebloom;
import com.shatteredpixel.shatteredpixeldungeon.plants.Icecap;
import com.shatteredpixel.shatteredpixeldungeon.plants.Plant;
import com.shatteredpixel.shatteredpixeldungeon.plants.Sorrowmoss;
import com.shatteredpixel.shatteredpixeldungeon.plants.Stormvine;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.CheckBox;
import com.shatteredpixel.shatteredpixeldungeon.ui.RedButton;
import com.shatteredpixel.shatteredpixeldungeon.ui.RenderedTextBlock;
import com.shatteredpixel.shatteredpixeldungeon.ui.Window;
import com.watabou.utils.Bundle;
import com.watabou.utils.Random;
import java.util.ArrayList;
public class NaturesBow extends SpiritBow {
public static final String AC_CHOOSE = "CHOOSE";
{
image = ItemSpriteSheet.NATURE_BOW;
}
private void activatePlant(Plant plant, Char defender) {
plant.pos = defender.pos;
plant.activate( defender.isAlive() ? defender : null );
}
private boolean blindweedAct = true;
private boolean fireblossomAct = true;
private boolean icecapAct = true;
private boolean sorrowmossAct = true;
private boolean stormvineAct = true;
private static final String BLINDWEED_ACT = "blindweedAct";
private static final String FIREBLOSSOM_ACT = "fireblossomAct";
private static final String ICECAP_ACT = "icecapAct";
private static final String SORROWMOSS_ACT = "sorrowmossAct";
private static final String STORMVINE_ACT = "stormvineAct";
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put(BLINDWEED_ACT, blindweedAct );
bundle.put(FIREBLOSSOM_ACT, fireblossomAct);
bundle.put(ICECAP_ACT, icecapAct );
bundle.put(SORROWMOSS_ACT, sorrowmossAct );
bundle.put(STORMVINE_ACT, stormvineAct );
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
blindweedAct = bundle.getBoolean(BLINDWEED_ACT);
fireblossomAct = bundle.getBoolean(FIREBLOSSOM_ACT);
icecapAct = bundle.getBoolean(ICECAP_ACT);
sorrowmossAct = bundle.getBoolean(SORROWMOSS_ACT);
stormvineAct = bundle.getBoolean(STORMVINE_ACT);
}
@Override
public ArrayList<String> actions(Hero hero) {
ArrayList<String> actions = super.actions(hero);
actions.add(AC_CHOOSE);
return actions;
}
@Override
public void execute(Hero hero, String action) {
super.execute(hero, action);
if (action.equals(AC_CHOOSE)) {
choosePlant();
}
}
@Override
public int proc(Char attacker, Char defender, int damage) {
int dmg = super.proc(attacker, defender, damage);
switch (Random.Int(15)) {
default:
break;
case 0:
Buff.affect(defender, Roots.class, 3f);
if (!blindweedAct) break;
activatePlant(new Blindweed(), defender);
break;
case 1:
Buff.affect(defender, Roots.class, 3f);
if (!fireblossomAct) break;
activatePlant(new Firebloom(), defender);
break;
case 2:
Buff.affect(defender, Roots.class, 3f);
if (!icecapAct) break;
activatePlant(new Icecap(), defender);
break;
case 3:
Buff.affect(defender, Roots.class, 3f);
if (!sorrowmossAct) break;
activatePlant(new Sorrowmoss(), defender);
break;
case 4:
Buff.affect(defender, Roots.class, 3f);
if (!stormvineAct) break;
activatePlant(new Stormvine(), defender);
break;
}
return dmg;
}
@Override
public SpiritArrow knockArrow(){
return new NatureArrow();
}
public class NatureArrow extends SpiritArrow {
{
image = ItemSpriteSheet.ARROW_NATURE;
}
}
public void choosePlant() {
final int WIDTH_P = 150;
final int BTN_HEIGHT = 16;
final float GAP = 1;
ShatteredPixelDungeon.scene().addToFront(new Window(){
RenderedTextBlock title;
RenderedTextBlock uiDesc;
CheckBox bilndweed;
CheckBox fireblossom;
CheckBox icecap;
CheckBox sorrowmoss;
CheckBox stormvine;
{
title = PixelScene.renderTextBlock(Messages.get(NaturesBow.class, "ui_title"), 9);
title.hardlight(TITLE_COLOR);
add(title);
//설명 문구
uiDesc = PixelScene.renderTextBlock(Messages.get(NaturesBow.class, "ui_desc"), 6);
add(uiDesc);
//체크박스 버튼
bilndweed = new CheckBox(Messages.get(Blindweed.class, "name")) {
@Override
protected void onClick() {
checked(switchPlantAct(0));
}
};
bilndweed.checked(blindweedAct);
add(bilndweed);
fireblossom = new CheckBox(Messages.get(Firebloom.class, "name")) {
@Override
protected void onClick() {
checked(switchPlantAct(1));
}
};
fireblossom.checked(fireblossomAct);
add(fireblossom);
icecap = new CheckBox(Messages.get(Icecap.class, "name")) {
@Override
protected void onClick() {
checked(switchPlantAct(2));
}
};
icecap.checked(icecapAct);
add(icecap);
sorrowmoss = new CheckBox(Messages.get(Sorrowmoss.class, "name")) {
@Override
protected void onClick() {
checked(switchPlantAct(3));
}
};
sorrowmoss.checked(sorrowmossAct);
add(sorrowmoss);
stormvine = new CheckBox(Messages.get(Stormvine.class, "name")) {
@Override
protected void onClick() {
checked(switchPlantAct(4));
}
};
stormvine.checked(stormvineAct);
add(stormvine);
//layout
resize(WIDTH_P, 0);
int btnWidth = width;
title.setPos((width - title.width())/2, GAP);
uiDesc.setPos(0, title.bottom()+2*GAP);
uiDesc.maxWidth(btnWidth);
bilndweed.setRect(0, uiDesc.bottom()+2*GAP, btnWidth, BTN_HEIGHT);
fireblossom.setRect(0, bilndweed.bottom()+2*GAP, btnWidth, BTN_HEIGHT);
icecap.setRect(0, fireblossom.bottom()+2*GAP, btnWidth, BTN_HEIGHT);
sorrowmoss.setRect(0, icecap.bottom()+2*GAP, btnWidth, BTN_HEIGHT);
stormvine.setRect(0, sorrowmoss.bottom()+2*GAP, btnWidth, BTN_HEIGHT);
resize(WIDTH_P, (int)stormvine.bottom());
}
});
}
public boolean switchPlantAct(int index) {
switch (index) {
default: case 0:
blindweedAct = !blindweedAct;
return blindweedAct;
case 1:
fireblossomAct = !fireblossomAct;
return fireblossomAct;
case 2:
icecapAct = !icecapAct;
return icecapAct;
case 3:
sorrowmossAct = !sorrowmossAct;
return sorrowmossAct;
case 4:
stormvineAct = !stormvineAct;
return stormvineAct;
}
}
}
| 0 | 0.887049 | 1 | 0.887049 | game-dev | MEDIA | 0.949489 | game-dev | 0.930341 | 1 | 0.930341 |
BigheadSMZ/Zelda-LA-DX-HD-Updated | 1,636 | ladxhd_game_source_code/InGame/GameObjects/Base/Systems/SystemAi.cs | using System;
using System.Collections.Generic;
using ProjectZ.InGame.GameObjects.Base.Components;
using ProjectZ.InGame.GameObjects.Base.Pools;
using ProjectZ.InGame.Map;
namespace ProjectZ.InGame.GameObjects.Base.Systems
{
class SystemAi
{
public ComponentPool Pool;
private readonly List<GameObject> _objectList = new List<GameObject>();
public void Update(Type[] objectTypes = null)
{
_objectList.Clear();
Pool.GetComponentList(_objectList,
(int)((MapManager.Camera.X - Game1.RenderWidth / 2) / MapManager.Camera.Scale),
(int)((MapManager.Camera.Y - Game1.RenderHeight / 2) / MapManager.Camera.Scale),
(int)(Game1.RenderWidth / MapManager.Camera.Scale),
(int)(Game1.RenderHeight / MapManager.Camera.Scale), AiComponent.Mask);
foreach (var gameObject in _objectList)
{
bool skipObject = (objectTypes == null) switch
{
true => (!gameObject.IsActive),
false => (!gameObject.IsActive || !ObjectManager.IsGameObjectType(gameObject, objectTypes))
};
if (skipObject) continue;
var aiComponent = (gameObject.Components[AiComponent.Index]) as AiComponent;
aiComponent?.CurrentState.Update?.Invoke();
foreach (var trigger in aiComponent.CurrentState.Trigger)
trigger.Update();
foreach (var trigger in aiComponent.Trigger)
trigger.Update();
}
}
}
}
| 0 | 0.894725 | 1 | 0.894725 | game-dev | MEDIA | 0.968703 | game-dev | 0.965712 | 1 | 0.965712 |
PotRooms/AzurPromiliaData | 5,124 | Lua/src/ui/manager/interactive/interactiveManager.lua | local this = class("interactiveManager", G_EventManagerBase)
this:importPartialClass(require("ui.manager.interactive.interactiveManagerHandles"))
this.event = {
onButtonDataChange = "onButtonDataChange",
onBuildButtonChange = "onBuildButtonChange"
}
local CONFIG_PAGE = require("ui.config").pages
local _wroldCityTpl = L_GameTpl:getWorldCityTpl()
local _interactiveTpl = L_GameTpl:getWorldInteractivetypeTpl()
local _battleTpl = L_GameTpl:getBattleTpl()
local _transferTpl = L_GameTpl:getWorldBorthposTpl()
local pageNoButton = {
pageFaceIn = true,
pageHomePlayerEdit = true,
pageHomePlayerEditCS = true,
pageWorldBattle = true,
dialogWindow = true,
pageShop = true,
pageBattlePetCatch = true
}
function this:ctor()
self.super.ctor(self)
self._entity2ButtonDatas = {}
self._triggerBuildGuids = {}
self._newEntity2BtnDatas = {}
self._pageLock = {}
self._moduleLock = {}
self._entityInteractOptions = {}
end
function this:setInteract(L_interData)
if L_interData.entity == nil then
return
end
self._newEntity2BtnDatas[L_interData.entity] = self._newEntity2BtnDatas[L_interData.entity] or {}
if L_interData.isIn then
self._newEntity2BtnDatas[L_interData.entity][L_interData.sId] = L_interData
else
self._newEntity2BtnDatas[L_interData.entity][L_interData.sId] = nil
end
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
function this:findInteractData(cData)
if cData.entity == nil then
return
end
if self._newEntity2BtnDatas[cData.entity] == nil then
return
end
return self._newEntity2BtnDatas[cData.entity][cData.sId]
end
function this:changeInteractState(cData)
local interData = self:findInteractData(cData)
if interData == nil then
return
end
interData.hide = cData.hide
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
function this:getIsLock()
local result = next(self._pageLock) or next(self._moduleLock)
if result then
end
return result
end
function this:getButtonIsShow()
return not self:getIsLock()
end
function this:getNewInteractDatas()
return self._newEntity2BtnDatas
end
function this:getButtonDatas()
return self._entity2ButtonDatas
end
function this:getInteractOptions()
return self._entityInteractOptions
end
function this:initialize()
L_UI:open("interactive")
L_UI:addListener(L_UI.pageEvent.preOpen, self._onShowPage, self)
L_UI:addListener(L_UI.pageEvent.closed, self._onHidePage, self)
L_SceneManager:addListener(L_SceneManager.event.suspendCurScene, function()
self:_setModuleLock(L_Const.moduleControl.world, true)
end)
L_SceneManager:addListener(L_SceneManager.event.resumeCurSceneEnd, function()
self:_setModuleLock(L_Const.moduleControl.world, false)
end)
L_PlayerStore:listenCallFunc(L_PlayerStore.event.refreshMountStatus, function()
self:_setModuleLock(L_Const.moduleControl.fly, L_PlayerManager:inMountFly())
end)
L_PlayerStore:listenCallFunc(L_PlayerStore.event.refreshPlayerStatus, function()
self:_setModuleLock(L_Const.moduleControl.fly, L_PlayerManager:inMountFly())
end)
L_SceneManager:addListener(L_SceneManager.event.switchSceneEnd, function()
self:_setModuleLock(L_Const.moduleControl.fly, L_PlayerManager:inMountFly())
end)
L_BattleManager:addListener(L_BattleManager.event.tmpPauseInput, function(pause)
self:_setModuleLock(L_Const.moduleControl.heroUltimateSkill, pause)
end)
self:addModulesListener()
end
function this:resetLock()
self._pageLock = {}
self._moduleLock = {}
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
function this:_onShowPage(pageName)
local cfg = CONFIG_PAGE[pageName]
if not (cfg.uiType == "freedom" or cfg.controlMove) or pageNoButton[pageName] then
self._pageLock[pageName] = true
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
end
function this:_onHidePage(pageName)
self._pageLock[pageName] = nil
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
function this:_setModuleLock(key, state)
self._moduleLock[key] = state == true or nil
self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end
function this:getInterNameByBevNode(interData, bevNode)
local entity = interData.entity
local interType = interData.interType
local tpl = _interactiveTpl:getTplById(interType)
local type = _interactiveTpl:getType(tpl)
if type == L_Const.interactiveType.battle then
local tpl = _battleTpl:getTplById(bevNode.battleId)
return _battleTpl:getName(tpl)
elseif type == L_Const.interactiveType.tranferPoint then
local tpl = _transferTpl:getTplById(bevNode.pointId)
return L_WordsTpl:getValue("ui_interactiveManager_07", {
[0] = _transferTpl:getName(tpl)
})
elseif type == L_Const.interactiveType.transferScene then
local tpl = _transferTpl:getTplById(bevNode.pointId)
local sceneId = _transferTpl:getCityId(tpl)
tpl = _wroldCityTpl:getTplById(sceneId)
return L_WordsTpl:getValue("ui_interactiveManager_07", {
[0] = _wroldCityTpl:getCity(tpl)
})
else
return entity:getEntityName()
end
end
return this
| 0 | 0.887136 | 1 | 0.887136 | game-dev | MEDIA | 0.807775 | game-dev,desktop-app | 0.957709 | 1 | 0.957709 |
adospace/reactorui-xamarin | 11,780 | src/XamarinReactorUI/RxShell.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Xamarin.Forms;
namespace XamarinReactorUI
{
public interface IRxShell : IRxPage
{
FlyoutBehavior FlyoutBehavior { get; set; }
//DataTemplate MenuItemTemplate { get; set; }
//DataTemplate ItemTemplate { get; set; }
//Color BackgroundColor { get; set; }
//ShellItem CurrentItem { get; set; }
ImageSource FlyoutBackgroundImage { get; set; }
Aspect FlyoutBackgroundImageAspect { get; set; }
Color FlyoutBackgroundColor { get; set; }
FlyoutHeaderBehavior FlyoutHeaderBehavior { get; set; }
object FlyoutHeader { get; set; }
//DataTemplate FlyoutHeaderTemplate { get; set; }
bool FlyoutIsPresented { get; set; }
ImageSource FlyoutIcon { get; set; }
ScrollMode FlyoutVerticalScrollMode { get; set; }
}
public class RxShell<T> : RxPage<T>, IRxShell, IEnumerable<VisualNode> where T : Shell, new()
{
private readonly List<VisualNode> _contents = new List<VisualNode>();
private readonly Dictionary<Page, ShellItem> _elementItemMap = new Dictionary<Page, ShellItem>();
public RxShell()
{
}
public RxShell(Action<T> componentRefAction)
: base(componentRefAction)
{
}
public void Add(VisualNode child)
{
_contents.Add(child);
}
public IEnumerator<VisualNode> GetEnumerator()
{
return _contents.GetEnumerator();
}
protected override void OnAddChild(VisualNode widget, BindableObject childControl)
{
if (childControl is ShellItem shellItem)
{
NativeControl.Items.Insert(widget.ChildIndex, shellItem);
}
else if (childControl is Page page)
{
NativeControl.Items.Insert(widget.ChildIndex, _elementItemMap[page] = new ShellContent() { Content = page });
}
else if (childControl is ToolbarItem toolbarItem)
{
NativeControl.ToolbarItems.Add(toolbarItem);
}
//else if (childControl is SearchHandler handler)
//{
// Shell.SetSearchHandler(NativeControl, handler);
//}
//else
//{
// throw new InvalidOperationException($"Type '{childControl.GetType()}' not supported under '{GetType()}'");
//}
base.OnAddChild(widget, childControl);
}
protected override void OnRemoveChild(VisualNode widget, BindableObject childControl)
{
if (childControl is ShellItem shellItem)
{
NativeControl.Items.Remove(shellItem);
}
else if (childControl is Page page)
{
NativeControl.Items.Remove(_elementItemMap[page]);
}
else if (childControl is ToolbarItem toolbarItem)
{
NativeControl.ToolbarItems.Remove(toolbarItem);
}
//else if (childControl is SearchHandler _)
//{
// Shell.SetSearchHandler(NativeControl, null);
//}
base.OnRemoveChild(widget, childControl);
}
protected override IEnumerable<VisualNode> RenderChildren()
{
return _contents;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public FlyoutBehavior FlyoutBehavior { get; set; } = (FlyoutBehavior)Shell.FlyoutBehaviorProperty.DefaultValue;
//public DataTemplate MenuItemTemplate { get; set; } = (DataTemplate)Shell.MenuItemTemplateProperty.DefaultValue;
//public DataTemplate ItemTemplate { get; set; } = (DataTemplate)Shell.ItemTemplateProperty.DefaultValue;
//public Color BackgroundColor { get; set; } = (Color)Shell.BackgroundColorProperty.DefaultValue;
//public ShellItem CurrentItem { get; set; } = (ShellItem)Shell.CurrentItemProperty.DefaultValue;
public ImageSource FlyoutBackgroundImage { get; set; } = (ImageSource)Shell.FlyoutBackgroundImageProperty.DefaultValue;
public Aspect FlyoutBackgroundImageAspect { get; set; } = (Aspect)Shell.FlyoutBackgroundImageAspectProperty.DefaultValue;
public Color FlyoutBackgroundColor { get; set; } = (Color)Shell.FlyoutBackgroundColorProperty.DefaultValue;
public FlyoutHeaderBehavior FlyoutHeaderBehavior { get; set; } = (FlyoutHeaderBehavior)Shell.FlyoutHeaderBehaviorProperty.DefaultValue;
public object FlyoutHeader { get; set; } = (object)Shell.FlyoutHeaderProperty.DefaultValue;
public DataTemplate FlyoutHeaderTemplate { get; set; } = (DataTemplate)Shell.FlyoutHeaderTemplateProperty.DefaultValue;
public bool FlyoutIsPresented { get; set; } = (bool)Shell.FlyoutIsPresentedProperty.DefaultValue;
public ImageSource FlyoutIcon { get; set; } = (ImageSource)Shell.FlyoutIconProperty.DefaultValue;
public ScrollMode FlyoutVerticalScrollMode { get; set; } = (ScrollMode)Shell.FlyoutVerticalScrollModeProperty.DefaultValue;
protected override void OnUpdate()
{
NativeControl.FlyoutBehavior = FlyoutBehavior;
//NativeControl.MenuItemTemplate = MenuItemTemplate;
//NativeControl.ItemTemplate = ItemTemplate;
NativeControl.FlyoutBackgroundImage = FlyoutBackgroundImage;
NativeControl.FlyoutBackgroundImageAspect = FlyoutBackgroundImageAspect;
NativeControl.FlyoutBackgroundColor = FlyoutBackgroundColor;
NativeControl.FlyoutHeaderBehavior = FlyoutHeaderBehavior;
NativeControl.FlyoutHeader = FlyoutHeader;
NativeControl.FlyoutHeaderTemplate = FlyoutHeaderTemplate;
NativeControl.FlyoutIsPresented = FlyoutIsPresented;
NativeControl.FlyoutIcon = FlyoutIcon;
NativeControl.FlyoutVerticalScrollMode = FlyoutVerticalScrollMode;
base.OnUpdate();
}
}
public class RxShell : RxShell<Shell>
{
public RxShell()
{
}
public RxShell(Action<Shell> componentRefAction)
: base(componentRefAction)
{
}
}
public static class RxShellExtensions
{
public static T FlyoutBehavior<T>(this T shell, FlyoutBehavior flyoutBehavior) where T : IRxShell
{
shell.FlyoutBehavior = flyoutBehavior;
return shell;
}
public static T FlyoutBackgroundImage<T>(this T shell, ImageSource flyoutBackgroundImage) where T : IRxShell
{
shell.FlyoutBackgroundImage = flyoutBackgroundImage;
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, string file) where T : IRxShell
{
shell.FlyoutBackgroundImage = ImageSource.FromFile(file);
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, string fileAndroid, string fileiOS) where T : IRxShell
{
shell.FlyoutBackgroundImage = Device.RuntimePlatform == Device.Android ? ImageSource.FromFile(fileAndroid) : ImageSource.FromFile(fileiOS);
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, string resourceName, Assembly sourceAssembly) where T : IRxShell
{
shell.FlyoutBackgroundImage = ImageSource.FromResource(resourceName, sourceAssembly);
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, Uri imageUri) where T : IRxShell
{
shell.FlyoutBackgroundImage = ImageSource.FromUri(imageUri);
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, Uri imageUri, bool cachingEnabled, TimeSpan cacheValidity) where T : IRxShell
{
shell.FlyoutBackgroundImage = new UriImageSource
{
Uri = imageUri,
CachingEnabled = cachingEnabled,
CacheValidity = cacheValidity
};
return shell;
}
public static T FlyoutBackgroun<T>(this T shell, Func<Stream> imageStream) where T : IRxShell
{
shell.FlyoutBackgroundImage = ImageSource.FromStream(imageStream);
return shell;
}
public static T FlyoutBackgroundImageAspect<T>(this T shell, Aspect flyoutBackgroundImageAspect) where T : IRxShell
{
shell.FlyoutBackgroundImageAspect = flyoutBackgroundImageAspect;
return shell;
}
public static T FlyoutBackgroundColor<T>(this T shell, Color flyoutBackgroundColor) where T : IRxShell
{
shell.FlyoutBackgroundColor = flyoutBackgroundColor;
return shell;
}
public static T FlyoutHeaderBehavior<T>(this T shell, FlyoutHeaderBehavior flyoutHeaderBehavior) where T : IRxShell
{
shell.FlyoutHeaderBehavior = flyoutHeaderBehavior;
return shell;
}
public static T FlyoutHeader<T>(this T shell, object flyoutHeader) where T : IRxShell
{
shell.FlyoutHeader = flyoutHeader;
return shell;
}
//public static T FlyoutHeaderTemplate<T>(this T shell, DataTemplate flyoutHeaderTemplate) where T : IRxShell
//{
// shell.FlyoutHeaderTemplate = flyoutHeaderTemplate;
// return shell;
//}
public static T FlyoutIsPresented<T>(this T shell, bool flyoutIsPresented) where T : IRxShell
{
shell.FlyoutIsPresented = flyoutIsPresented;
return shell;
}
public static T FlyoutIcon<T>(this T shell, ImageSource flyoutIcon) where T : IRxShell
{
shell.FlyoutIcon = flyoutIcon;
return shell;
}
public static T FlyoutIcon<T>(this T shell, string file) where T : IRxShell
{
shell.FlyoutIcon = ImageSource.FromFile(file);
return shell;
}
public static T FlyoutIcon<T>(this T shell, string fileAndroid, string fileiOS) where T : IRxShell
{
shell.FlyoutIcon = Device.RuntimePlatform == Device.Android ? ImageSource.FromFile(fileAndroid) : ImageSource.FromFile(fileiOS);
return shell;
}
public static T FlyoutIcon<T>(this T shell, string resourceName, Assembly sourceAssembly) where T : IRxShell
{
shell.FlyoutIcon = ImageSource.FromResource(resourceName, sourceAssembly);
return shell;
}
public static T FlyoutIcon<T>(this T shell, Uri imageUri) where T : IRxShell
{
shell.FlyoutIcon = ImageSource.FromUri(imageUri);
return shell;
}
public static T FlyoutIcon<T>(this T shell, Uri imageUri, bool cachingEnabled, TimeSpan cacheValidity) where T : IRxShell
{
shell.FlyoutIcon = new UriImageSource
{
Uri = imageUri,
CachingEnabled = cachingEnabled,
CacheValidity = cacheValidity
};
return shell;
}
public static T FlyoutIcon<T>(this T shell, Func<Stream> imageStream) where T : IRxShell
{
shell.FlyoutIcon = ImageSource.FromStream(imageStream);
return shell;
}
public static T FlyoutVerticalScrollMode<T>(this T shell, ScrollMode flyoutVerticalScrollMode) where T : IRxShell
{
shell.FlyoutVerticalScrollMode = flyoutVerticalScrollMode;
return shell;
}
}
} | 0 | 0.810394 | 1 | 0.810394 | game-dev | MEDIA | 0.452296 | game-dev | 0.842224 | 1 | 0.842224 |
Catacomb-Snatch/Catacomb-Snatch | 7,098 | Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/UnsafeList.tt | <#/*THIS IS A T4 FILE - see t4_text_templating.md for what it is and how to run codegen*/#>
<#@ output extension=".gen.cs" #>
<#@ assembly name="System.Collections" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Collections.Generic" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// TextTransform Samples/Packages/com.unity.entities/Unity.Entities/UnsafeList.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Diagnostics;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
namespace Unity.Entities
{
<#
{
foreach (var (type, typeName) in new[] {
( "int", "Int" ),
( "uint", "Uint" ),
}) {
#>
[DebuggerTypeProxy(typeof(Unsafe<#=typeName#>ListDebugView))]
internal unsafe struct Unsafe<#=typeName#>List
{
[NativeDisableUnsafePtrRestriction]
public readonly <#=type#>* Ptr;
public readonly int Length;
public readonly int Capacity;
public readonly Allocator Allocator;
private ref UnsafeList ListData { get { return ref *(UnsafeList*)UnsafeUtility.AddressOf(ref this); } }
public unsafe Unsafe<#=typeName#>List(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { Ptr = null; Length = 0; Capacity = 0; Allocator = Allocator.Invalid; ListData = new UnsafeList(UnsafeUtility.SizeOf<<#=type#>>(), UnsafeUtility.AlignOf<<#=type#>>(), initialCapacity, allocator, options); }
public void Dispose() { ListData.Dispose(); }
public JobHandle Dispose(JobHandle inputDeps) { return ListData.Dispose(inputDeps); }
public void Clear() { ListData.Clear(); }
public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { ListData.Resize<<#=type#>>(length, options); }
public void SetCapacity(int capacity) { ListData.SetCapacity<<#=type#>>(capacity); }
public int IndexOf(<#=type#> value) { return ListData.IndexOf(value); }
public bool Contains(<#=type#> value) { return ListData.Contains(value); }
public void Add(<#=type#> value) { ListData.Add(value); }
public void AddRange(Unsafe<#=typeName#>List src) { ListData.AddRange<<#=type#>>(src.ListData); }
public void RemoveAtSwapBack(int index) { ListData.RemoveAtSwapBack<<#=type#>>(index); }
public ParallelReader AsParallelReader() { return new ParallelReader(Ptr, Length); }
public unsafe struct ParallelReader
{
public readonly <#=type#>* Ptr;
public readonly int Length;
public ParallelReader(<#=type#>* ptr, int length) { Ptr = ptr; Length = length; }
public int IndexOf(<#=type#> value) { for (int i = Length - 1; i >= 0; --i) { if (Ptr[i] == value) { return i; } } return -1; }
public bool Contains(<#=type#> value) { return IndexOf(value) != -1; }
}
}
sealed class Unsafe<#=typeName#>ListDebugView
{
private Unsafe<#=typeName#>List m_ListData;
public Unsafe<#=typeName#>ListDebugView(Unsafe<#=typeName#>List listData)
{
m_ListData = listData;
}
public unsafe <#=type#>[] Items
{
get
{
var result = new <#=type#>[m_ListData.Length];
var ptr = m_ListData.Ptr;
for (int i = 0, num = result.Length; i < num; ++i)
{
result[i] = ptr[i];
}
return result;
}
}
}
<#}}#>
<#
{
foreach (var (type, typeName, typeDebugView) in new[] {
( "Chunk", "Chunk", "ArchetypeChunk" ),
( "Archetype", "Archetype", "EntityArchetype" ),
( "EntityQueryData", "EntityQueryData", "EntityQueryData*" ),
}) {
#>
[DebuggerTypeProxy(typeof(Unsafe<#=typeName#>PtrListDebugView))]
internal unsafe struct Unsafe<#=typeName#>PtrList
{
[NativeDisableUnsafePtrRestriction]
public readonly <#=type#>** Ptr;
public readonly int Length;
public readonly int Capacity;
public readonly Allocator Allocator;
private ref UnsafePtrList ListData { get { return ref *(UnsafePtrList*)UnsafeUtility.AddressOf(ref this); } }
public unsafe Unsafe<#=typeName#>PtrList(<#=type#>** ptr, int length) { Ptr = null; Length = 0; Capacity = 0; Allocator = Allocator.Invalid; ListData = new UnsafePtrList((void**)ptr, length); }
public unsafe Unsafe<#=typeName#>PtrList(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { Ptr = null; Length = 0; Capacity = 0; Allocator = Allocator.Invalid; ListData = new UnsafePtrList(initialCapacity, allocator, options); }
public void Dispose() { ListData.Dispose(); }
public JobHandle Dispose(JobHandle inputDeps) { return ListData.Dispose(inputDeps); }
public void Clear() { ListData.Clear(); }
public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { ListData.Resize(length, options); }
public void SetCapacity(int capacity) { ListData.SetCapacity(capacity); }
public int IndexOf(<#=type#>* value) { return ListData.IndexOf(value); }
public bool Contains(<#=type#>* value) { return ListData.Contains(value); }
public void Add(<#=type#>* value) { ListData.Add(value); }
public void AddRange(Unsafe<#=typeName#>PtrList src) { ListData.AddRange(src.ListData); }
public void RemoveAtSwapBack(int index) { ListData.RemoveAtSwapBack(index); }
public unsafe struct ParallelReader
{
public readonly <#=type#>** Ptr;
public readonly int Length;
public ParallelReader(<#=type#>** ptr, int length) { Ptr = ptr; Length = length; }
public int IndexOf(<#=type#>* value) { for (int i = Length - 1; i >= 0; --i) { if (Ptr[i] == value) { return i; } } return -1; }
public bool Contains(<#=type#>* value) { return IndexOf(value) != -1; }
}
}
sealed class Unsafe<#=typeName#>PtrListDebugView
{
private Unsafe<#=typeName#>PtrList m_ListData;
public Unsafe<#=typeName#>PtrListDebugView(Unsafe<#=typeName#>PtrList listData)
{
m_ListData = listData;
}
public unsafe <#=typeDebugView#>[] Items
{
get
{
var result = new <#=typeDebugView#>[m_ListData.Length];
var ptr = m_ListData.Ptr;
for (int i = 0, num = result.Length; i < num; ++i)
{
result[i] = *(<#=typeDebugView#>*)ptr[i];
}
return result;
}
}
}
<#}}#>
}
| 0 | 0.907302 | 1 | 0.907302 | game-dev | MEDIA | 0.141154 | game-dev | 0.855141 | 1 | 0.855141 |
MenoData/Time4J | 3,875 | base/src/main/java/net/time4j/AbstractTimeElement.java | /*
* -----------------------------------------------------------------------
* Copyright © 2013-2016 Meno Hochschild, <http://www.menodata.de/>
* -----------------------------------------------------------------------
* This file (AbstractTimeElement.java) is part of project Time4J.
*
* Time4J is free software: You can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* Time4J is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Time4J. If not, see <http://www.gnu.org/licenses/>.
* -----------------------------------------------------------------------
*/
package net.time4j;
import net.time4j.engine.ChronoFunction;
import net.time4j.format.DisplayElement;
import net.time4j.tz.TZID;
import net.time4j.tz.Timezone;
import net.time4j.tz.ZonalOffset;
/**
* <p>Abstrakte Basisklasse für Uhrzeit-Elemente, die bereits alle
* Methoden des Interface {@code AdjustableElement} vordefiniert. </p>
*
* @param <V> generic type of element values
* @author Meno Hochschild
*/
abstract class AbstractTimeElement<V extends Comparable<V>>
extends DisplayElement<V>
implements AdjustableElement<V, PlainTime> {
//~ Instanzvariablen --------------------------------------------------
private transient final ElementOperator<PlainTime> minimizer;
private transient final ElementOperator<PlainTime> maximizer;
//~ Konstruktoren -----------------------------------------------------
AbstractTimeElement(String name) {
super(name);
this.minimizer = new TimeOperator(this, ElementOperator.OP_MINIMIZE);
this.maximizer = new TimeOperator(this, ElementOperator.OP_MAXIMIZE);
}
//~ Methoden ----------------------------------------------------------
@Override
public ElementOperator<PlainTime> newValue(V value) {
return new TimeOperator(this, ElementOperator.OP_NEW_VALUE, value);
}
@Override
public ElementOperator<PlainTime> minimized() {
return this.minimizer;
}
@Override
public ElementOperator<PlainTime> maximized() {
return this.maximizer;
}
@Override
public ElementOperator<PlainTime> decremented() {
return new TimeOperator(this, ElementOperator.OP_DECREMENT);
}
@Override
public ElementOperator<PlainTime> incremented() {
return new TimeOperator(this, ElementOperator.OP_INCREMENT);
}
@Override
public ElementOperator<PlainTime> atFloor() {
return new TimeOperator(this, ElementOperator.OP_FLOOR);
}
@Override
public ElementOperator<PlainTime> atCeiling() {
return new TimeOperator(this, ElementOperator.OP_CEILING);
}
public ElementOperator<PlainTime> setLenient(V value) {
return new TimeOperator(this, ElementOperator.OP_LENIENT, value);
}
@Override
public ChronoFunction<Moment, V> inStdTimezone() {
return this.in(Timezone.ofSystem());
}
@Override
public ChronoFunction<Moment, V> inTimezone(TZID tzid) {
return this.in(Timezone.of(tzid));
}
@Override
public ChronoFunction<Moment, V> in(Timezone tz) {
return new ZonalQuery<>(this, tz);
}
@Override
public ChronoFunction<Moment, V> atUTC() {
return this.at(ZonalOffset.UTC);
}
@Override
public ChronoFunction<Moment, V> at(ZonalOffset offset) {
return new ZonalQuery<>(this, offset);
}
}
| 0 | 0.868496 | 1 | 0.868496 | game-dev | MEDIA | 0.261991 | game-dev | 0.880221 | 1 | 0.880221 |
online-go/online-go.com | 10,082 | src/views/LearningHub/Sections/BeginnerLevel2/Defense3.tsx | /*
* Copyright (C) Online-Go.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* cSpell:disable */
import { GobanConfig } from "goban";
import { LearningPage, LearningPageProperties } from "../../LearningPage";
import { _, pgettext } from "@/lib/translate";
import { LearningHubSection } from "../../LearningHubSection";
export class BL2Defense3 extends LearningHubSection {
static pages(): Array<typeof LearningPage> {
return [
Page01,
Page02,
Page03,
Page04,
Page05,
Page06,
Page07,
Page08,
Page09,
Page10,
Page11,
Page12,
];
}
static section(): string {
return "bl2-defense-3";
}
static title(): string {
return pgettext("Tutorial section name on learning defense 3", "Defense 3");
}
static subtext(): string {
return "";
}
}
class Page01 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dofq",
white: "cndp",
},
marks: { A: "co", B: "eo", C: "cp", 1: "do" },
move_tree: this.makePuzzleMoveTree(["co"], [], 19, 19),
};
}
}
class Page02 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "doepdqfq",
white: "cncodpcq",
},
marks: { A: "dn", B: "cp", C: "dr", 1: "ep" },
move_tree: this.makePuzzleMoveTree(["cp"], [], 19, 19),
};
}
}
class Page03 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dpepfpfqhq",
white: "clcncodqeq",
},
marks: { A: "cp", B: "bq", C: "cq", 1: "dp" },
move_tree: this.makePuzzleMoveTree(["cp"], [], 19, 19),
};
}
}
class Page04 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dodqfq",
white: "cncodp",
},
marks: { A: "cp", B: "cq", C: "eq", 1: "dq" },
move_tree: this.makePuzzleMoveTree(["cq"], [], 19, 19),
};
}
}
class Page05 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dlbmcnbo",
white: "cpdpfq",
},
marks: { A: "co", B: "bp", C: "bq", 1: "bo" },
move_tree: this.makePuzzleMoveTree(["bp"], [], 19, 19),
};
}
}
class Page06 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "fodpepbqcqfqgq",
white: "clcncocpdqeqcr",
},
marks: { A: "bp", B: "aq", C: "br", 1: "bq" },
move_tree: this.makePuzzleMoveTree(["br"], [], 19, 19),
};
}
}
class Page07 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "cofq",
white: "dndp",
},
marks: { A: "dl", B: "do", C: "cp", 1: "co" },
move_tree: this.makePuzzleMoveTree(["do"], [], 19, 19),
};
}
}
class Page08 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dpepeqhqer",
white: "cldncodqdr",
},
marks: { A: "cp", B: "bq", C: "cq", 1: "dp" },
move_tree: this.makePuzzleMoveTree(["cp"], [], 19, 19),
};
}
}
class Page09 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dlcndocp",
white: "epdqhq",
},
marks: { A: "bq", B: "cq", C: "cr", 1: "cp" },
move_tree: this.makePuzzleMoveTree(["cq"], [], 19, 19),
};
}
}
class Page10 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "cofq",
white: "cndp",
},
marks: { A: "cm", B: "do", C: "cp", 1: "co" },
move_tree: this.makePuzzleMoveTree(["do"], [], 19, 19),
};
}
}
class Page11 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dlcndnbo",
white: "codpfqhq",
},
marks: { A: "bn", B: "bp", C: "cp", 1: "bo" },
move_tree: this.makePuzzleMoveTree(["bp"], [], 19, 19),
};
}
}
class Page12 extends LearningPage {
constructor(props: LearningPageProperties) {
super(props);
}
text() {
return _("White to play. Choose the best defense in reply of Black's 1, A, B or C.");
}
config(): GobanConfig {
return {
width: 19,
height: 19,
mode: "puzzle",
initial_player: "white",
bounds: { top: 10, left: 0, bottom: 18, right: 8 },
initial_state: {
black: "dpfpcqeqhqer",
white: "cldncocpdqdr",
},
marks: { A: "bq", B: "br", C: "cr", 1: "cq" },
move_tree: this.makePuzzleMoveTree(["cr"], [], 19, 19),
};
}
}
| 0 | 0.796322 | 1 | 0.796322 | game-dev | MEDIA | 0.813957 | game-dev | 0.822241 | 1 | 0.822241 |
daydayasobi/TowerDefense-TEngine-Demo | 2,075 | Packages/YooAsset/Mini Game/Runtime/TaptapFileSystem/Operation/TPFSRequestPackageVersionOperation.cs | #if UNITY_WEBGL && TAPMINIGAME
using YooAsset;
internal class TPFSRequestPackageVersionOperation : FSRequestPackageVersionOperation
{
private enum ESteps
{
None,
RequestPackageVersion,
Done,
}
private readonly TaptapFileSystem _fileSystem;
private readonly bool _appendTimeTicks;
private readonly int _timeout;
private RequestWebPackageVersionOperation _requestWebPackageVersionOp;
private ESteps _steps = ESteps.None;
internal TPFSRequestPackageVersionOperation(TaptapFileSystem fileSystem, bool appendTimeTicks, int timeout)
{
_fileSystem = fileSystem;
_appendTimeTicks = appendTimeTicks;
_timeout = timeout;
}
internal override void InternalStart()
{
_steps = ESteps.RequestPackageVersion;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.RequestPackageVersion)
{
if (_requestWebPackageVersionOp == null)
{
_requestWebPackageVersionOp = new RequestWebPackageVersionOperation(_fileSystem.RemoteServices, _fileSystem.PackageName, _appendTimeTicks, _timeout);
_requestWebPackageVersionOp.StartOperation();
AddChildOperation(_requestWebPackageVersionOp);
}
_requestWebPackageVersionOp.UpdateOperation();
Progress = _requestWebPackageVersionOp.Progress;
if (_requestWebPackageVersionOp.IsDone == false)
return;
if (_requestWebPackageVersionOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.Done;
PackageVersion = _requestWebPackageVersionOp.PackageVersion;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _requestWebPackageVersionOp.Error;
}
}
}
}
#endif | 0 | 0.804322 | 1 | 0.804322 | game-dev | MEDIA | 0.3174 | game-dev | 0.863092 | 1 | 0.863092 |
AionGermany/aion-germany | 5,558 | AL-Game/src/com/aionemu/gameserver/model/gameobjects/Summon.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.gameobjects;
import java.util.concurrent.Future;
import com.aionemu.gameserver.ai2.AI2Engine;
import com.aionemu.gameserver.controllers.CreatureController;
import com.aionemu.gameserver.controllers.SummonController;
import com.aionemu.gameserver.controllers.attack.AggroList;
import com.aionemu.gameserver.controllers.attack.PlayerAggroList;
import com.aionemu.gameserver.controllers.movement.SiegeWeaponMoveController;
import com.aionemu.gameserver.controllers.movement.SummonMoveController;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.Race;
import com.aionemu.gameserver.model.TribeClass;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.stats.container.SummonGameStats;
import com.aionemu.gameserver.model.stats.container.SummonLifeStats;
import com.aionemu.gameserver.model.summons.SummonMode;
import com.aionemu.gameserver.model.templates.npc.NpcTemplate;
import com.aionemu.gameserver.model.templates.spawns.SpawnTemplate;
import com.aionemu.gameserver.model.templates.stats.SummonStatsTemplate;
import com.aionemu.gameserver.world.WorldPosition;
/**
* @author ATracer
*/
public class Summon extends Creature {
private Player master;
private SummonMode mode = SummonMode.GUARD;
private byte level;
private int liveTime;
private Future<?> releaseTask;
/**
* @param objId
* @param controller
* @param spawnTemplate
* @param objectTemplate
* @param position
* @param level
*/
public Summon(int objId, CreatureController<? extends Creature> controller, SpawnTemplate spawnTemplate, NpcTemplate objectTemplate, byte level, int time) {
super(objId, controller, spawnTemplate, objectTemplate, new WorldPosition(spawnTemplate.getWorldId()));
controller.setOwner(this);
String ai = objectTemplate.getAi();
AI2Engine.getInstance().setupAI(ai, this);
moveController = ai.equals("siege_weapon") ? new SiegeWeaponMoveController(this) : new SummonMoveController(this);
this.level = level;
this.liveTime = time;
SummonStatsTemplate statsTemplate = DataManager.SUMMON_STATS_DATA.getSummonTemplate(objectTemplate.getTemplateId(), level);
setGameStats(new SummonGameStats(this, statsTemplate));
setLifeStats(new SummonLifeStats(this));
}
@Override
protected AggroList createAggroList() {
return new PlayerAggroList(this);
}
@Override
public SummonGameStats getGameStats() {
return (SummonGameStats) super.getGameStats();
}
@Override
public Player getMaster() {
return master;
}
/**
* @param master
* the master to set
*/
public void setMaster(Player master) {
this.master = master;
}
@Override
public String getName() {
return objectTemplate.getName();
}
/**
* @return the level
*/
@Override
public byte getLevel() {
return level;
}
@Override
public NpcTemplate getObjectTemplate() {
return (NpcTemplate) super.getObjectTemplate();
}
public int getNpcId() {
return getObjectTemplate().getTemplateId();
}
public int getNameId() {
return getObjectTemplate().getNameId();
}
/**
* @return NpcObjectType.SUMMON
*/
@Override
public NpcObjectType getNpcObjectType() {
return NpcObjectType.SUMMON;
}
@Override
public SummonController getController() {
return (SummonController) super.getController();
}
/**
* @return the mode
*/
public SummonMode getMode() {
return mode;
}
/**
* @param mode
* the mode to set
*/
public void setMode(SummonMode mode) {
this.mode = mode;
}
@Override
public boolean isEnemy(Creature creature) {
return master != null ? master.isEnemy(creature) : false;
}
@Override
public boolean isEnemyFrom(Npc npc) {
return master != null ? master.isEnemyFrom(npc) : false;
}
@Override
public boolean isEnemyFrom(Player player) {
return master != null ? master.isEnemyFrom(player) : false;
}
@Override
public TribeClass getTribe() {
if (master == null) {
return ((NpcTemplate) objectTemplate).getTribe();
}
return master.getTribe();
}
@Override
public SummonMoveController getMoveController() {
return (SummonMoveController) super.getMoveController();
}
@Override
public Creature getActingCreature() {
return getMaster() == null ? this : getMaster();
}
@Override
public Race getRace() {
return getMaster() != null ? getMaster().getRace() : Race.NONE;
}
/**
* @return liveTime in sec.
*/
public int getLiveTime() {
return liveTime;
}
/**
* @param liveTime
* in sec.
*/
public void setLiveTime(int liveTime) {
this.liveTime = liveTime;
}
public void setReleaseTask(Future<?> task) {
releaseTask = task;
}
public void cancelReleaseTask() {
if (releaseTask != null && !releaseTask.isDone()) {
releaseTask.cancel(true);
}
}
}
| 0 | 0.963538 | 1 | 0.963538 | game-dev | MEDIA | 0.939157 | game-dev | 0.823898 | 1 | 0.823898 |
ericraio/vanilla-wow-addons | 1,585 | i/IMBA/Mods/Other/IMBA_RangeChecker.lua | function IMBA_RangeChecker_OnUpdate()
if not IMBA_RangeChecker_Active and not IMBA_CheckVar("Range Checker","AlwaysRun") then
this:SetBackdropColor(0.0,0.0,0.0,0.6);
return;
end
if IMBA_RangeChecker_UpdateTime>GetTime() then
return;
end
local PlayerList={};
for i=1,GetNumRaidMembers() do
if UnitExists("raid"..i) and not UnitIsUnit("player", "raid"..i) and (UnitHealth("raid"..i)>0) and (not UnitIsDeadOrGhost("raid"..i)) then
if CheckInteractDistance("raid"..i,3) then
tinsert(PlayerList,{UnitName("raid"..i)});
end
end
end
--table.sort(PlayerList);
local numEntries = getn(PlayerList);
for i=1,5 do
if i<=numEntries then
getglobal("IMBA_RangeChecker_Player"..i):SetText(PlayerList[i][1]);
getglobal("IMBA_RangeChecker_Player"..i):Show();
else
getglobal("IMBA_RangeChecker_Player"..i):Hide();
end
end
if numEntries>5 then
numEntries=5;
end
this:SetHeight(30+16*numEntries);
if numEntries==0 then
this:SetBackdropColor(0.0,1.0,0.0,0.6);
else
this:SetBackdropColor(1.0,0.0,0.0,0.6);
end
IMBA_RangeChecker_UpdateTime=GetTime()+0.1;
end
function IMBA_RangeChecker_OnLoad()
this:SetBackdropBorderColor(1, 1, 1, 1);
this:SetBackdropColor(0.0,0.0,0.0,0.6);
IMBA_RangeChecker_Title:SetText("Range Checker");
IMBA_AddAddon("Range Checker", "Checks for players within 10 yds, Grey=Inactive, Green=Safe and Red=Too Close", IMBA_LOCATIONS_OTHER, nil, nil,nil,"IMBA_RangeChecker");
IMBA_AddOption2("Range Checker","AlwaysRun","Always Running");
IMBA_RangeChecker_UpdateTime=0;
IMBA_RangeChecker_Active=false;
end
| 0 | 0.752088 | 1 | 0.752088 | game-dev | MEDIA | 0.905067 | game-dev | 0.949505 | 1 | 0.949505 |
evemuproject/evemu_server | 2,857 | src/eve-server/station/ReprocessingService.h | /*
------------------------------------------------------------------------------------
LICENSE:
------------------------------------------------------------------------------------
This file is part of EVEmu: EVE Online Server Emulator
Copyright 2006 - 2021 The EVEmu Team
For the latest information visit https://github.com/evemuproject/evemu_server
------------------------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------------
Author: Zhur
*/
#ifndef __REPROCESSING_SVC_H__
#define __REPROCESSING_SVC_H__
#include "PyService.h"
#include "PyBoundObject.h"
#include "station/ReprocessingDB.h"
class ReprocessingService
: public PyService
{
public:
ReprocessingService(PyServiceMgr *mgr);
virtual ~ReprocessingService();
protected:
class Dispatcher;
Dispatcher *const m_dispatch;
ReprocessingDB m_db;
virtual PyBoundObject* CreateBoundObject(Client *pClient, const PyRep *bind_args);
};
class ReprocessingServiceBound
: public PyBoundObject
{
public:
ReprocessingServiceBound(PyServiceMgr *mgr, ReprocessingDB& db, uint32 stationID);
virtual ~ReprocessingServiceBound();
PyCallable_DECL_CALL(GetOptionsForItemTypes);
PyCallable_DECL_CALL(GetReprocessingInfo);
PyCallable_DECL_CALL(GetQuote);
PyCallable_DECL_CALL(GetQuotes);
PyCallable_DECL_CALL(Reprocess);
virtual void Release();
protected:
class Dispatcher;
Dispatcher *const m_dispatch;
ReprocessingDB& m_db;
StationItemRef m_stationRef;
uint32 m_stationCorpID; //corp that owns station. Used for standing
float m_staEfficiency;
float m_tax;
float CalcReprocessingEfficiency(const Client *pClient, InventoryItemRef item = InventoryItemRef(nullptr)) const;
float CalcTax(float standing) const;
PyRep* GetQuote(uint32 itemID, Client* pClient);
float GetStanding(const Client* pClient) const; // gets the higher of char/corp standings with station owner
};
#endif
| 0 | 0.871209 | 1 | 0.871209 | game-dev | MEDIA | 0.312286 | game-dev | 0.733939 | 1 | 0.733939 |
CalamityTeam/CalamityModPublic | 10,027 | Projectiles/Summon/SandElementalMinion.cs | using System;
using CalamityMod.CalPlayer;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Summon
{
public class SandElementalMinion : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Summon";
public int dust = 3;
public override void SetStaticDefaults()
{
Main.projFrames[Projectile.type] = 12;
ProjectileID.Sets.MinionSacrificable[Projectile.type] = true;
ProjectileID.Sets.MinionTargettingFeature[Projectile.type] = true;
}
public override void SetDefaults()
{
Projectile.width = 42;
Projectile.height = 98;
Projectile.netImportant = true;
Projectile.friendly = true;
Projectile.ignoreWater = true;
Projectile.minionSlots = 0f;
Projectile.timeLeft = 18000;
Projectile.penetrate = -1;
Projectile.tileCollide = false;
Projectile.timeLeft *= 5;
Projectile.minion = true;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = 20;
Projectile.DamageType = DamageClass.Summon;
}
public override void AI()
{
Player player = Main.player[Projectile.owner];
CalamityPlayer modPlayer = player.Calamity();
if (!modPlayer.sandWaifu && !modPlayer.allWaifus && !modPlayer.sandWaifuVanity && !modPlayer.allWaifusVanity)
{
Projectile.active = false;
return;
}
bool isMinion = Projectile.type == ModContent.ProjectileType<SandElementalMinion>();
if (isMinion)
{
if (player.dead)
{
modPlayer.sWaifu = false;
}
if (modPlayer.sWaifu)
{
Projectile.timeLeft = 2;
}
}
dust--;
if (dust >= 0)
{
for (int i = 0; i < 50; i++)
{
int dust = Dust.NewDust(new Vector2(Projectile.position.X, Projectile.position.Y + 16f), Projectile.width, Projectile.height - 16, DustID.Sand, 0f, 0f, 0, default, 1f);
Main.dust[dust].velocity *= 2f;
Main.dust[dust].scale *= 1.15f;
}
}
bool passive = modPlayer.sandWaifuVanity || modPlayer.allWaifusVanity;
if (Math.Abs(Projectile.velocity.X) > 0.2f)
{
Projectile.spriteDirection = -Projectile.direction;
}
float attackDistance = 700f; //700
if (!passive)
{
float lights = (float)Main.rand.Next(90, 111) * 0.01f;
lights *= Main.essScale;
Lighting.AddLight(Projectile.Center, 0.7f * lights, 0.6f * lights, 0f * lights);
}
Projectile.MinionAntiClump();
Vector2 projPos = Projectile.position;
bool canAttack = false;
if (Projectile.ai[0] != 1f)
{
Projectile.tileCollide = false;
}
if (Projectile.tileCollide && WorldGen.SolidTile(Framing.GetTileSafely((int)Projectile.Center.X / 16, (int)Projectile.Center.Y / 16)))
{
Projectile.tileCollide = false;
}
if (player.HasMinionAttackTargetNPC && !passive)
{
NPC npc = Main.npc[player.MinionAttackTargetNPC];
if (npc.CanBeChasedBy(Projectile, false))
{
float targetDist = Vector2.Distance(npc.Center, Projectile.Center);
if (!canAttack && targetDist < attackDistance)
{
projPos = npc.Center;
canAttack = true;
}
}
}
if (!canAttack && !passive)
{
foreach (NPC nPC2 in Main.ActiveNPCs)
{
if (nPC2.CanBeChasedBy(Projectile, false))
{
float targetDist = Vector2.Distance(nPC2.Center, Projectile.Center);
if ((!canAttack && targetDist < attackDistance) && Collision.CanHitLine(Projectile.position, Projectile.width, Projectile.height, nPC2.position, nPC2.width, nPC2.height))
{
attackDistance = targetDist;
projPos = nPC2.Center;
canAttack = true;
}
}
}
}
float separationAnxietyDist = 800f;
if (canAttack && !passive)
{
if (Projectile.frame < 6)
{
Projectile.frame = 6;
}
Projectile.frameCounter++;
if (Projectile.frameCounter > 7)
{
Projectile.frame++;
Projectile.frameCounter = 0;
}
if (Projectile.frame > 11)
{
Projectile.frame = 6;
}
separationAnxietyDist = 1200f;
}
else
{
Projectile.frameCounter++;
if (Projectile.frameCounter > 7)
{
Projectile.frame++;
Projectile.frameCounter = 0;
}
if (Projectile.frame > 5)
{
Projectile.frame = 0;
}
}
if (Vector2.Distance(player.Center, Projectile.Center) > separationAnxietyDist)
{
Projectile.ai[0] = 1f;
Projectile.tileCollide = false;
Projectile.netUpdate = true;
}
if (canAttack && Projectile.ai[0] == 0f)
{
Vector2 targetDirection = projPos - Projectile.Center;
float targetDistance = targetDirection.Length();
targetDirection.Normalize();
if (targetDistance > 200f)
{
float scaleFactor2 = 8f;
targetDirection *= scaleFactor2;
Projectile.velocity = (Projectile.velocity * 40f + targetDirection) / 41f;
}
else
{
targetDirection *= -4f;
Projectile.velocity = (Projectile.velocity * 40f + targetDirection) / 41f;
}
}
else
{
bool isReturning = false;
if (!isReturning)
{
isReturning = Projectile.ai[0] == 1f;
}
float returnSpeed = 6f; //6
if (isReturning)
{
returnSpeed = 15f; //16
}
Vector2 center2 = Projectile.Center;
Vector2 playerDirection = player.Center - center2 + new Vector2(250f, -60f); //-60
float playerDist = playerDirection.Length();
if (playerDist > 200f && returnSpeed < 8f) //200 and 8
{
returnSpeed = 8f; //8
}
if (playerDist < 200f && isReturning && !Collision.SolidCollision(Projectile.position, Projectile.width, Projectile.height))
{
Projectile.ai[0] = 0f;
Projectile.netUpdate = true;
}
if (playerDist > 2000f)
{
Projectile.position.X = player.Center.X - (float)(Projectile.width / 2);
Projectile.position.Y = player.Center.Y - (float)(Projectile.height / 2);
Projectile.netUpdate = true;
}
if (playerDist > 70f)
{
playerDirection.Normalize();
playerDirection *= returnSpeed;
Projectile.velocity = (Projectile.velocity * 40f + playerDirection) / 41f;
}
else if (Projectile.velocity.X == 0f && Projectile.velocity.Y == 0f)
{
Projectile.velocity.X = -0.195f;
Projectile.velocity.Y = -0.095f;
}
}
if (Projectile.ai[1] > 0f)
{
Projectile.ai[1] += (float)Main.rand.Next(1, 4);
}
if (Projectile.ai[1] > 220f)
{
Projectile.ai[1] = 0f;
Projectile.netUpdate = true;
}
// Prevent firing immediately
if (Projectile.localAI[0] < 120f)
Projectile.localAI[0] += 1f;
if (Projectile.ai[0] == 0f)
{
float scaleFactor3 = 11f;
int projType = ModContent.ProjectileType<SandBolt>();
if (canAttack && Projectile.ai[1] == 0f && Projectile.localAI[0] >= 120f)
{
Projectile.ai[1] += 1f;
if (Main.myPlayer == Projectile.owner && Collision.CanHitLine(Projectile.position, Projectile.width, Projectile.height, projPos, 0, 0))
{
Vector2 projVel = projPos - Projectile.Center;
projVel.Normalize();
projVel *= scaleFactor3;
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, projVel, projType, Projectile.damage, 0f, Main.myPlayer);
Projectile.netUpdate = true;
}
}
}
}
public override bool? CanDamage() => false;
}
}
| 0 | 0.930376 | 1 | 0.930376 | game-dev | MEDIA | 0.997073 | game-dev | 0.984361 | 1 | 0.984361 |
spring-attic/reactor-core-dotnet | 1,353 | Reactor.Core/publisher/PublisherMaterialize.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reactive.Streams;
using Reactor.Core;
using System.Threading;
using Reactor.Core.flow;
using Reactor.Core.subscriber;
using Reactor.Core.subscription;
using Reactor.Core.util;
namespace Reactor.Core.publisher
{
sealed class PublisherMaterialize<T> : IFlux<ISignal<T>>
{
readonly IPublisher<T> source;
internal PublisherMaterialize(IPublisher<T> source)
{
this.source = source;
}
public void Subscribe(ISubscriber<ISignal<T>> s)
{
source.Subscribe(new MaterializeSubscriber(s));
}
sealed class MaterializeSubscriber : BasicSinglePostCompleteSubscriber<T, ISignal<T>>
{
public MaterializeSubscriber(ISubscriber<ISignal<T>> actual) : base(actual)
{
}
public override void OnComplete()
{
Complete(SignalHelper.Complete<T>());
}
public override void OnError(Exception e)
{
Complete(SignalHelper.Error<T>(e));
}
public override void OnNext(T t)
{
produced++;
actual.OnNext(SignalHelper.Next(t));
}
}
}
}
| 0 | 0.698799 | 1 | 0.698799 | game-dev | MEDIA | 0.277968 | game-dev | 0.500893 | 1 | 0.500893 |
lua9520/source-engine-2018-hl2_src | 9,543 | game/client/tf/tf_hud_arena_class_layout.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "hud.h"
#include "hud_macros.h"
#include "c_tf_player.h"
#include "c_tf_team.h"
#include "c_tf_playerresource.h"
#include "iclientmode.h"
#include "ienginevgui.h"
#include "tf_gamerules.h"
#include <vgui/ILocalize.h>
#include <vgui/ISurface.h>
#include <vgui/IVGui.h>
#include <vgui_controls/EditablePanel.h>
#include "tf_hud_arena_class_layout.h"
#include "tf_hud_menu_spy_disguise.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
const char *g_sImagesBlue[] = {
"",
"class_sel_sm_scout_blu",
"class_sel_sm_sniper_blu",
"class_sel_sm_soldier_blu",
"class_sel_sm_demo_blu",
"class_sel_sm_medic_blu",
"class_sel_sm_heavy_blu",
"class_sel_sm_pyro_blu",
"class_sel_sm_spy_blu",
"class_sel_sm_engineer_blu",
"",
};
const char *g_sImagesRed[] = {
"",
"class_sel_sm_scout_red",
"class_sel_sm_sniper_red",
"class_sel_sm_soldier_red",
"class_sel_sm_demo_red",
"class_sel_sm_medic_red",
"class_sel_sm_heavy_red",
"class_sel_sm_pyro_red",
"class_sel_sm_spy_red",
"class_sel_sm_engineer_red",
"",
};
DECLARE_HUDELEMENT( CHudArenaClassLayout );
bool ArenaClassLayoutKeyInput( int down, ButtonCode_t keynum, const char *pszCurrentBinding )
{
CHudArenaClassLayout *pArenaClassLayoutPanel = ( CHudArenaClassLayout * )GET_HUDELEMENT( CHudArenaClassLayout );
if ( pArenaClassLayoutPanel && pArenaClassLayoutPanel->ShouldDraw() )
{
return pArenaClassLayoutPanel->HandleKeyCodePressed( keynum );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHudArenaClassLayout::CHudArenaClassLayout( const char *pElementName ) : CHudElement( pElementName ), BaseClass( NULL, "HudArenaClassLayout" )
{
Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
vgui::SETUP_PANEL( this );
SetKeyBoardInputEnabled( true );
vgui::ivgui()->AddTickSignal( GetVPanel(), 100 );
m_pBackground = new CTFImagePanel( this, "background" );
m_pLocalPlayerBG = new CTFImagePanel( this, "localPlayerBG" );
m_pTitle = new CExLabel( this, "title", "" );
m_pChangeLabel = new CExLabel( this, "changeLabel", "" );
m_pChangeLabelShadow = new CExLabel( this, "changeLabelShadow", "" );
char tempName[MAX_PATH];
for ( int i = 0 ; i < MAX_CLASS_IMAGES ; ++i )
{
Q_snprintf( tempName, sizeof( tempName ), "classImage%d", i );
m_ClassImages[i] = new CTFImagePanel( this, tempName );
}
SetVisible( false );
RegisterForRenderGroup( "mid" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudArenaClassLayout::Init( void )
{
CHudElement::Init();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudArenaClassLayout::ApplySchemeSettings( IScheme *pScheme )
{
// load control settings...
LoadControlSettings( "resource/UI/HudArenaClassLayout.res" );
BaseClass::ApplySchemeSettings( pScheme );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudArenaClassLayout::PerformLayout( void )
{
if ( !g_TF_PR )
return;
int i = 0;
CUtlVector<int> teamPlayers;
int nLocalPlayerTeam = GetLocalPlayerTeam();
int iImageIndex = 0;
CTFImagePanel *pImage = NULL;
int nImageXPos = 0, nImageYPos = 0;
if ( GetLocalPlayerTeam() <= LAST_SHARED_TEAM )
return;
int nClass = g_TF_PR->GetPlayerClass( GetLocalPlayerIndex() );
if ( nClass == TF_CLASS_UNDEFINED )
return;
// count the number of players on our team that have chosen a playerclass
for ( i = 1 ; i <= MAX_PLAYERS ; i++ )
{
if ( g_TF_PR->GetTeam( i ) == GetLocalPlayerTeam() )
{
if ( g_TF_PR->GetPlayerClass( i ) > TF_CLASS_UNDEFINED )
{
teamPlayers.AddToTail( i );
}
}
if ( teamPlayers.Count() >= MAX_CLASS_IMAGES )
{
break;
}
}
if ( teamPlayers.Count() > 0 )
{
int nBackgroundXPos, nBackgroundYPos, nBackgroundWide, nBackgroundTall;
int nImageWide = m_ClassImages[iImageIndex]->GetWide();
int nTotalWidth = ( teamPlayers.Count() * nImageWide ) + ( 2 * XRES( 10 ) ); // the XRES(10) is for the background to be scaled to cover the images on both ends
int nXPos = ( GetWide() - nTotalWidth ) * 0.5;
m_pBackground->GetBounds( nBackgroundXPos, nBackgroundYPos, nBackgroundWide, nBackgroundTall );
m_pBackground->SetBounds( nXPos, nBackgroundYPos, nTotalWidth, nBackgroundTall );
// this is where our first image will start
nXPos += XRES( 10 );
// the first image on the left is always the local player (and we'll have a special background behind it)
pImage = m_ClassImages[iImageIndex];
iImageIndex++;
if ( pImage )
{
pImage->SetVisible( true );
pImage->GetPos( nImageXPos, nImageYPos ); // only really care about the YPos here
pImage->SetPos( nXPos, nImageYPos );
pImage->SetImage( nLocalPlayerTeam == TF_TEAM_BLUE ? g_sImagesBlue[nClass] : g_sImagesRed[nClass] );
if ( teamPlayers.Count() > 1 )
{
// local player background
int nBGXPos, nBGYPos;
m_pLocalPlayerBG->SetVisible( true );
m_pLocalPlayerBG->GetPos( nBGXPos, nBGYPos );
m_pLocalPlayerBG->SetPos( nXPos, nBGYPos );
}
else
{
m_pLocalPlayerBG->SetVisible( false );
}
nXPos += nImageWide;
}
for ( i = 0 ; i < teamPlayers.Count() ; i++ )
{
int iPlayerIndex = teamPlayers[i];
if ( iPlayerIndex == GetLocalPlayerIndex() )
continue;
if ( iImageIndex >= MAX_CLASS_IMAGES )
continue;
if ( g_TF_PR->GetTeam( iPlayerIndex ) == GetLocalPlayerTeam() )
{
nClass = g_TF_PR->GetPlayerClass( iPlayerIndex );
if ( nClass == TF_CLASS_UNDEFINED )
continue;
pImage = m_ClassImages[iImageIndex];
if ( pImage )
{
pImage->SetVisible( true );
pImage->SetPos( nXPos, nImageYPos );
pImage->SetImage( nLocalPlayerTeam == TF_TEAM_BLUE ? g_sImagesBlue[nClass] : g_sImagesRed[nClass] );
nXPos += nImageWide;
}
iImageIndex++;
}
}
}
// turn off any unused images
while ( iImageIndex < MAX_CLASS_IMAGES )
{
pImage = m_ClassImages[iImageIndex];
if ( pImage )
{
pImage->SetVisible( false );
}
iImageIndex++;
}
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pLocalPlayer && m_pChangeLabel && m_pChangeLabelShadow )
{
bool bShow = true;
if ( ( pLocalPlayer->m_Shared.GetArenaNumChanges() >= tf_arena_change_limit.GetInt() ) ||
( tf_arena_force_class.GetBool() == false ) )
{
bShow = false;
}
if ( m_pChangeLabel->IsVisible() != bShow )
{
m_pChangeLabel->SetVisible( bShow );
m_pChangeLabelShadow->SetVisible( bShow );
}
}
BaseClass::PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudArenaClassLayout::ShouldDraw( void )
{
if ( TFGameRules() == NULL )
return false;
if ( CHudElement::ShouldDraw() == false )
return false;
if ( TFGameRules()->State_Get() != GR_STATE_PREROUND )
return false;
if ( TFGameRules()->IsInArenaMode() == false )
return false;
if ( GetLocalPlayerTeam() > LAST_SHARED_TEAM )
{
if ( ( tf_arena_force_class.GetBool() == true ) || ( GetGlobalTeam( GetLocalPlayerTeam() )->Get_Number_Players() > 1 ) )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pLocalPlayer && pLocalPlayer->IsAlive() )
{
C_TFPlayerClass *pClass = pLocalPlayer->GetPlayerClass();
if ( pClass && pClass->GetClassIndex() != TF_CLASS_UNDEFINED )
{
return true;
}
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudArenaClassLayout::SetVisible( bool state )
{
IGameEvent *event = gameeventmanager->CreateEvent( "show_class_layout" );
if ( event )
{
event->SetBool( "show", state );
gameeventmanager->FireEventClientSide( event );
}
BaseClass::SetVisible( state );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudArenaClassLayout::OnTick( void )
{
bool bVisible = ShouldDraw();
if ( bVisible != IsVisible() )
{
SetVisible( bVisible );
}
if ( !bVisible )
return;
InvalidateLayout( true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudArenaClassLayout::HandleKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_F4 )
{
if ( ShouldDraw() && ( tf_arena_force_class.GetBool() == true ) )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pLocalPlayer && ( pLocalPlayer->m_Shared.GetArenaNumChanges() < tf_arena_change_limit.GetInt() ) )
{
engine->ClientCmd( "arena_changeclass" );
}
}
}
return false;
}
| 0 | 0.934252 | 1 | 0.934252 | game-dev | MEDIA | 0.788557 | game-dev,desktop-app | 0.950512 | 1 | 0.950512 |
Deadrik/TFCraft | 13,575 | src/Common/com/bioxx/tfc/Items/Pottery/ItemPotterySmallVessel.java | package com.bioxx.tfc.Items.Pottery;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import com.bioxx.tfc.Reference;
import com.bioxx.tfc.TerraFirmaCraft;
import com.bioxx.tfc.Core.TFC_Core;
import com.bioxx.tfc.Core.TFC_Time;
import com.bioxx.tfc.Core.Metal.Alloy;
import com.bioxx.tfc.Core.Metal.AlloyManager;
import com.bioxx.tfc.Core.Metal.AlloyMetal;
import com.bioxx.tfc.Food.ItemFoodTFC;
import com.bioxx.tfc.Items.ItemOre;
import com.bioxx.tfc.Items.ItemOreSmall;
import com.bioxx.tfc.api.Food;
import com.bioxx.tfc.api.Metal;
import com.bioxx.tfc.api.Enums.EnumSize;
import com.bioxx.tfc.api.Enums.EnumWeight;
import com.bioxx.tfc.api.Interfaces.IBag;
import com.bioxx.tfc.api.Interfaces.ISmeltable;
import com.bioxx.tfc.api.Util.Helper;
public class ItemPotterySmallVessel extends ItemPotteryBase implements IBag
{
@SideOnly(Side.CLIENT)
private IIcon overlayIcon;
public ItemPotterySmallVessel()
{
super();
this.metaNames = new String[]{"Clay Vessel", "Ceramic Vessel", "Ceramic Vessel"};
this.setMaxStackSize(1);
this.setWeight(EnumWeight.MEDIUM);
this.setSize(EnumSize.SMALL);
}
@Override
@SideOnly(Side.CLIENT)
public boolean requiresMultipleRenderPasses()
{
return true;
}
@Override
public IIcon getIcon(ItemStack stack, int pass)
{
if (pass == 1 && stack.getTagCompound() != null && stack.getTagCompound().hasKey("color"))
return overlayIcon;
return super.getIcon(stack, pass);
}
@Override
public void registerIcons(IIconRegister registerer)
{
super.registerIcons(registerer);
this.overlayIcon = registerer.registerIcon(Reference.MOD_ID + ":" + textureFolder + "Ceramic Vessel Overlay");
}
@Override
public void getSubItems(Item item, CreativeTabs tabs, List list)
{
list.add(new ItemStack(this, 1, 0));
list.add(new ItemStack(this, 1, 1));
}
@Override
public boolean canStack()
{
return false;
}
@Override
public void onDoneCooking(World world, ItemStack is, Alloy.EnumTier furnaceTier)
{
ItemStack[] bag = loadBagInventory(is);
boolean canCookAlloy = true;
for(int i = 0; bag != null && i < 4; i++)
{
if(bag[i] != null)
{
if(!(bag[i].getItem() instanceof ItemOreSmall) && !(bag[i].getItem() instanceof ItemOre))
canCookAlloy = false;
}
}
if(is.getItemDamage() == 2)
{
NBTTagCompound tag = is.stackTagCompound;
long totalH = TFC_Time.getTotalHours();
tag.setLong("TempTimer", totalH);
}
if(canCookAlloy && bag != null)
{
Metal[] types = new Metal[4];
int[] metalAmounts = new int[4];
if(bag[0] != null)
{
types[0] = ((ISmeltable)bag[0].getItem()).getMetalType(bag[0]);
metalAmounts[0] = ((ISmeltable)bag[0].getItem()).getMetalReturnAmount(bag[0]) * bag[0].stackSize;
}
if(bag[1] != null)
{
types[1] = ((ISmeltable)bag[1].getItem()).getMetalType(bag[1]);
metalAmounts[1] = ((ISmeltable)bag[1].getItem()).getMetalReturnAmount(bag[1]) * bag[1].stackSize;
if(mergeMetals(types[0], types[1], metalAmounts[0], metalAmounts[1]) != metalAmounts[0])
{
metalAmounts[0] = mergeMetals(types[0], types[1], metalAmounts[0], metalAmounts[1]);
types[1] = null;
metalAmounts[1] = 0;
}
}
if(bag[2] != null)
{
types[2] = ((ISmeltable)bag[2].getItem()).getMetalType(bag[2]);
metalAmounts[2] = ((ISmeltable)bag[2].getItem()).getMetalReturnAmount(bag[2]) * bag[2].stackSize;
if(mergeMetals(types[0], types[2], metalAmounts[0], metalAmounts[2]) != metalAmounts[0])
{
metalAmounts[0] = mergeMetals(types[0], types[2], metalAmounts[0], metalAmounts[2]);
types[2] = null;
metalAmounts[2] = 0;
}
if(mergeMetals(types[1], types[2], metalAmounts[1], metalAmounts[2]) != metalAmounts[1])
{
metalAmounts[1] = mergeMetals(types[1], types[2], metalAmounts[1], metalAmounts[2]);
types[2] = null;
metalAmounts[2] = 0;
}
}
if(bag[3] != null)
{
types[3] = ((ISmeltable)bag[3].getItem()).getMetalType(bag[3]);
metalAmounts[3] = ((ISmeltable)bag[3].getItem()).getMetalReturnAmount(bag[3]) * bag[3].stackSize;
if(mergeMetals(types[0], types[3], metalAmounts[0], metalAmounts[3]) != metalAmounts[0])
{
metalAmounts[0] = mergeMetals(types[0], types[3], metalAmounts[0], metalAmounts[3]);
types[3] = null;
metalAmounts[3] = 0;
}
if(mergeMetals(types[1], types[3], metalAmounts[1], metalAmounts[3]) != metalAmounts[1])
{
metalAmounts[1] = mergeMetals(types[1], types[3], metalAmounts[1], metalAmounts[3]);
types[3] = null;
metalAmounts[3] = 0;
}
if(mergeMetals(types[2], types[3], metalAmounts[2], metalAmounts[3]) != metalAmounts[2])
{
metalAmounts[2] = mergeMetals(types[2], types[3], metalAmounts[2], metalAmounts[3]);
types[3] = null;
metalAmounts[3] = 0;
}
}
int total = metalAmounts[0] + metalAmounts[1] + metalAmounts[2] + metalAmounts[3];
/*int numMetals = 0;
if(metalAmounts[0] > 0)
numMetals++;
if(metalAmounts[1] > 0)
numMetals++;
if(metalAmounts[2] > 0)
numMetals++;
if(metalAmounts[3] > 0)
numMetals++;*/
if(total > 0)
{
float[] metalPercent = new float[4];
metalPercent[0] = ((float)metalAmounts[0] / (float)total) * 100f;
metalPercent[1] = ((float)metalAmounts[1] / (float)total) * 100f;
metalPercent[2] = ((float)metalAmounts[2] / (float)total) * 100f;
metalPercent[3] = ((float)metalAmounts[3] / (float)total) * 100f;
List<AlloyMetal> a = new ArrayList<AlloyMetal>();
if(types[0] != null)
a.add(new AlloyMetal(types[0], metalPercent[0]));
if(types[1] != null)
a.add(new AlloyMetal(types[1], metalPercent[1]));
if(types[2] != null)
a.add(new AlloyMetal(types[2], metalPercent[2]));
if(types[3] != null)
a.add(new AlloyMetal(types[3], metalPercent[3]));
Metal match = AlloyManager.INSTANCE.matchesAlloy(a, furnaceTier);
if(match != null)
{
Alloy output = new Alloy(match, total);
NBTTagCompound tag = is.stackTagCompound;
tag.setString("MetalType", output.outputType.name);
tag.setInteger("MetalAmount", (int)output.outputAmount);
long totalH = TFC_Time.getTotalHours();
tag.setLong("TempTimer", totalH);
is.getTagCompound().removeTag("Items");
is.setItemDamage(2);
}
}
}
}
private int mergeMetals(Metal mt0, Metal mt1, int m0, int m1)
{
if(mt0 != null && mt1 != null && m0 > 0)
{
if(mt0.name.equals(mt1.name))
return m0 + m1;
}
return m0;
}
@Override
@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack is, int pass)
{
if (pass != 1)
{
return 0xFFFFFF; // White multiplier does not change the color.
}
else
{
int j = this.getColor(is);
if (j < 0) // No NBT flag for color
{
return 0xFFFFFF; // White multiplier does not change the color.
}
if (is.getItemDamage() == 0) // Unfired Vessels
{
/*
* Increase each color value by 0x60 so the overlay on unfired vessels is lighter.
* Make sure that none of the color values go above 0xFF or else it bleeds into
* the other colors.
*/
int r = Math.min((j >> 16) + 0x60, 0xFF);
int b = Math.min(((j >> 8) & 0x00FF) + 0x60, 0xFF); //NOPMD
int g = Math.min((j & 0x0000FF) + 0x60, 0xFF); //NOPMD
return (r << 16) | (b << 8) | g;
}
else
return j;
}
}
public int getColor(ItemStack is)
{
if (!is.hasTagCompound() || !is.getTagCompound().hasKey("color"))
return -1;
else
return is.getTagCompound().getInteger("color");
}
@Override
public ItemStack[] loadBagInventory(ItemStack is)
{
ItemStack[] bag = new ItemStack[4];
if(is != null && is.hasTagCompound() && is.getTagCompound().hasKey("Items"))
{
NBTTagList nbttaglist = is.getTagCompound().getTagList("Items", 10);
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
byte byte0 = nbttagcompound1.getByte("Slot");
if(byte0 >= 0 && byte0 < 4)
bag[byte0] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
else
return null;
return bag;
}
@Override
public boolean onUpdate(ItemStack is, World world, int x, int y, int z)
{
ItemStack[] bag = loadBagInventory(is);
if(bag != null)
{
TFC_Core.handleItemTicking(bag, world, x, y, z, 0.5f);
for(ItemStack i : bag)
{
if(i != null && i.stackSize == 0)
i = null;
}
saveContents(is, bag);
}
return true;
}
public void saveContents(ItemStack vessel, ItemStack[] bag)
{
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < 4; i++)
{
if(bag[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
bag[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
if(vessel != null)
{
if(!vessel.hasTagCompound())
vessel.setTagCompound(new NBTTagCompound());
vessel.getTagCompound().setTag("Items", nbttaglist);
}
}
@Override
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
{
if(!entityplayer.isSneaking())
{
if (itemstack.getItemDamage() == 2)
{
NBTTagCompound nbt = itemstack.getTagCompound();
if (nbt == null)
{
itemstack.setItemDamage(1);
if (!world.isRemote) // Prevent double logging.
{
String error = TFC_Core.translate("error.error") + " " + itemstack.getUnlocalizedName() + " " +
TFC_Core.translate("error.NBT") + " " + TFC_Core.translate("error.Contact");
TerraFirmaCraft.LOG.error(error);
TFC_Core.sendInfoMessage(entityplayer, new ChatComponentText(error));
}
}
else if (nbt.hasKey("TempTimer"))
{
long temp = nbt.getLong("TempTimer");
if(TFC_Time.getTotalHours() - temp < 11)
entityplayer.openGui(TerraFirmaCraft.instance, 19, entityplayer.worldObj, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
}
else if (itemstack.getItemDamage() == 1)
{
entityplayer.openGui(TerraFirmaCraft.instance, 39, entityplayer.worldObj, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
}
return itemstack;
}
@Override
public void addItemInformation(ItemStack is, EntityPlayer player, List<String> arraylist)
{
NBTTagCompound tag = is.stackTagCompound;
if(tag != null)
{
if(tag.hasKey("MetalType"))
{
String name = tag.getString("MetalType");
name = name.replace(" ", "");
name = TFC_Core.translate("gui.metal." + name);
// check if the vessel contains an amount of metal.
if(tag.hasKey("MetalAmount"))
{
// suffix the amount of metal to the metal name.
name += " (" + tag.getInteger("MetalAmount")+" "+TFC_Core.translate("gui.units")+")";
}
arraylist.add(EnumChatFormatting.DARK_GREEN + name);
}
if(tag.hasKey("TempTimer"))
{
long total = TFC_Time.getTotalHours();
long temp = tag.getLong("TempTimer");
if(total - temp < 11)
arraylist.add(EnumChatFormatting.WHITE + TFC_Core.translate("gui.ItemHeat.Liquid"));
else
arraylist.add(EnumChatFormatting.WHITE + TFC_Core.translate("gui.ItemHeat.Solidified"));
}
if(tag.hasKey("Items"))
{
NBTTagList nbttaglist = tag.getTagList("Items", 10);
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
byte byte0 = nbttagcompound1.getByte("Slot");
if(byte0 >= 0 && byte0 < 4)
{
ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound1);
if(itemstack.stackSize > 0)
{
if(itemstack.getItem() instanceof ItemFoodTFC)
{
float decay = Food.getDecay(itemstack);
float weight = Helper.roundNumber(Food.getWeight(itemstack), 100);
String ds = " " + EnumChatFormatting.DARK_GRAY + Helper.roundNumber(decay / weight * 100, 10) + "%";
if (decay <= 0)
ds = "";
arraylist.add(EnumChatFormatting.GOLD.toString() + itemstack.getItem().getItemStackDisplayName(itemstack) + " " + EnumChatFormatting.WHITE+weight + "oz" + ds);
}
else
arraylist.add(EnumChatFormatting.GOLD.toString() + itemstack.stackSize + "x " + itemstack.getItem().getItemStackDisplayName(itemstack));
}
}
}
}
}
}
@Override
public void addExtraInformation(ItemStack is, EntityPlayer player, List<String> arraylist)
{
if (TFC_Core.showShiftInformation())
{
arraylist.add(TFC_Core.translate("gui.Help"));
arraylist.add(TFC_Core.translate("gui.PotteryBase.Inst0"));
NBTTagCompound tag = is.stackTagCompound;
if (tag != null && tag.hasKey("TempTimer"))
{
long total = TFC_Time.getTotalHours();
long temp = tag.getLong("TempTimer");
if (total - temp < 11)
arraylist.add(TFC_Core.translate("gui.PotteryVesselSmall.Inst0"));
}
else
arraylist.add(TFC_Core.translate("gui.PotteryVesselSmall.Inst0"));
}
else
{
arraylist.add(TFC_Core.translate("gui.ShowHelp"));
}
}
}
| 0 | 0.887098 | 1 | 0.887098 | game-dev | MEDIA | 0.995056 | game-dev | 0.979351 | 1 | 0.979351 |
hakan-krgn/hCore | 3,097 | hCore-bukkit/nms/v1_15_R1/src/main/java/com/hakan/core/item/nbt/NbtManager_v1_15_R1.java | package com.hakan.core.item.nbt;
import com.hakan.core.utils.Validate;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.server.v1_15_R1.MojangsonParser;
import net.minecraft.server.v1_15_R1.NBTTagCompound;
import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nonnull;
/**
* {@inheritDoc}
*/
public final class NbtManager_v1_15_R1 implements NbtManager {
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public ItemStack set(@Nonnull ItemStack itemStack, @Nonnull String key, @Nonnull String value) {
Validate.notNull(itemStack, "itemStack cannot be null");
Validate.notNull(key, "key cannot be null");
Validate.notNull(value, "value cannot be null");
net.minecraft.server.v1_15_R1.ItemStack nmsCopy = CraftItemStack.asNMSCopy(itemStack);
if (nmsCopy == null)
return itemStack;
else if (!nmsCopy.hasTag())
nmsCopy.setTag(new NBTTagCompound());
nmsCopy.getTag().setString(key, value);
return CraftItemStack.asBukkitCopy(nmsCopy);
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public ItemStack set(@Nonnull ItemStack itemStack, @Nonnull String nbt) {
Validate.notNull(itemStack, "itemStack cannot be null");
Validate.notNull(nbt, "nbt cannot be null");
net.minecraft.server.v1_15_R1.ItemStack nmsCopy = CraftItemStack.asNMSCopy(itemStack);
if (nmsCopy == null)
return itemStack;
else if (!nmsCopy.hasTag())
nmsCopy.setTag(new NBTTagCompound());
nmsCopy.getTag().a(this.parse(nbt));
return CraftItemStack.asBukkitCopy(nmsCopy);
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public String get(@Nonnull ItemStack itemStack, @Nonnull String key) {
Validate.notNull(itemStack, "itemStack cannot be null");
Validate.notNull(key, "key cannot be null");
net.minecraft.server.v1_15_R1.ItemStack nmsCopy = CraftItemStack.asNMSCopy(itemStack);
if (nmsCopy == null)
return "{}";
else if (!nmsCopy.hasTag())
nmsCopy.setTag(new NBTTagCompound());
NBTTagCompound nbtTagCompound = nmsCopy.getTag();
return nbtTagCompound.hasKey(key) ? nbtTagCompound.getString(key) : "{}";
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public String get(@Nonnull ItemStack itemStack) {
Validate.notNull(itemStack, "itemStack cannot be null");
net.minecraft.server.v1_15_R1.ItemStack nmsCopy = CraftItemStack.asNMSCopy(itemStack);
if (nmsCopy == null)
return "{}";
else if (!nmsCopy.hasTag())
nmsCopy.setTag(new NBTTagCompound());
return nmsCopy.getTag().toString();
}
private NBTTagCompound parse(String nbt) {
try {
return MojangsonParser.parse(nbt);
} catch (CommandSyntaxException e) {
throw new RuntimeException(e);
}
}
}
| 0 | 0.855076 | 1 | 0.855076 | game-dev | MEDIA | 0.962011 | game-dev | 0.748904 | 1 | 0.748904 |
supertuxkart/stk-code | 3,085 | src/states_screens/dialogs/splitscreen_player_dialog.hpp | // SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2018 SuperTuxKart-Team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_SPLITSCREEN_PLAYER_DIALOG_HPP
#define HEADER_SPLITSCREEN_PLAYER_DIALOG_HPP
#include "guiengine/modaldialog.hpp"
#include "utils/types.hpp"
#include <irrString.h>
#include <vector>
class InputDevice;
class PlayerProfile;
namespace GUIEngine
{
class CheckBoxWidget;
class IconButtonWidget;
class LabelWidget;
class RibbonWidget;
class SpinnerWidget;
}
/**
* \brief Dialog that handle user in network lobby
* \ingroup states_screens
*/
class SplitscreenPlayerDialog : public GUIEngine::ModalDialog
{
private:
InputDevice* m_device;
bool m_self_destroy;
std::vector<PlayerProfile*> m_available_players;
GUIEngine::LabelWidget* m_message;
GUIEngine::SpinnerWidget* m_profiles;
GUIEngine::CheckBoxWidget* m_handicap;
GUIEngine::RibbonWidget* m_options_widget;
GUIEngine::IconButtonWidget* m_add;
GUIEngine::IconButtonWidget* m_connect;
GUIEngine::IconButtonWidget* m_cancel;
GUIEngine::IconButtonWidget* m_reset;
public:
SplitscreenPlayerDialog(InputDevice* device)
: ModalDialog(0.8f,0.8f), m_device(device), m_self_destroy(false)
{
loadFromFile("online/splitscreen_player_dialog.stkgui");
}
// ------------------------------------------------------------------------
~SplitscreenPlayerDialog() {}
// ------------------------------------------------------------------------
virtual void beforeAddingWidgets();
// ------------------------------------------------------------------------
void onEnterPressedInternal() { m_self_destroy = true; }
// ------------------------------------------------------------------------
GUIEngine::EventPropagation processEvent(const std::string& source);
// ------------------------------------------------------------------------
virtual bool onEscapePressed()
{
m_self_destroy = true;
return false;
}
// ------------------------------------------------------------------------
virtual void onUpdate(float dt)
{
// It's unsafe to delete from inside the event handler so we do it here
if (m_self_destroy)
{
ModalDialog::dismiss();
return;
}
}
};
#endif
| 0 | 0.915113 | 1 | 0.915113 | game-dev | MEDIA | 0.727179 | game-dev,desktop-app | 0.537342 | 1 | 0.537342 |
P3pp3rF1y/AncientWarfare2 | 12,607 | src/main/java/net/shadowmage/ancientwarfare/npc/init/AWNPCEntities.java | package net.shadowmage.ancientwarfare.npc.init;
import com.google.common.collect.ImmutableList;
import net.minecraft.entity.Entity;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.shadowmage.ancientwarfare.core.entity.AWEntityRegistry;
import net.shadowmage.ancientwarfare.core.entity.AWEntityRegistry.EntityDeclaration;
import net.shadowmage.ancientwarfare.core.init.AWCoreItems;
import net.shadowmage.ancientwarfare.npc.AncientWarfareNPC;
import net.shadowmage.ancientwarfare.npc.entity.NpcBard;
import net.shadowmage.ancientwarfare.npc.entity.NpcBase;
import net.shadowmage.ancientwarfare.npc.entity.NpcCombat;
import net.shadowmage.ancientwarfare.npc.entity.NpcCourier;
import net.shadowmage.ancientwarfare.npc.entity.NpcPriest;
import net.shadowmage.ancientwarfare.npc.entity.NpcTrader;
import net.shadowmage.ancientwarfare.npc.entity.NpcWorker;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFaction;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionArcher;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionArcherElite;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionBard;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionCivilianFemale;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionCivilianMale;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionLeader;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionLeaderElite;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionMountedArcher;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionMountedSoldier;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionPriest;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionSiegeEngineer;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionSoldier;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionSoldierElite;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionSpellcaster;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionSpellcasterWizardry;
import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFactionTrader;
import net.shadowmage.ancientwarfare.npc.entity.vehicle.NpcSiegeEngineer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
@Mod.EventBusSubscriber(modid = AncientWarfareNPC.MOD_ID)
public class AWNPCEntities {
private AWNPCEntities() {}
private static final String COMBAT_TYPE = "combat";
private static final String SOLDIER_SUBTYPE = "soldier";
private static final String COMMANDER_SUBTYPE = "commander";
private static final String ARCHER_SUBTYPE = "archer";
private static final String WORKER_TYPE = "worker";
private static final String MINER_SUBTYPE = "miner";
private static final String SPELLCASTER_SUBTYPE = "spellcaster";
private static int nextID = 0;
private static NpcFactionDeclaration wizreg;
/*
* Npc base type -> NpcDeclaration<br>
* Used to retrieve declaration for creating entities<br>
* NpcDeclaration also stores information pertaining to npc-sub-type basic setup
*/
private static final HashMap<String, NpcDeclaration> npcMap = new HashMap<>();
@SubscribeEvent
public static void register(RegistryEvent.Register<EntityEntry> event) {
addPlayerOwnedNpcs();
addFaction();
}
private static void addPlayerOwnedNpcs() {
NpcDeclaration reg = new NpcDeclaration(NpcCombat.class, AWEntityRegistry.NPC_COMBAT, COMBAT_TYPE, SOLDIER_SUBTYPE);
reg.addSubTypes(COMMANDER_SUBTYPE, SOLDIER_SUBTYPE, ARCHER_SUBTYPE, "medic", "engineer");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcWorker.class, AWEntityRegistry.NPC_WORKER, WORKER_TYPE, MINER_SUBTYPE);
reg.addSubTypes(MINER_SUBTYPE, "farmer", "lumberjack", "researcher", "craftsman");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcCourier.class, AWEntityRegistry.NPC_COURIER, "courier");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcTrader.class, AWEntityRegistry.NPC_TRADER, "trader");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcPriest.class, AWEntityRegistry.NPC_PRIEST, "priest");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcBard.class, AWEntityRegistry.NPC_BARD, "bard");
addNpcRegistration(reg);
reg = new NpcDeclaration(NpcSiegeEngineer.class, AWEntityRegistry.NPC_SIEGE_ENGINEER, "siege_engineer");
addNpcRegistration(reg);
}
private static void addFaction() {
NpcFactionDeclaration reg;
reg = new NpcFactionDeclaration(NpcFactionArcher.class, AWEntityRegistry.NPC_FACTION_ARCHER, ARCHER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionSoldier.class, AWEntityRegistry.NPC_FACTION_SOLDIER, SOLDIER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionLeader.class, AWEntityRegistry.NPC_FACTION_COMMANDER, COMMANDER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionPriest.class, AWEntityRegistry.NPC_FACTION_PRIEST, "priest");
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionTrader.class, AWEntityRegistry.NPC_FACTION_TRADER, "trader");
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionMountedSoldier.class, AWEntityRegistry.NPC_FACTION_CAVALRY, SOLDIER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionMountedArcher.class, AWEntityRegistry.NPC_FACTION_MOUNTED_ARCHER, ARCHER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionCivilianMale.class, AWEntityRegistry.NPC_FACTION_CIVILIAN_MALE, "civilian_male");
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionCivilianFemale.class, AWEntityRegistry.NPC_FACTION_CIVILIAN_FEMALE, "civilian_female");
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionArcherElite.class, AWEntityRegistry.NPC_FACTION_ARCHER_ELITE, ARCHER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionSoldierElite.class, AWEntityRegistry.NPC_FACTION_SOLDIER_ELITE, SOLDIER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionLeaderElite.class, AWEntityRegistry.NPC_FACTION_LEADER_ELITE, COMMANDER_SUBTYPE);
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionBard.class, AWEntityRegistry.NPC_FACTION_BARD, "bard");
addNpcRegistration(reg);
reg = new NpcFactionDeclaration(NpcFactionSiegeEngineer.class, AWEntityRegistry.NPC_FACTION_SIEGE_ENGINEER, "siege_engineer");
addNpcRegistration(reg);
registerSpellcasterFactionNpc();
}
private static void registerSpellcasterFactionNpc() {
NpcFactionDeclaration reg;
/* optional dependency for EBWizardry spell casters
* References to the EBWizardry specific class can only be here, to avoid class loading if the mod is no present.
* Any reference outside of the lambdas will crash the game if EBWizardry is not present */
Supplier<Runnable> registerWizardrySpellcaster = () -> () -> {
wizreg = new NpcFactionDeclaration(NpcFactionSpellcasterWizardry.class, AWEntityRegistry.NPC_FACTION_SPELLCASTER, SPELLCASTER_SUBTYPE);
addNpcRegistration(wizreg);
};
if (Loader.isModLoaded("ebwizardry")) {
registerWizardrySpellcaster.get().run();
} else {
reg = new NpcFactionDeclaration(NpcFactionSpellcaster.class, AWEntityRegistry.NPC_FACTION_SPELLCASTER, SPELLCASTER_SUBTYPE);
addNpcRegistration(reg);
}
}
/*
* has to be called during post-init so that all items/etc are fully initialized
*/
public static void loadNpcSubtypeEquipment() {
addNpcSubtypeEquipment(WORKER_TYPE, "farmer", new ItemStack(Items.IRON_HOE));
addNpcSubtypeEquipment(WORKER_TYPE, MINER_SUBTYPE, new ItemStack(Items.IRON_PICKAXE));
addNpcSubtypeEquipment(WORKER_TYPE, "lumberjack", new ItemStack(Items.IRON_AXE));
addNpcSubtypeEquipment(WORKER_TYPE, "researcher", new ItemStack(AWCoreItems.IRON_QUILL));
addNpcSubtypeEquipment(WORKER_TYPE, "craftsman", new ItemStack(AWCoreItems.IRON_HAMMER));
addNpcSubtypeEquipment(COMBAT_TYPE, COMMANDER_SUBTYPE, new ItemStack(AWNPCItems.IRON_COMMAND_BATON));
addNpcSubtypeEquipment(COMBAT_TYPE, SOLDIER_SUBTYPE, new ItemStack(Items.IRON_SWORD));
addNpcSubtypeEquipment(COMBAT_TYPE, ARCHER_SUBTYPE, new ItemStack(Items.BOW));
addNpcSubtypeEquipment(COMBAT_TYPE, "engineer", new ItemStack(AWCoreItems.IRON_HAMMER));
addNpcSubtypeEquipment(COMBAT_TYPE, "medic", new ItemStack(Items.IRON_AXE));
}
private static void addNpcRegistration(NpcDeclaration reg) {
AWEntityRegistry.registerEntity(reg);
getNpcMap().put(reg.getNpcType(), reg);
}
public static NpcBase createNpc(World world, String npcType, String npcSubtype, String faction) {
if (!getNpcMap().containsKey(npcType)) {
return null;
}
NpcDeclaration reg = getNpcMap().get(npcType);
return reg.createEntity(world, npcSubtype, faction);
}
private static void addNpcSubtypeEquipment(String npcType, String npcSubtype, ItemStack equipment) {
if (!getNpcMap().containsKey(npcType)) {
throw new IllegalArgumentException("npc type must first be mapped");
}
NpcDeclaration reg = getNpcMap().get(npcType);
reg.addSubtypeEquipment(npcSubtype, equipment);
}
public static Map<String, NpcDeclaration> getNpcMap() {
return npcMap;
}
public static NpcDeclaration getNpcDeclaration(String npcType) {
return npcMap.get(npcType);
}
public static class NpcDeclaration extends EntityDeclaration {
private final String itemModelVariant;
private boolean spawnBaseEntity = true;
private final String npcType;
private final HashMap<String, ItemStack> spawnEquipment = new HashMap<>();
public NpcDeclaration(Class<? extends Entity> entityClass, String entityName, String npcType) {
this(entityClass, entityName, npcType, npcType.replace(".", "_"));
}
public NpcDeclaration(Class<? extends Entity> entityClass, String entityName, String npcType, String itemModelVariant) {
super(entityClass, entityName, nextID++, AncientWarfareNPC.MOD_ID);
this.npcType = npcType;
this.itemModelVariant = itemModelVariant;
}
public String getFaction() {
return "";
}
private void addSubTypes(String... subTypes) {
Arrays.stream(subTypes).forEach(s -> addSubtypeEquipment(s, ItemStack.EMPTY));
}
private void addSubtypeEquipment(String type, ItemStack equipment) {
spawnEquipment.put(type, equipment);
}
public NpcBase createEntity(World world, String subType, String factionName) {
NpcBase npc = (NpcBase) createEntity(world);
if (!subType.isEmpty()) {
ItemStack stack = spawnEquipment.get(subType);
if (!stack.isEmpty()) {
npc.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, stack.copy());
}
}
return npc;
}
@Override
public final Object mod() {
return AncientWarfareNPC.instance;
}
@Override
public final int trackingRange() {
return 120;
}
@Override
public final int updateFrequency() {
return 3;
}
@Override
public final boolean sendsVelocityUpdates() {
return true;
}
public List<String> getItemModelVariants() {
return new ImmutableList.Builder<String>().addAll(spawnEquipment.keySet()).add(itemModelVariant).build();
}
public String getItemModelVariant(String npcSubType) {
if (npcSubType.isEmpty()) {
return itemModelVariant;
}
return npcSubType;
}
public Set<String> getSubTypes() {
return spawnEquipment.keySet();
}
public boolean canSpawnBaseEntity() {
return spawnBaseEntity;
}
public String getNpcType() {
return npcType;
}
}
public static class NpcFactionDeclaration extends NpcDeclaration {
private NpcFactionDeclaration(Class<? extends NpcFaction> entityClass, String entityName, String itemModelVariant) {
super(entityClass, entityName, entityName, itemModelVariant);
}
@Override
public NpcFaction createEntity(World world, String subType, String factionName) {
try {
return (NpcFaction) getEntityClass().getConstructor(World.class, String.class).newInstance(world, factionName);
}
catch (Exception e) {
AncientWarfareNPC.LOG.error("Couldn't create entity:" + e.getMessage());
}
return null;
}
}
}
| 0 | 0.884203 | 1 | 0.884203 | game-dev | MEDIA | 0.994705 | game-dev | 0.813814 | 1 | 0.813814 |
generalroboticslab/CREW | 3,705 | crew-dojo/Unity/Assets/Examples/HideAndSeek_Single/Scripts/AIAgentManager.cs | using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.SideChannels;
using Unity.MLAgents.Sensors;
using Dojo;
using Unity.Netcode;
using Unity.Netcode.Components;
namespace Examples.HideAndSeek_Single
{
public class AIAgentManager : MonoBehaviour
{
[SerializeField]
private MapManager _map;
[SerializeField]
private GameObject _agentPrefab;
[SerializeField]
private Camera _aiAgentCamera;
private DojoConnection _connection;
private GameManager _gameManager;
private EventChannel _eventChannel;
private WrittenFeedbackChannel _writtenFeedbackChannel;
private Vector3 spawnpos;
[HideInInspector]
public AIAgent agent;
private void Awake()
{
_connection = FindObjectOfType<DojoConnection>();
_gameManager = FindObjectOfType<GameManager>();
var cameraSensorComponent = _agentPrefab.GetComponent<CameraSensorComponent>();
// _aiAgentCamera.enabled = true;
var cams = _agentPrefab.transform.Find("AccCam_Sensor").GetComponent<AccumuCamera>().GetComponent<Camera>();
cameraSensorComponent.Camera = cams;
// cameraSensorComponent.Camera = _aiAgentCamera; // fully observable
}
public void SpawnAgent()
{
if (!_connection.IsServer)
throw new NotServerException("You must spawn agents on the server for server ownership");
_connection.RegisterAIPlayers(new List<string> { "Seeker-0" });
var netObj = Instantiate(_agentPrefab).GetComponent<NetworkObject>();
agent = netObj.GetComponentInChildren<AIAgent>();
agent.AgentID = 0;
ResetAgent();
netObj.Spawn();
Initialize();
}
private void Initialize()
{
if (Academy.IsInitialized)
{
// register MLAgent environment
_eventChannel = new(_connection);
_writtenFeedbackChannel = new(_connection);
if (_eventChannel.IsInitialized)
SideChannelManager.RegisterSideChannel(_eventChannel);
if (_writtenFeedbackChannel.IsInitialized)
SideChannelManager.RegisterSideChannel(_writtenFeedbackChannel);
Academy.Instance.OnEnvironmentReset += _gameManager.ResetGame;
}
}
public void ResetAgent()
{
if (_connection.IsServer)
{
var spawnPoint = _map.FindSpawnPointForPlayer();
var success = agent.GetComponentInChildren<UnityEngine.AI.NavMeshAgent>().Warp(spawnPoint.center);
agent.GetComponentInChildren<Rigidbody>().velocity = Vector3.zero;
agent.GetComponentInChildren<Rigidbody>().angularVelocity = Vector3.zero;
agent.StartRequestingDecisions();
}
agent.GetComponentInChildren<PlayerController>().CamAcc.ClearAccumulation();
agent.GetComponentInChildren<PlayerController>().CamAccSens.ClearAccumulation();
agent.GetComponentInChildren<PlayerController>().clear_cam_flag.Value = true;
}
private void OnDestroy()
{
if (Academy.IsInitialized)
{
if (_eventChannel.IsInitialized)
SideChannelManager.UnregisterSideChannel(_eventChannel);
if (_writtenFeedbackChannel.IsInitialized)
SideChannelManager.UnregisterSideChannel(_writtenFeedbackChannel);
}
}
}
}
| 0 | 0.936416 | 1 | 0.936416 | game-dev | MEDIA | 0.968451 | game-dev | 0.911846 | 1 | 0.911846 |
rudzen/ChessLib | 5,959 | src/chess-lib/Rudzoft.ChessLib/Hash/Zobrist.cs | /*
ChessLib, a chess data structure library
MIT License
Copyright (c) 2017-2023 Rudy Alex Kohn
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.
*/
using System.Runtime.CompilerServices;
using Rudzoft.ChessLib.Types;
using File = Rudzoft.ChessLib.Types.File;
namespace Rudzoft.ChessLib.Hash;
/// <summary>
/// Class responsible for keeping random values for use with Zobrist hashing.
/// The zobrist key for which this class helps generate, is a "unique" representation of
/// a complete chess board, including its status.
///
/// Collisions:
/// Key collisions or type-1 errors are inherent in using Zobrist keys with far less bits than required to encode all reachable chess positions.
/// This representation is using a 64 bit key, thus it could be expected to get a collision after about 2 ^ 32 or 4 billion positions.
///
/// Collision information from
/// https://chessprogramming.wikispaces.com/Zobrist+Hashing
/// </summary>
public sealed class Zobrist : IZobrist
{
/// <summary>
/// Represents the piece index (as in EPieces), with each a square of the board value to match.
/// </summary>
private readonly HashKey[][] _zobristPst;
/// <summary>
/// Represents the castleling rights.
/// </summary>
private readonly HashKey[] _zobristCastling;
/// <summary>
/// En-Passant is only required to have 8 entries, one for each possible file where the En-Passant square can occur.
/// </summary>
private readonly HashKey[] _zobristEpFile;
/// <summary>
/// This is used if the side to move is black, if the side is white, no hashing will occur.
/// </summary>
private readonly HashKey _zobristSide;
/// <summary>
/// To use as base for pawn hash table
/// </summary>
public HashKey ZobristNoPawn { get; }
public Zobrist(IRKiss rKiss)
{
_zobristPst = new HashKey[Square.Count][];
foreach (var sq in Square.All)
{
_zobristPst[sq] = new HashKey[Piece.Count];
foreach (var pc in Piece.All.AsSpan())
_zobristPst[sq][pc] = rKiss.Rand();
}
_zobristCastling = new HashKey[CastleRight.Count];
for (var cr = CastleRights.None; cr <= CastleRights.Any; cr++)
{
var v = cr.AsInt();
_zobristCastling[v] = HashKey.Empty;
var bb = BitBoard.Create((uint)v);
while (bb)
{
var key = _zobristCastling[1UL << BitBoards.PopLsb(ref bb)];
key = !key.IsEmpty ? key : rKiss.Rand();
_zobristCastling[v] ^= key.Key;
}
}
_zobristEpFile = new HashKey[File.Count];
for (var i = 0; i < _zobristEpFile.Length; i++)
_zobristEpFile[i] = rKiss.Rand();
_zobristSide = rKiss.Rand();
ZobristNoPawn = rKiss.Rand();
}
public HashKey ComputeMaterialKey(IPosition pos)
{
var key = HashKey.Empty;
foreach (var pc in Piece.All.AsSpan())
for (var count = 0; count < pos.Board.PieceCount(pc); count++)
key ^= Psq(count, pc);
return key;
}
public HashKey ComputePawnKey(IPosition pos)
{
var key = ZobristNoPawn;
var pawns = pos.Pieces(Piece.WhitePawn);
while (pawns)
key ^= Psq(BitBoards.PopLsb(ref pawns), Piece.WhitePawn);
pawns = pos.Pieces(Piece.BlackPawn);
while (pawns)
key ^= Psq(BitBoards.PopLsb(ref pawns), Piece.BlackPawn);
return key;
}
public HashKey ComputePositionKey(IPosition pos)
{
var key = HashKey.Empty;
foreach (var pc in Piece.All.AsSpan())
{
var bb = pos.Pieces(pc);
while (bb)
key ^= Psq(BitBoards.PopLsb(ref bb), pc);
}
if (pos.SideToMove.IsWhite)
key ^= _zobristSide;
key ^= Castle(pos.State.CastleRights.Rights);
key ^= EnPassant(pos.EnPassantSquare.File);
return key;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref HashKey Psq(Square square, Piece pc) => ref _zobristPst[square][pc];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref HashKey Psq(int pieceCount, Piece pc) => ref _zobristPst[pieceCount][pc];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref HashKey Castle(CastleRights index) => ref _zobristCastling[index.AsInt()];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref HashKey Castle(CastleRight index) => ref Castle(index.Rights);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HashKey Side() => _zobristSide;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref HashKey EnPassant(File f) => ref _zobristEpFile[f];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HashKey EnPassant(Square sq)
{
return sq == Square.None ? HashKey.Empty : EnPassant(sq.File);
}
} | 0 | 0.972906 | 1 | 0.972906 | game-dev | MEDIA | 0.844843 | game-dev | 0.788132 | 1 | 0.788132 |
emileb/OpenGames | 56,970 | opengames/src/main/jni/OpenJK/codemp/client/FxPrimitives.cpp | #include "client.h"
#include "cl_cgameapi.h"
#include "FxScheduler.h"
extern int drawnFx;
//--------------------------
//
// Base Effect Class
//
//--------------------------
CEffect::CEffect(void) :
mFlags(0),
mMatImpactFX(MATIMPACTFX_NONE),
mMatImpactParm(-1),
mSoundRadius(-1),
mSoundVolume(-1)
{
memset( &mRefEnt, 0, sizeof( mRefEnt ));
}
//--------------------------
//
// Derived Particle Class
//
//--------------------------
//----------------------------
void CParticle::Init(void)
{
mRefEnt.radius = 0.0f;
if (mFlags & FX_PLAYER_VIEW)
{
mOrigin1[0] = irand(0, 639);
mOrigin1[1] = irand(0, 479);
}
}
//----------------------------
void CParticle::Die(void)
{
if ( mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT) )
{
vec3_t norm;
// Man, this just seems so, like, uncool and stuff...
VectorSet( norm, flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f));
VectorNormalize( norm );
theFxScheduler.PlayEffect( mDeathFxID, mOrigin1, norm );
}
}
//----------------------------
bool CParticle::Cull(void)
{
vec3_t dir;
if (mFlags & FX_PLAYER_VIEW)
{
// this will be drawn as a 2D effect so don't cull it
return false;
}
// Get the direction to the view
VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0) // cg.cosHalfFOV * (len - mRadius) )
{
return true;
}
// don't cull if this is hacked to show up close to the inview wpn
if (mFlags & FX_DEPTH_HACK)
{
return false;
}
// Can't be too close
float len = VectorLengthSquared( dir );
if ( len < fx_nearCull->value )
{
return true;
}
return false;
}
//----------------------------
void CParticle::Draw(void)
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
if (mFlags & FX_PLAYER_VIEW)
{
vec4_t color;
color[0] = mRefEnt.shaderRGBA[0] / 255.0;
color[1] = mRefEnt.shaderRGBA[1] / 255.0;
color[2] = mRefEnt.shaderRGBA[2] / 255.0;
color[3] = mRefEnt.shaderRGBA[3] / 255.0;
// add this 2D effect to the proper list. it will get drawn after the trap->RenderScene call
theFxScheduler.Add2DEffect(mOrigin1[0], mOrigin1[1], mRefEnt.radius, mRefEnt.radius, color, mRefEnt.customShader);
}
else
{
// Add our refEntity to the scene
VectorCopy( mOrigin1, mRefEnt.origin );
theFxHelper.AddFxToScene(&mRefEnt);
}
drawnFx++;
}
//----------------------------
// Update
//----------------------------
bool CParticle::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
vec3_t org;
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax))
{ //could not get bolt
return false;
}
vec3_t realVel, realAccel;
VectorMA( org, mOrgOffset[0], ax[0], org );
VectorMA( org, mOrgOffset[1], ax[1], org );
VectorMA( org, mOrgOffset[2], ax[2], org );
const float time = (theFxHelper.mTime - mTimeStart) * 0.001f;
// calc the real velocity and accel vectors
VectorScale( ax[0], mVel[0], realVel );
VectorMA( realVel, mVel[1], ax[1], realVel );
VectorMA( realVel, mVel[2], ax[2], realVel );
//realVel[2] += 0.5f * mGravity * time;
VectorScale( ax[0], mAccel[0], realAccel );
VectorMA( realAccel, mAccel[1], ax[1], realAccel );
VectorMA( realAccel, mAccel[2], ax[2], realAccel );
// Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise
VectorMA( realVel, time, realAccel, realVel );
// Now move us to where we should be at the given time
VectorMA( org, time, realVel, mOrigin1 );
}
else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull() )
{
// Only update these if the thing is visible.
UpdateSize();
UpdateRGB();
UpdateAlpha();
UpdateRotation();
Draw();
}
return true;
}
//----------------------------
// Update Origin
//----------------------------
bool CParticle::UpdateOrigin(void)
{
vec3_t new_origin;
VectorMA( mVel, theFxHelper.mRealTime, mAccel, mVel );
// Predict the new position
new_origin[0] = mOrigin1[0] + (theFxHelper.mRealTime * mVel[0]);// + (theFxHelper.mHalfRealTimeSq * mVel[0]);
new_origin[1] = mOrigin1[1] + (theFxHelper.mRealTime * mVel[1]);// + (theFxHelper.mHalfRealTimeSq * mVel[1]);
new_origin[2] = mOrigin1[2] + (theFxHelper.mRealTime * mVel[2]);// + (theFxHelper.mHalfRealTimeSq * mVel[2]);
// Only perform physics if this object is tagged to do so
if ( (mFlags & FX_APPLY_PHYSICS) && !(mFlags & FX_PLAYER_VIEW) )
{
trace_t trace;
float dot;
if ( mFlags & FX_USE_BBOX )
{
if (mFlags & FX_GHOUL2_TRACE)
{
theFxHelper.G2Trace( trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID );
}
else
{
theFxHelper.Trace( trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID );
}
}
else
{
if (mFlags & FX_GHOUL2_TRACE)
{
theFxHelper.G2Trace( trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_PLAYERSOLID );
}
else
{
theFxHelper.Trace( trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_SOLID );
}
}
// Hit something
if (trace.startsolid || trace.allsolid)
{
VectorClear( mVel );
VectorClear( mAccel );
if ((mFlags & FX_GHOUL2_TRACE) && (mFlags & FX_IMPACT_RUNS_FX))
{
static vec3_t bsNormal = {0, 1, 0};
theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, bsNormal );
}
mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX);
return true;
}
else if ( trace.fraction < 1.0f )//&& !trace.startsolid && !trace.allsolid )
{
if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT ))
{
theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal );
}
// may need to interact with the material type we hit
theFxScheduler.MaterialImpact(&trace, (CEffect*)this);
if ( mFlags & FX_KILL_ON_IMPACT )
{
// time to die
return false;
}
VectorMA( mVel, theFxHelper.mRealTime * trace.fraction, mAccel, mVel );
dot = DotProduct( mVel, trace.plane.normal );
VectorMA( mVel, -2.0f * dot, trace.plane.normal, mVel );
VectorScale( mVel, mElasticity, mVel );
mElasticity *= 0.5f;
// If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid
// doing expensive operations when they aren't needed
//if ( trace.plane.normal[2] > 0.33f && mVel[2] < 10.0f )
if (VectorLengthSquared(mVel) < 100.0f)
{
VectorClear( mVel );
VectorClear( mAccel );
mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX);
}
// Set the origin to the exact impact point
VectorMA( trace.endpos, 1.0f, trace.plane.normal, mOrigin1 );
return true;
}
}
// No physics were done to this object, move it
VectorCopy( new_origin, mOrigin1 );
if (mFlags & FX_PLAYER_VIEW)
{
if (mOrigin1[0] < 0 || mOrigin1[0] > 639 || mOrigin1[1] < 0 || mOrigin1[1] > 479)
{
return false;
}
}
return true;
}
//----------------------------
// Update Size
//----------------------------
void CParticle::UpdateSize(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( (mFlags & FX_SIZE_LINEAR) )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR )
{
if ( theFxHelper.mTime > mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm);
}
if ( mFlags & FX_SIZE_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSizeParm );
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP )
{
if ( theFxHelper.mTime < mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( (mFlags & FX_SIZE_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_SIZE_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
mRefEnt.radius = (mSizeStart * perc1) + (mSizeEnd * (1.0f - perc1));
}
void ClampRGB( const vec3_t in, byte *out )
{
int r;
for ( int i=0; i<3; i++ ) {
r = Q_ftol(in[i] * 255.0f);
if ( r < 0 )
r = 0;
else if ( r > 255 )
r = 255;
out[i] = (byte)r;
}
}
//----------------------------
// Update RGB
//----------------------------
void CParticle::UpdateRGB(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
vec3_t res;
if ( (mFlags & FX_RGB_LINEAR) )
{
// calculate element biasing
perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) / (float)( mTimeEnd - mTimeStart );
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR )
{
if ( theFxHelper.mTime > mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) / (float)( mTimeEnd - mRGBParm );
}
if ( (mFlags & FX_RGB_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf(( theFxHelper.mTime - mTimeStart ) * mRGBParm );
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP )
{
if ( theFxHelper.mTime < mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if (( mFlags & FX_RGB_LINEAR ))
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_RGB_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
// Now get the correct color
VectorScale( mRGBStart, perc1, res );
VectorMA( res, 1.0f - perc1, mRGBEnd, res );
ClampRGB( res, (byte*)(&mRefEnt.shaderRGBA) );
}
//----------------------------
// Update Alpha
//----------------------------
void CParticle::UpdateAlpha(void)
{
int alpha;
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( (mFlags & FX_ALPHA_LINEAR) )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_NONLINEAR )
{
if ( theFxHelper.mTime > mAlphaParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) / (float)(mTimeEnd - mAlphaParm);
}
if (( mFlags & FX_ALPHA_LINEAR ))
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mAlphaParm );
}
else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_CLAMP )
{
if ( theFxHelper.mTime < mAlphaParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mAlphaParm - theFxHelper.mTime) / (float)(mAlphaParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if (( mFlags & FX_ALPHA_LINEAR ))
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
perc1 = (mAlphaStart * perc1) + (mAlphaEnd * (1.0f - perc1));
// We should be in the right range, but clamp to ensure
perc1 = Com_Clamp(0.0f, 1.0f, perc1);
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_ALPHA_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
alpha = Com_Clamp(0, 255, perc1 * 255.0f);
if ( mFlags & FX_USE_ALPHA )
{
// should use this when using art that has an alpha channel
mRefEnt.shaderRGBA[3] = (byte)alpha;
}
else
{
// Modulate the rgb fields by the alpha value to do the fade, works fine for additive blending
mRefEnt.shaderRGBA[0] = ((int)mRefEnt.shaderRGBA[0] * alpha) >> 8;
mRefEnt.shaderRGBA[1] = ((int)mRefEnt.shaderRGBA[1] * alpha) >> 8;
mRefEnt.shaderRGBA[2] = ((int)mRefEnt.shaderRGBA[2] * alpha) >> 8;
}
}
//--------------------------
void CParticle::UpdateRotation(void)
{
mRefEnt.rotation += theFxHelper.mFrameTime * 0.01f * mRotationDelta;
mRotationDelta *= ( 1.0f - ( theFxHelper.mFrameTime * 0.0007f )); // decay rotationDelta
}
//--------------------------------
//
// Derived Oriented Particle Class
//
//--------------------------------
COrientedParticle::COrientedParticle(void)
{
mRefEnt.reType = RT_ORIENTED_QUAD;
}
//----------------------------
bool COrientedParticle::Cull(void)
{
vec3_t dir;
// float len;
// Get the direction to the view
VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0 )
{
return true;
}
// len = VectorLengthSquared( dir );
// don't cull stuff that's associated with inview wpns
if ( mFlags & FX_DEPTH_HACK )
{
return false;
}
// Can't be too close
// if ( len < fx_nearCull->value * fx_nearCull->value)
// {
// return true;
// }
return false;
}
//----------------------------
void COrientedParticle::Draw(void)
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set
mRefEnt.renderfx |= RF_DEPTHHACK;
}
// Add our refEntity to the scene
VectorCopy( mOrigin1, mRefEnt.origin );
if ( !(mFlags&FX_RELATIVE) )
{
VectorCopy( mNormal, mRefEnt.axis[0] );
MakeNormalVectors( mRefEnt.axis[0], mRefEnt.axis[1], mRefEnt.axis[2] );
}
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
}
//----------------------------
// Update
//----------------------------
bool COrientedParticle::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
vec3_t org;
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax))
{ //could not get bolt
return false;
}
vec3_t realVel, realAccel;
VectorMA( org, mOrgOffset[0], ax[0], org );
VectorMA( org, mOrgOffset[1], ax[1], org );
VectorMA( org, mOrgOffset[2], ax[2], org );
const float time = (theFxHelper.mTime - mTimeStart) * 0.001f;
// calc the real velocity and accel vectors
VectorScale( ax[0], mVel[0], realVel );
VectorMA( realVel, mVel[1], ax[1], realVel );
VectorMA( realVel, mVel[2], ax[2], realVel );
// realVel[2] += 0.5f * mGravity * time;
VectorScale( ax[0], mAccel[0], realAccel );
VectorMA( realAccel, mAccel[1], ax[1], realAccel );
VectorMA( realAccel, mAccel[2], ax[2], realAccel );
// Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise
VectorMA( realVel, time, realAccel, realVel );
// Now move us to where we should be at the given time
VectorMA( org, time, realVel, mOrigin1 );
//use the normalOffset and add that to the actual normal of the bolt
//NOTE: not tested!!!
VectorCopy( ax[0], mRefEnt.axis[0] );
VectorCopy( ax[1], mRefEnt.axis[1] );
VectorCopy( ax[2], mRefEnt.axis[2] );
//vec3_t offsetAngles;
//VectorSet( offsetAngles, 0, 90, 90 );
matrix3_t offsetAxis;
//NOTE: mNormal is actually PITCH YAW and ROLL offsets
AnglesToAxis( mNormal, offsetAxis );
MatrixMultiply( offsetAxis, ax, mRefEnt.axis );
}
else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull() )
{ // Only update these if the thing is visible.
UpdateSize();
UpdateRGB();
UpdateAlpha();
UpdateRotation();
Draw();
}
return true;
}
//----------------------------
//
// Derived Line Class
//
//----------------------------
CLine::CLine(void)
{
mRefEnt.reType = RT_LINE;
}
//----------------------------
void CLine::Draw(void)
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
VectorCopy( mOrigin2, mRefEnt.oldorigin );
theFxHelper.AddFxToScene(&mRefEnt);
drawnFx++;
}
//----------------------------
bool CLine::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax))
{ //could not get bolt
return false;
}
VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point
VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 );
VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 );
VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 );
}
if ( !Cull())
{
// Only update these if the thing is visible.
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
//
// Derived Electricity Class
//
//----------------------------
CElectricity::CElectricity(void)
{
mRefEnt.reType = RT_ELECTRICITY;
}
//----------------------------
void CElectricity::Initialize(void)
{
mRefEnt.frame = flrand(0.0f, 1.0f) * 1265536.0f;
mRefEnt.axis[0][2] = theFxHelper.mTime + (mTimeEnd - mTimeStart); // endtime
if ( mFlags & FX_DEPTH_HACK )
{
mRefEnt.renderfx |= RF_DEPTHHACK;
}
if ( mFlags & FX_BRANCH )
{
mRefEnt.renderfx |= RF_FORKED;
}
if ( mFlags & FX_TAPER )
{
mRefEnt.renderfx |= RF_TAPERED;
}
if ( mFlags & FX_GROW )
{
mRefEnt.renderfx |= RF_GROW;
}
}
//----------------------------
void CElectricity::Draw(void)
{
VectorCopy( mOrigin1, mRefEnt.origin );
VectorCopy( mOrigin2, mRefEnt.oldorigin );
mRefEnt.axis[0][0] = mChaos;
mRefEnt.axis[0][1] = mTimeEnd - mTimeStart;
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
}
//----------------------------
bool CElectricity::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax))
{ //could not get bolt
return false;
}
VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point
VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 );
VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 );
VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 );
}
if ( !Cull())
{
// Only update these if the thing is visible.
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
//
// Derived Tail Class
//
//----------------------------
CTail::CTail(void)
{
mRefEnt.reType = RT_LINE;
}
//----------------------------
void CTail::Draw(void)
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
theFxHelper.AddFxToScene(&mRefEnt);
drawnFx++;
}
//----------------------------
bool CTail::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
vec3_t org;
matrix3_t ax;
if (mModelNum>=0 && mBoltNum>=0) //bolt style
{
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax))
{ //could not get bolt
return false;
}
}
vec3_t realVel, realAccel;
VectorMA( org, mOrgOffset[0], ax[0], org );
VectorMA( org, mOrgOffset[1], ax[1], org );
VectorMA( org, mOrgOffset[2], ax[2], org );
// calc the real velocity and accel vectors
// FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra work
VectorScale( ax[0], mVel[0], realVel );
VectorMA( realVel, mVel[1], ax[1], realVel );
VectorMA( realVel, mVel[2], ax[2], realVel );
VectorScale( ax[0], mAccel[0], realAccel );
VectorMA( realAccel, mAccel[1], ax[1], realAccel );
VectorMA( realAccel, mAccel[2], ax[2], realAccel );
const float time = (theFxHelper.mTime - mTimeStart) * 0.001f;
// Get our real velocity at the current time, taking into account the effects of acceleration. NOTE: not sure if this is even 100% correct math-wise
VectorMA( realVel, time, realAccel, realVel );
// Now move us to where we should be at the given time
VectorMA( org, time, realVel, mOrigin1 );
// Just calc an old point some time in the past, doesn't really matter when
VectorMA( org, (time - 0.003f), realVel, mOldOrigin );
}
#ifdef _DEBUG
else if ( !fx_freeze->integer )
#else
else
#endif
{
VectorCopy( mOrigin1, mOldOrigin );
}
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull() )
{
// Only update these if the thing is visible.
UpdateSize();
UpdateLength();
UpdateRGB();
UpdateAlpha();
CalcNewEndpoint();
Draw();
}
return true;
}
//----------------------------
void CTail::UpdateLength(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_LENGTH_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_NONLINEAR )
{
if ( theFxHelper.mTime > mLengthParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) / (float)(mTimeEnd - mLengthParm);
}
if ( mFlags & FX_LENGTH_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mLengthParm );
}
else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_CLAMP )
{
if ( theFxHelper.mTime < mLengthParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mLengthParm - theFxHelper.mTime) / (float)(mLengthParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_LENGTH_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_LENGTH_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
mLength = (mLengthStart * perc1) + (mLengthEnd * (1.0f - perc1));
}
//----------------------------
void CTail::CalcNewEndpoint(void)
{
vec3_t temp;
// FIXME: Hmmm, this looks dumb when physics are on and a bounce happens
VectorSubtract( mOldOrigin, mOrigin1, temp );
// I wish we didn't have to do a VectorNormalize every frame.....
VectorNormalize( temp );
VectorMA( mOrigin1, mLength, temp, mRefEnt.oldorigin );
}
//----------------------------
//
// Derived Cylinder Class
//
//----------------------------
CCylinder::CCylinder(void)
{
mRefEnt.reType = RT_CYLINDER;
mTraceEnd = qfalse;
}
bool CCylinder::Cull(void)
{
if (mTraceEnd)
{ //eh, don't cull variable-length cylinders
return false;
}
return CTail::Cull();
}
void CCylinder::UpdateLength(void)
{
if (mTraceEnd)
{
vec3_t temp;
trace_t tr;
VectorMA( mOrigin1, FX_MAX_TRACE_DIST, mRefEnt.axis[0], temp );
theFxHelper.Trace( tr, mOrigin1, NULL, NULL, temp, -1, MASK_SOLID );
VectorSubtract( tr.endpos, mOrigin1, temp );
mLength = VectorLength(temp);
}
else
{
CTail::UpdateLength();
}
}
//----------------------------
void CCylinder::Draw(void)
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
VectorMA( mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin );
theFxHelper.AddFxToScene(&mRefEnt);
drawnFx++;
}
//----------------------------
// Update Size2
//----------------------------
void CCylinder::UpdateSize2(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_SIZE2_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_NONLINEAR )
{
if ( theFxHelper.mTime > mSize2Parm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) / (float)(mTimeEnd - mSize2Parm);
}
if ( (mFlags & FX_SIZE2_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSize2Parm );
}
else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_CLAMP )
{
if ( theFxHelper.mTime < mSize2Parm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSize2Parm - theFxHelper.mTime) / (float)(mSize2Parm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_SIZE2_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_SIZE2_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
mRefEnt.rotation = (mSize2Start * perc1) + (mSize2End * (1.0f - perc1));
}
//----------------------------
bool CCylinder::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax))
{ //could not get bolt
return false;
}
VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point
VectorCopy( ax[0], mRefEnt.axis[0] );
//FIXME: should mNormal be a modifier on the forward axis?
/*
VectorMA( mOrigin1, mNormal[0], ax[0], mOrigin2 );
VectorMA( mOrigin2, mNormal[1], ax[1], mOrigin2 );
VectorMA( mOrigin2, mNormal[2], ax[2], mOrigin2 );
*/
}
if ( !Cull() )
{
// Only update these if the thing is visible.
UpdateSize();
UpdateSize2();
UpdateLength();
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
//
// Derived Emitter Class
//
//----------------------------
CEmitter::CEmitter(void)
{
// There may or may not be a model, but if there isn't one,
// we just won't bother adding the refEnt in our Draw func
mRefEnt.reType = RT_MODEL;
}
//----------------------------
CEmitter::~CEmitter(void)
{
}
//----------------------------
// Draw
//----------------------------
void CEmitter::Draw(void)
{
// Emitters don't draw themselves, but they may need to add an attached model
if ( mFlags & FX_ATTACHED_MODEL )
{
mRefEnt.nonNormalizedAxes = qtrue;
VectorCopy( mOrigin1, mRefEnt.origin );
VectorScale( mRefEnt.axis[0], mRefEnt.radius, mRefEnt.axis[0] );
VectorScale( mRefEnt.axis[1], mRefEnt.radius, mRefEnt.axis[1] );
VectorScale( mRefEnt.axis[2], mRefEnt.radius, mRefEnt.axis[2] );
theFxHelper.AddFxToScene((miniRefEntity_t*)0);// I hate having to do this, but this needs to get added as a regular refEntity
theFxHelper.AddFxToScene(&mRefEnt);
}
// If we are emitting effects, we had better be careful because just calling it every cgame frame could
// either choke up the effects system on a fast machine, or look really nasty on a low end one.
if ( mFlags & FX_EMIT_FX )
{
vec3_t org, v;
float ftime, time2, step;
int t, dif;
#define TRAIL_RATE 12 // we "think" at about a 60hz rate
// Pick a target step distance and square it
step = mDensity + flrand(-mVariance, mVariance);
step *= step;
dif = 0;
for ( t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE )
{
dif += TRAIL_RATE;
// ?Not sure if it's better to update this before or after updating the origin
VectorMA( mOldVelocity, dif * 0.001f, mAccel, v );
// Calc the time differences
ftime = dif * 0.001f;
time2 = ftime * ftime * 0.5f;
// Predict the new position
org[0] = mOldOrigin[0] + (ftime * v[0]) + (time2 * v[0]);
org[1] = mOldOrigin[1] + (ftime * v[1]) + (time2 * v[1]);
org[2] = mOldOrigin[2] + (ftime * v[2]) + (time2 * v[2]);
// Is it time to draw an effect?
if ( DistanceSquared( org, mOldOrigin ) >= step )
{
// Pick a new target step distance and square it
step = mDensity + flrand(-mVariance, mVariance);
step *= step;
// We met the step criteria so, we should add in the effect
theFxScheduler.PlayEffect( mEmitterFxID, org, mRefEnt.axis );
VectorCopy( org, mOldOrigin );
VectorCopy( v, mOldVelocity );
dif = 0;
mOldTime = t;
}
}
}
drawnFx++;
}
//----------------------------
bool CEmitter::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
// Use this to track if we've stopped moving
VectorCopy( mOrigin1, mOldOrigin );
VectorCopy( mVel, mOldVelocity );
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
assert(0);//need this?
}
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
bool moving = false;
// If the thing is no longer moving, kill the angle delta, but don't do it too quickly or it will
// look very artificial. Don't do it too slowly or it will look like there is no friction.
if ( VectorCompare( mOldOrigin, mOrigin1 ))
{
VectorScale( mAngleDelta, 0.7f, mAngleDelta );
}
else
{
moving = true;
}
if ( mFlags & FX_PAPER_PHYSICS )
{
// do this in a more framerate independent manner
float sc = ( 20.0f / theFxHelper.mFrameTime);
// bah, evil clamping
if ( sc >= 1.0f )
{
sc = 1.0f;
}
if ( moving )
{
// scale the velocity down, basically inducing drag. Acceleration ( gravity ) should keep it pulling down, which is what we want.
VectorScale( mVel, (sc * 0.8f + 0.2f ) * 0.92f, mVel );
// add some chaotic motion based on the way we are oriented
VectorMA( mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[0], mVel );
VectorMA( mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[1], mVel );
}
// make us settle so we can lay flat
mAngles[0] *= (0.97f * (sc * 0.4f + 0.6f ));
mAngles[2] *= (0.97f * (sc * 0.4f + 0.6f ));
// decay our angle delta so we don't rotate as quickly
VectorScale( mAngleDelta, (0.96f * (sc * 0.1f + 0.9f )), mAngleDelta );
}
UpdateAngles();
UpdateSize();
Draw();
return true;
}
//----------------------------
void CEmitter::UpdateAngles(void)
{
VectorMA( mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, mAngles ); // was 0.001f, but then you really have to jack up the delta to even notice anything
AnglesToAxis( mAngles, mRefEnt.axis );
}
//--------------------------
//
// Derived Light Class
//
//--------------------------
//----------------------------
void CLight::Draw(void)
{
theFxHelper.AddLightToScene( mOrigin1, mRefEnt.radius, mRefEnt.origin[0], mRefEnt.origin[1], mRefEnt.origin[2] );
drawnFx++;
}
//----------------------------
// Update
//----------------------------
bool CLight::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2))
{ // the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
matrix3_t ax;
// Get our current position and direction
if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax))
{ //could not get bolt
return false;
}
VectorMA( mOrigin1, mOrgOffset[0], ax[0], mOrigin1 );
VectorMA( mOrigin1, mOrgOffset[1], ax[1], mOrigin1 );
VectorMA( mOrigin1, mOrgOffset[2], ax[2], mOrigin1 );
}
UpdateSize();
UpdateRGB();
Draw();
return true;
}
//----------------------------
// Update Size
//----------------------------
void CLight::UpdateSize(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_SIZE_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR )
{
if ( theFxHelper.mTime > mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm);
}
if ( (mFlags & FX_SIZE_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSizeParm );
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP )
{
if ( theFxHelper.mTime < mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_SIZE_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_SIZE_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
mRefEnt.radius = (mSizeStart * perc1) + (mSizeEnd * (1.0f - perc1));
}
//----------------------------
// Update RGB
//----------------------------
void CLight::UpdateRGB(void)
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
vec3_t res;
if ( mFlags & FX_RGB_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) / (float)( mTimeEnd - mTimeStart );
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR )
{
if ( theFxHelper.mTime > mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) / (float)( mTimeEnd - mRGBParm );
}
if ( mFlags & FX_RGB_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * cosf(( theFxHelper.mTime - mTimeStart ) * mRGBParm );
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP )
{
if ( theFxHelper.mTime < mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_RGB_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_RGB_RAND )
{
// Random simply modulates the existing value
perc1 = flrand(0.0f, perc1);
}
// Now get the correct color
VectorScale( mRGBStart, perc1, res );
VectorMA(res, ( 1.0f - perc1 ), mRGBEnd, mRefEnt.origin);
}
//--------------------------
//
// Derived Trail Class
//
//--------------------------
#define NEW_MUZZLE 0
#define NEW_TIP 1
#define OLD_TIP 2
#define OLD_MUZZLE 3
//----------------------------
void CTrail::Draw()
{
polyVert_t verts[3];
// vec3_t color;
// build the first tri out of the new muzzle...new tip...old muzzle
VectorCopy( mVerts[NEW_MUZZLE].origin, verts[0].xyz );
VectorCopy( mVerts[NEW_TIP].origin, verts[1].xyz );
VectorCopy( mVerts[OLD_MUZZLE].origin, verts[2].xyz );
// VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color );
verts[0].modulate[0] = mVerts[NEW_MUZZLE].rgb[0];
verts[0].modulate[1] = mVerts[NEW_MUZZLE].rgb[1];
verts[0].modulate[2] = mVerts[NEW_MUZZLE].rgb[2];
verts[0].modulate[3] = mVerts[NEW_MUZZLE].alpha;
// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color );
verts[1].modulate[0] = mVerts[NEW_TIP].rgb[0];
verts[1].modulate[1] = mVerts[NEW_TIP].rgb[1];
verts[1].modulate[2] = mVerts[NEW_TIP].rgb[2];
verts[1].modulate[3] = mVerts[NEW_TIP].alpha;
// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color );
verts[2].modulate[0] = mVerts[OLD_MUZZLE].rgb[0];
verts[2].modulate[1] = mVerts[OLD_MUZZLE].rgb[1];
verts[2].modulate[2] = mVerts[OLD_MUZZLE].rgb[2];
verts[2].modulate[3] = mVerts[OLD_MUZZLE].alpha;
verts[0].st[0] = mVerts[NEW_MUZZLE].curST[0];
verts[0].st[1] = mVerts[NEW_MUZZLE].curST[1];
verts[1].st[0] = mVerts[NEW_TIP].curST[0];
verts[1].st[1] = mVerts[NEW_TIP].curST[1];
verts[2].st[0] = mVerts[OLD_MUZZLE].curST[0];
verts[2].st[1] = mVerts[OLD_MUZZLE].curST[1];
// Add this tri
theFxHelper.AddPolyToScene( mShader, 3, verts );
// build the second tri out of the old muzzle...old tip...new tip
VectorCopy( mVerts[OLD_MUZZLE].origin, verts[0].xyz );
VectorCopy( mVerts[OLD_TIP].origin, verts[1].xyz );
VectorCopy( mVerts[NEW_TIP].origin, verts[2].xyz );
// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color );
verts[0].modulate[0] = mVerts[OLD_MUZZLE].rgb[0];
verts[0].modulate[1] = mVerts[OLD_MUZZLE].rgb[1];
verts[0].modulate[2] = mVerts[OLD_MUZZLE].rgb[2];
verts[0].modulate[3] = mVerts[OLD_MUZZLE].alpha;
// VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color );
verts[1].modulate[0] = mVerts[OLD_TIP].rgb[0];
verts[1].modulate[1] = mVerts[OLD_TIP].rgb[1];
verts[1].modulate[2] = mVerts[OLD_TIP].rgb[2];
verts[0].modulate[3] = mVerts[OLD_TIP].alpha;
// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color );
verts[2].modulate[0] = mVerts[NEW_TIP].rgb[0];
verts[2].modulate[1] = mVerts[NEW_TIP].rgb[1];
verts[2].modulate[2] = mVerts[NEW_TIP].rgb[2];
verts[0].modulate[3] = mVerts[NEW_TIP].alpha;
verts[0].st[0] = mVerts[OLD_MUZZLE].curST[0];
verts[0].st[1] = mVerts[OLD_MUZZLE].curST[1];
verts[1].st[0] = mVerts[OLD_TIP].curST[0];
verts[1].st[1] = mVerts[OLD_TIP].curST[1];
verts[2].st[0] = mVerts[NEW_TIP].curST[0];
verts[2].st[1] = mVerts[NEW_TIP].curST[1];
// Add this tri
theFxHelper.AddPolyToScene( mShader, 3, verts );
drawnFx++;
}
//----------------------------
// Update
//----------------------------
bool CTrail::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
float perc = (float)(mTimeEnd - theFxHelper.mTime) / (float)(mTimeEnd - mTimeStart);
for ( int t = 0; t < 4; t++ )
{
// mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc );
// if ( mVerts[t].curAlpha < 0.0f )
// {
// mVerts[t].curAlpha = 0.0f;
// }
// VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB );
// VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB );
mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * ( 1.0f - perc );
if ( mVerts[t].curST[0] > 1.0f )
{
mVerts[t].curST[0] = 1.0f;
}
mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * ( 1.0f - perc );
}
Draw();
return true;
}
//--------------------------
//
// Derived Poly Class
//
//--------------------------
//----------------------------
bool CPoly::Cull(void)
{
vec3_t dir;
// Get the direction to the view
VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0 )
{
return true;
}
float len = VectorLengthSquared( dir );
// Can't be too close
if ( len < fx_nearCull->value * fx_nearCull->value)
{
return true;
}
return false;
}
//----------------------------
void CPoly::Draw(void)
{
polyVert_t verts[MAX_CPOLY_VERTS];
for ( int i = 0; i < mCount; i++ )
{
// Add our midpoint and vert offset to get the actual vertex
VectorAdd( mOrigin1, mOrg[i], verts[i].xyz );
// Assign the same color to each vert
for ( int k=0; k<4; k++ )
verts[i].modulate[k] = mRefEnt.shaderRGBA[k];
// Copy the ST coords
Vector2Copy( mST[i], verts[i].st );
}
// Add this poly
theFxHelper.AddPolyToScene( mRefEnt.customShader, mCount, verts );
drawnFx++;
}
//----------------------------
void CPoly::CalcRotateMatrix(void)
{
float cosX, cosZ;
float sinX, sinZ;
float rad;
// rotate around Z
rad = DEG2RAD( mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f );
cosZ = cosf( rad );
sinZ = sinf( rad );
// rotate around X
rad = DEG2RAD( mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f );
cosX = cosf( rad );
sinX = sinf( rad );
/*Pitch - aroundx Yaw - around z
1 0 0 c -s 0
0 c -s s c 0
0 s c 0 0 1
*/
mRot[0][0] = cosZ;
mRot[1][0] = -sinZ;
mRot[2][0] = 0;
mRot[0][1] = cosX * sinZ;
mRot[1][1] = cosX * cosZ;
mRot[2][1] = -sinX;
mRot[0][2] = sinX * sinZ;
mRot[1][2] = sinX * cosZ;
mRot[2][2] = cosX;
/*
// ROLL is not supported unless anyone complains, if it needs to be added, use this format
Roll
c 0 s
0 1 0
-s 0 c
*/
mLastFrameTime = theFxHelper.mFrameTime;
}
//--------------------------------
void CPoly::Rotate(void)
{
vec3_t temp[MAX_CPOLY_VERTS];
float dif = fabs( (float)(mLastFrameTime - theFxHelper.mFrameTime) );
if ( dif > 0.1f * mLastFrameTime )
{
CalcRotateMatrix();
}
// Multiply our rotation matrix by each of the offset verts to get their new position
for ( int i = 0; i < mCount; i++ )
{
VectorRotate( mOrg[i], mRot, temp[i] );
VectorCopy( temp[i], mOrg[i] );
}
}
//----------------------------
// Update
//----------------------------
bool CPoly::Update(void)
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
// If our timestamp hasn't exired yet, we won't even consider doing any kind of motion
if ( theFxHelper.mTime > mTimeStamp )
{
vec3_t mOldOrigin;
VectorCopy( mOrigin1, mOldOrigin );
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
// Only rotate whilst moving
if ( !VectorCompare( mOldOrigin, mOrigin1 ))
{
Rotate();
}
}
if ( !Cull())
{
// Only update these if the thing is visible.
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
void CPoly::PolyInit(void)
{
if ( mCount < 3 )
{
return;
}
int i;
vec3_t org = {0.0f, 0.0f ,0.0f};
// Find our midpoint
for ( i = 0; i < mCount; i++ )
{
VectorAdd( org, mOrg[i], org );
}
VectorScale( org, (float)(1.0f / mCount), org );
// now store our midpoint for physics purposes
VectorCopy( org, mOrigin1 );
// Now we process the passed in points and make it so that they aren't actually the point...
// rather, they are the offset from mOrigin1.
for ( i = 0; i < mCount; i++ )
{
VectorSubtract( mOrg[i], mOrigin1, mOrg[i] );
}
CalcRotateMatrix();
}
/*
-------------------------
CBezier
Bezier curve line
-------------------------
*/
bool CBezier::Cull( void )
{
vec3_t dir;
VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir );
//Check if it's in front of the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 )
{
return false; //don't cull
}
VectorSubtract( mOrigin2, theFxHelper.refdef->vieworg, dir );
//Check if it's in front of the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 )
{
return false;
}
VectorSubtract( mControl1, theFxHelper.refdef->vieworg, dir );
//Check if it's in front of the viewer
if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 )
{
return false;
}
return true; //all points behind viewer
}
//----------------------------
bool CBezier::Update( void )
{
float ftime, time2;
ftime = theFxHelper.mFrameTime * 0.001f;
time2 = ftime * ftime * 0.5f;
mControl1[0] = mControl1[0] + (ftime * mControl1Vel[0]) + (time2 * mControl1Vel[0]);
mControl2[0] = mControl2[0] + (ftime * mControl2Vel[0]) + (time2 * mControl2Vel[0]);
mControl1[1] = mControl1[1] + (ftime * mControl1Vel[1]) + (time2 * mControl1Vel[1]);
mControl2[1] = mControl2[1] + (ftime * mControl2Vel[1]) + (time2 * mControl2Vel[1]);
mControl1[2] = mControl1[2] + (ftime * mControl1Vel[2]) + (time2 * mControl1Vel[2]);
mControl2[2] = mControl2[2] + (ftime * mControl2Vel[2]) + (time2 * mControl2Vel[2]);
if ( Cull() == false )
{
// Only update these if the thing is visible.
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
inline void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texcoord2, float segPercent, float lastSegPercent )
{
vec3_t lineDir, cross, viewDir;
static vec3_t lastEnd[2];
polyVert_t verts[4];
float scaleBottom = 0.0f, scaleTop = 0.0f;
VectorSubtract( end, start, lineDir );
VectorSubtract( end, theFxHelper.refdef->vieworg, viewDir );
CrossProduct( lineDir, viewDir, cross );
VectorNormalize( cross );
// scaleBottom is the width of the bottom edge of the quad, scaleTop is the width of the top edge
scaleBottom = (mSizeStart + ((mSizeEnd - mSizeStart) * lastSegPercent)) * 0.5f;
scaleTop = (mSizeStart + ((mSizeEnd - mSizeStart) * segPercent)) * 0.5f;
//Construct the oriented quad
if ( mInit )
{
VectorCopy( lastEnd[0], verts[0].xyz );
VectorCopy( lastEnd[1], verts[1].xyz );
}
else
{
VectorMA( start, -scaleBottom, cross, verts[0].xyz );
VectorMA( start, scaleBottom, cross, verts[1].xyz );
}
verts[0].st[0] = 0.0f;
verts[0].st[1] = texcoord1;
verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 );
verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 );
verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 );
verts[0].modulate[3] = mRefEnt.shaderRGBA[3];
verts[1].st[0] = 1.0f;
verts[1].st[1] = texcoord1;
verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 );
verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 );
verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 );
verts[1].modulate[3] = mRefEnt.shaderRGBA[3];
if ( texcoord1 == 0.0f )
{
for ( int k=0; k<4; k++ ) {
verts[0].modulate[k] = verts[1].modulate[k] = 0;
}
}
VectorMA( end, scaleTop, cross, verts[2].xyz );
verts[2].st[0] = 1.0f;
verts[2].st[1] = texcoord2;
verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 );
verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 );
verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 );
verts[2].modulate[3] = mRefEnt.shaderRGBA[3];
VectorMA( end, -scaleTop, cross, verts[3].xyz );
verts[3].st[0] = 0.0f;
verts[3].st[1] = texcoord2;
verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 );
verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 );
verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 );
verts[3].modulate[3] = mRefEnt.shaderRGBA[3];
theFxHelper.AddPolyToScene( mRefEnt.customShader, 4, verts );
VectorCopy( verts[2].xyz, lastEnd[1] );
VectorCopy( verts[3].xyz, lastEnd[0] );
mInit = true;
}
const float BEZIER_RESOLUTION = 16.0f;
//----------------------------
void CBezier::Draw( void )
{
vec3_t pos, old_pos;
float mu, mum1;
float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2;
int i = 0;
VectorCopy( mOrigin1, old_pos );
mInit = false; //Signify a new batch for vert gluing
float mum13, mu3, group1, group2;
tc1 = 0.0f;
for ( mu = incr; mu <= 1.0f; mu += incr)
{
//Four point curve
mum1 = 1 - mu;
mum13 = mum1 * mum1 * mum1;
mu3 = mu * mu * mu;
group1 = 3 * mu * mum1 * mum1;
group2 = 3 * mu * mu *mum1;
for ( i = 0; i < 3; i++ )
{
pos[i] = mum13 * mOrigin1[i] + group1 * mControl1[i] + group2 * mControl2[i] + mu3 * mOrigin2[i];
}
tc2 = mu * tex;
//Draw it
DrawSegment( old_pos, pos, tc1, tc2, mu, mu - incr );
VectorCopy( pos, old_pos );
tc1 = tc2;
}
drawnFx++;
}
/*
-------------------------
CFlash
Full screen flash
-------------------------
*/
//----------------------------
bool CFlash::Update( void )
{
if ( UpdateOrigin() == false )
{
// we are marked for death
return false;
}
UpdateSize();
mRefEnt.radius *= mRadiusModifier;
UpdateRGB();
UpdateAlpha();
Draw();
return true;
}
bool FX_WorldToScreen(vec3_t worldCoord, float *x, float *y)
{
int xcenter, ycenter;
vec3_t local, transformed;
vec3_t vfwd, vright, vup;
//NOTE: did it this way because most draw functions expect virtual 640x480 coords
// and adjust them for current resolution
xcenter = 640 / 2;//gives screen coords in virtual 640x480, to be adjusted when drawn
ycenter = 480 / 2;//gives screen coords in virtual 640x480, to be adjusted when drawn
VectorSubtract (worldCoord, theFxHelper.refdef->vieworg, local);
AngleVectors (theFxHelper.refdef->viewangles, vfwd, vright, vup);
transformed[0] = DotProduct(local,vright);
transformed[1] = DotProduct(local,vup);
transformed[2] = DotProduct(local,vfwd);
// Make sure Z is not negative.
if(transformed[2] < 0.01)
{
return false;
}
// Simple convert to screen coords.
float xzi = xcenter / transformed[2] * (90.0/theFxHelper.refdef->fov_x);
float yzi = ycenter / transformed[2] * (90.0/theFxHelper.refdef->fov_y);
*x = (xcenter + xzi * transformed[0]);
*y = (ycenter - yzi * transformed[1]);
return true;
}
//----------------------------
void CFlash::Init( void )
{
// 10/19/01 kef -- maybe we want to do something different here for localized flashes, but right
//now I want to be sure that whatever RGB changes occur to a non-localized flash will also occur
//to a localized flash (so I'll have the same initial RGBA values for both...I need them sync'd for an effect)
vec3_t dif;
float mod = 1.0f, dis = 0.0f, maxRange = 900;
VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dif );
dis = VectorNormalize( dif );
mod = DotProduct( dif, theFxHelper.refdef->viewaxis[0] );
if ( dis > maxRange || ( mod < 0.5f && dis > 100 ))
{
mod = 0.0f;
}
else if ( mod < 0.5f && dis <= 100 )
{
mod += 1.1f;
}
mod *= (1.0f - ((dis * dis) / (maxRange * maxRange)));
VectorScale( mRGBStart, mod, mRGBStart );
VectorScale( mRGBEnd, mod, mRGBEnd );
if ( mFlags & FX_LOCALIZED_FLASH )
{
FX_WorldToScreen(mOrigin1, &mScreenX, &mScreenY);
// modify size of localized flash based on distance to effect (but not orientation)
if (dis > 100 && dis < maxRange)
{
mRadiusModifier = (1.0f - ((dis * dis) / (maxRange * maxRange)));
}
}
}
//----------------------------
void CFlash::Draw( void )
{
// Interestingly, if znear is set > than this, then the flash
// doesn't appear at all.
const float FLASH_DISTANCE_FROM_VIEWER = 12.0f;
mRefEnt.reType = RT_SPRITE;
if ( mFlags & FX_LOCALIZED_FLASH )
{
vec4_t color;
color[0] = mRefEnt.shaderRGBA[0] / 255.0;
color[1] = mRefEnt.shaderRGBA[1] / 255.0;
color[2] = mRefEnt.shaderRGBA[2] / 255.0;
color[3] = mRefEnt.shaderRGBA[3] / 255.0;
// add this 2D effect to the proper list. it will get drawn after the trap->RenderScene call
theFxScheduler.Add2DEffect(mScreenX, mScreenY, mRefEnt.radius, mRefEnt.radius, color, mRefEnt.customShader);
}
else
{
VectorCopy( theFxHelper.refdef->vieworg, mRefEnt.origin );
VectorMA( mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, theFxHelper.refdef->viewaxis[0], mRefEnt.origin );
// This is assuming that the screen is wider than it is tall.
mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan (DEG2RAD (theFxHelper.refdef->fov_x * 0.5f));
theFxHelper.AddFxToScene( &mRefEnt );
}
drawnFx++;
}
void FX_AddPrimitive( CEffect **pEffect, int killTime );
void FX_FeedTrail(effectTrailArgStruct_t *a)
{
CTrail *fx = new CTrail;
int i = 0;
while (i < 4)
{
VectorCopy(a->mVerts[i].origin, fx->mVerts[i].origin);
VectorCopy(a->mVerts[i].rgb, fx->mVerts[i].rgb);
VectorCopy(a->mVerts[i].destrgb, fx->mVerts[i].destrgb);
VectorCopy(a->mVerts[i].curRGB, fx->mVerts[i].curRGB);
fx->mVerts[i].alpha = a->mVerts[i].alpha;
fx->mVerts[i].destAlpha = a->mVerts[i].destAlpha;
fx->mVerts[i].curAlpha = a->mVerts[i].curAlpha;
fx->mVerts[i].ST[0] = a->mVerts[i].ST[0];
fx->mVerts[i].ST[1] = a->mVerts[i].ST[1];
fx->mVerts[i].destST[0] = a->mVerts[i].destST[0];
fx->mVerts[i].destST[1] = a->mVerts[i].destST[1];
fx->mVerts[i].curST[0] = a->mVerts[i].curST[0];
fx->mVerts[i].curST[1] = a->mVerts[i].curST[1];
i++;
}
fx->SetFlags(a->mSetFlags);
fx->mShader = a->mShader;
FX_AddPrimitive((CEffect **)&fx, a->mKillTime);
}
// end
| 0 | 0.95895 | 1 | 0.95895 | game-dev | MEDIA | 0.698134 | game-dev,graphics-rendering | 0.964285 | 1 | 0.964285 |
oiuv/mud | 12,271 | clone/misc/depot_ob.h | // 如意乾坤袋 Modified by 雪风@mud.ren
// 已废弃调用,改为F_STORAGE
#include <ansi.h>
#include <config.h>
inherit ITEM;
inherit F_NOCLONE;
inherit F_DBSAVE;
int is_item_make() { return 1; }
int is_depot_ob() { return 1; }
int clean_up(int inherited) { return 1; }
int store_item(object me, object ob, int amount);
class store {
string name, id, file;
//string *ids;
int amount;
}
nosave class store *all = ({});
void create()
{
// object me = this_player();
set_name(HIW "如意" HIG "乾" HIY "坤" HIC "袋" NOR, ({ "ruyi dai", "ruyi", "dai" }));
set_weight(100);
set("long", HIC " 一个四周环绕着神秘光环的如意乾坤袋,其炼制手法堪称巧夺天工。据说可以将"
"东西无限制的存(" NOR HIY "store" NOR HIC ")进去,不会丢失,且无论什么时候都可以取"
"("NOR HIY "take" NOR HIC")出来。\n" NOR);
set("unit", "个");
set("value",1000);
set("no_drop", 1);
set("no_steal", 1);
set("no_put", 1);
set("no_sell", "如意乾坤袋你也舍得卖掉?\n");
setup();
::restore();
// 升级如意乾坤袋为背包系统
// if(!me->query("storage_bag"))
// {
// me->set("storage_bag", 1);
// store_variable("all", all, me);
// me->save_depot();
// tell_object(me , HIY "你的如意乾坤袋成功升级为个人背包,以后无需召唤,背包相关指令:" HIC "bag take store\n" NOR);
// DBASE_D->clear_object(this_object());
// }
}
/*
string short()
{
if(this_player())
return HIC + this_player()->query("name") + HIW "的" HIM "如意" HIG "乾" HIY "坤" HIB "袋" NOR "(Ruyi Dai)";
}
*/
string extra_long()
{
mixed ob_name_real_len;
string msg;
if( !all || sizeof(all) < 1 )
return "\n这个如意乾坤袋里没有存放任何物品。\n";
msg = HIW "\n这个如意乾坤袋里存放的物品有:\n编号 物品 数量\n"
"----------------------------------------------------------------\n" NOR;
for( int i=0; i<sizeof(all); i++ )
{
ob_name_real_len = color_len(all[i]->name + "(" + all[i]->id + ")");
// msg += sprintf("[%2d] %-" + (ob_name_real_len) + "s %-8d\n",
msg += sprintf("[%2d] %-" + (30) + "s %-8d\n",
i + 1, all[i]->name + "(" + all[i]->id + ")",
all[i]->amount);
if (all[i]->amount == 0)
all[i] = 0;
}
msg += HIW "----------------------------------------------------------------\n" NOR;
all -= ({ 0 });
return msg;
}
void init()
{
// 如意乾坤袋升级为玩家背包,存取功能禁用
// add_action("do_store", "store");
// add_action("do_take", "take");
}
int do_take(string arg)
{
object me, ob;
object *obs;
int n, amount, num;
string un;
me = this_player();
if( me->is_busy() ) return notify_fail("你正忙着呢。\n");
if( !arg || sscanf(arg, "%d %d", n, amount) != 2 )
return notify_fail("格式错误,请用 take 编号 数量 来取回物品。\n");
if( amount < 1 || amount > 10000 )
return notify_fail("每次取物品的数量不得小于一同时也不能大于一万。\n");
if( n < 1 ) return notify_fail("你要取第几号物品?\n");
if( !all || sizeof(all) < 1 || n > sizeof(all) )
return notify_fail("你的如意乾坤袋里没有存放这项物品。\n");
n--;
if( amount > all[n]->amount )
amount = all[n]->amount;
if( !(ob = new(all[n]->file)) )
{
all[n] = 0;
all -= ({ 0 });
tell_object(me, "无法取出该物品,系统自动清除之。\n");
return 1;
}
obs=filter_array(all_inventory(me),(:!$1->query("equipped"):));
if (sizeof(obs) >= MAX_ITEM_CARRIED &&
! ob->can_combine_to(me))
return notify_fail("你身上的东西实在是太多了,没法再拿东西了。\n");
if( me->query_encumbrance() + ob->query_weight() * amount > me->query_max_encumbrance() )
{
tell_object(me, "你的负重不够,无法一次取出这么多物品。\n");
destruct(ob);
return 1;
}
if (ob->query("unit"))
un = ob->query("unit");
else
un = ob->query("base_unit");
if( ob->query_amount() )
{
all[n]->amount -= amount;
if( all[n]->amount == 0 )
{
all[n] = 0;
all -= ({ 0 });
}
ob->set_amount(amount);
ob->move(me, 1);
save();
message_vision("$N从如意乾坤袋里取出一" + un + ob->query("name") + "。\n", me);
return 1;
}
destruct(ob);
if( amount > 100 ) amount = 100;
all[n]->amount -= amount;
num = amount;
while( num-- )
{
ob = new(all[n]->file);
if( ob->query("equipped")) ob->delete("equipped");
ob->move(me, 1);
}
message_vision("$N从如意乾坤袋里取出" + chinese_number(amount) +
un + ob->query("name") + "。\n", me);
if( !wizardp(me) && random(2) )
me->start_busy(3);
if( all[n]->amount == 0 )
{
all[n] = 0;
all -= ({ 0 });
}
save();
return 1;
}
int do_store(string arg)
{
int i, n, amount;
string item;
object me, ob1, ob2, *inv;
me = this_player();
if( !arg ) return notify_fail("你要存放什么东西?\n");
if( me->is_busy() ) return notify_fail("你正在忙着呢!\n");
n = 100;
if( sizeof(all) >= n )
{
return notify_fail("你如意乾坤袋的 " + n + " 个储藏空间全被使用了,请整理一下吧。\n");
}
if( arg == "all" )
{
inv = all_inventory(me);
inv -= ({ this_object() });
inv -= ({ 0 });
inv = filter_array(inv, (: !$1->is_item_make() && !$1->query("equipped") && !$1->is_money() && !$1->is_food() :));
n = sizeof(inv);
if( n > 100 )
{
tell_object(me, "你身上的物品太多了,很容易搞混,你还是一个一个存吧。\n");
return 1;
}
if( n < 1 )
{
tell_object(me, "你身上没有任何可以保存的物品。\n");
return 1;
}
for( i=0; i<n; i++ )
{
do_store(inv[i]->query("id"));
}
return 1;
}
else if (sscanf(arg, "%d %s", amount, item) == 2)
{
if( !objectp(ob1 = present(item, me)) )
return notify_fail("你身上没有这样东西。\n");
if( !ob1->query_amount() )
return notify_fail(ob1->name() + "不能被分开存放。\n");
if( amount < 1 )
return notify_fail("存东西的数量至少是一个。\n");
if( amount > ob1->query_amount() )
return notify_fail("你没有那么多的" + ob1->name() + "。\n");
if( amount == (int)ob1->query_amount() )
{
return store_item(me, ob1, amount);
}
else
{
ob1->set_amount((int)ob1->query_amount() - amount);
ob2 = new(base_name(ob1));
ob2->set_amount(amount);
if( !store_item(me, ob2, amount) )
{
ob2->move(me, 1);
return 0;
}
return 1;
}
}
if( !objectp(ob1 = present(arg, me)) )
return notify_fail("你身上没有这样东西。\n");
if( ob1->query_amount() )
return do_store(ob1->query_amount() + " " + arg);
store_item(me, ob1, 1);
return 1;
}
int store_item(object me, object ob, int amount)
{
class store item;
int i, n;
string file, name, id, un;
if( !objectp(ob) )
{
error("no this object!\n");
return 0;
}
if( file_size(base_name(ob) + ".c") < 0 )
return 0;
if( inherits(F_SILENTDEST, ob) )
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 0;
}
if( inherits(F_UNIQUE, ob) )
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 0;
}
if( member_array(ITEM + ".c", deep_inherit_list(ob)) == -1 &&
member_array(COMBINED_ITEM + ".c", deep_inherit_list(ob)) == -1 )
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 0;
}
/*
if( ! ob->query_autoload())
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 1;
}
*/
if (ob->query_entire_temp_dbase())
{
tell_object(me, ob->query("name") + "比较特别,请你自己妥善处理。\n");
return 0;
}
if (ob->is_money())
{
tell_object(me, "存钱请找钱庄老板存(deposit)。\n");
return 1;
}
if (ob->is_food() || ob->is_liquid())
{
tell_object(me, "食物饮水存到如意乾坤袋后会变质的。\n");
return 1;
}
if(ob->is_no_clone() || ob->query("no_put") || ob->query("no_store"))
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 0;
}
if( ob->is_character() || ob->is_item_make() || !clonep(ob) )
{
tell_object(me, "如意乾坤袋不保存" + ob->query("name") + ",请你自己妥善处理。\n");
return 0;
}
switch( ob->query("equipped"))
{
case "worn":
tell_object(me, ob->name() + "必须先脱下来才能存放。\n");
return 0;
case "wielded":
tell_object(me, ob->name() + "必须先解除装备才能存放。\n");
return 0;
}
if( sizeof(all_inventory(ob)) )
{
tell_object(me, "请你先把" + ob->query("name") + "里面的东西先拿出来。\n");
return 0;
}
name = ob->query("name");
file = base_name(ob);
id = ob->query("id");
if (ob->query("base_unit"))
un = ob->query("base_unit");
else
un = ob->query("unit");
n = sizeof(all);
for( i=0; i<n; i++ )
{
if( all[i]->file == file &&
all[i]->id == id &&
all[i]->name == name )
{
all[i]->amount += amount;
save();
message_vision("$N把" + chinese_number(amount) + un +
ob->query("name") + "存到如意乾坤袋里。\n", me);
destruct(ob);
return 1;
}
}
item = new(class store);
item->file = file;
item->name = name;
item->id = id;
//item->ids = ob->parse_command_id_list();
item->amount = amount;
all += ({ item });
save();
message_vision("$N把" + chinese_number(amount) + un +
ob->query("name") + "存到如意乾坤袋里。\n", me);
destruct(ob);
return 1;
}
int receive_summon(object me)
{
object env;
if( (env = environment()) && env == me )
{
write(name() + "不就在你身上嘛?你召唤个什么劲?\n");
return 1;
}
if( env == environment(me) )
{
message_vision(HIG "只见地上的" + name() + HIG "化作一道光芒,飞跃至$N" HIW
"的掌中!\n\n" NOR, me);
}
else
{
if( env )
{
if( env->is_character() && environment(env) )
env = environment(env);
message("vision", HIG "突然" + name() + HIG "化作一道光芒消失了!\n\n" NOR, env);
if( interactive(env = environment()) )
{
tell_object(env, HIM + name() + HIM "忽然离你而去了!\n" NOR);
}
}
message_vision(HIM "一道光芒划过,只见$N" HIM "掌中多了一个$n" HIM "!\n" NOR,
me, this_object());
}
if( !this_object()->move(me) )
tell_object(me, HIR "由于你的负重太高," + this_object()->name() + HIR "化作一道光芒,已然了无踪迹。\n" NOR);
return 1;
}
int hide_anywhere(object me)
{
if( me->query("jingli") < 100)
{
tell_object(me, "你试图令" + name() + "遁去,可是精力不济,难以发挥它的能力。\n");
return 0;
}
me->add("jingli", -100);
message_vision(HIB "$N" HIB "轻轻一挥手," + name() + HIB "已然了无踪迹。\n" NOR, me);
save();
destruct(this_object());
return 1;
}
/*
int receive_dbase_data(mixed data)
{
if( !mapp(data) || sizeof(data) < 1 )
return 0;
if( data["all"] )
all = data["all"];
return 1;
}
mixed save_dbase_data()
{
mapping data;
data = ([]);
if( sizeof(all) > 0 )
data += ([ "all" : all ]);
return data;
}
*/
// 接受存盘数据的接口函数
int receive_dbase_data(mixed data)
{
int i, n;
class store item;
if( !mapp(data) || sizeof(data) < 1 )
return 0;
n = sizeof(data);
for (i = 0; i < n; i++)
{
item = new(class store);
item->name = data["item" + i]["name"];
item->id = data["item" + i]["id"];
item->file = data["item" + i]["file"];
item->amount = data["item" + i]["amount"];
all += ({ item });
}
return 1;
}
// 进行保存数据的接口函数
mixed save_dbase_data()
{
mapping data,list;
int i, n;
data = ([]);
if( sizeof(all) > 0 )
{
n = sizeof(all);
for( i=0; i<n; i++ )
{
list = ([]);
list["name"] = all[i]->name;
list["id"] = all[i]->id;
list["file"] = all[i]->file;
list["amount"] = all[i]->amount;
data += ([ "item" + i :list]);
}
}
return data;
}
| 0 | 0.695456 | 1 | 0.695456 | game-dev | MEDIA | 0.335704 | game-dev | 0.770659 | 1 | 0.770659 |
DamiTheHuman/quill-framework | 3,577 | Assets/Resources/Regular Stage/Gimmicks/Layer Switch/Scripts/LayerSwitch.cs | using UnityEngine;
/// <summary>
/// Class that switches the layer the player is currently on based on the players direction
/// </summary>
public class LayerSwitch : TriggerContactGimmick
{
[SerializeField]
private BoxCollider2D boxCollider2D;
[SerializeField]
private LayerSwitchCondition switchCondition = LayerSwitchCondition.SwitchWhenGroundedAndMoving;
[SerializeField, LayerList]
[Help("Regular - The layer added when the player is going right but removed when going Left \n ForceSwitch - The layer added when a force switch takes place")]
private int layerSwap1 = 9;
[SerializeField, LayerList]
[Help("The layer added when the player is going left but removed when going right \n ForceSwitch - The layer removed when a force switch takes place")]
private int layerSwap2 = 10;
public Color debugColor = new Color(0f / 255f, 204f / 154f, 323f / 255f);
public override void Reset()
{
base.Reset();
this.boxCollider2D = this.GetComponent<BoxCollider2D>();
}
protected override void Start()
{
base.Start();
if (this.boxCollider2D == null)
{
this.Reset();
}
}
/// <summary>
/// Checks if the players solid box comes in contact with the solid box
/// <param name="player">The player object to check against </param>
/// <param name="solidBoxColliderBounds">The players solid box colliders bounds </param>
/// </summary>
public override bool HedgeIsCollisionValid(Player player, Bounds solidBoxColliderBounds)
{
bool triggerAction = true;
return triggerAction;
}
/// <summary>
/// Switch the players layer to the set layer to add and remove the layer the player is currently on
/// <param name="player">The player object to manipulate </param>
/// </summary>
public override void HedgeOnCollisionEnter(Player player)
{
base.HedgeOnCollisionEnter(player);
if (this.switchCondition == LayerSwitchCondition.Always)
{
this.SwitchLayer(player, true);
}
else
{
if (player.groundVelocity is < 0 or > 0)
{
this.SwitchLayer(player);
}
}
}
/// <summary>
/// Changes the player layer if he is grounded
/// <param name="player">The active player object </param>
/// <param name="forceSwitch">The flag which determines whether to always switch </param>
/// </summary>
private void SwitchLayer(Player player, bool forceSwitch = false)
{
Sensors sensors = player.GetSensors();
if (forceSwitch)
{
sensors.AddLayerToAllCollisionMasks(this.layerSwap1);
sensors.RemoveLayerFromAllCollisionMasks(this.layerSwap2);
return;
}
if (this.switchCondition == LayerSwitchCondition.SwitchWhenGroundedAndMoving)
{
if (player.groundVelocity > 0)
{
sensors.AddLayerToAllCollisionMasks(this.layerSwap1);
sensors.RemoveLayerFromAllCollisionMasks(this.layerSwap2);
}
else if (player.groundVelocity < 0)
{
sensors.AddLayerToAllCollisionMasks(this.layerSwap2);
sensors.RemoveLayerFromAllCollisionMasks(this.layerSwap1);
}
}
}
private void OnDrawGizmos()
{
if (this.boxCollider2D == null)
{
GizmosExtra.DrawWireRect(this.boxCollider2D.bounds, this.debugColor);
}
}
}
| 0 | 0.948158 | 1 | 0.948158 | game-dev | MEDIA | 0.964393 | game-dev | 0.961388 | 1 | 0.961388 |
CorsixTH/CorsixTH | 2,876 | CorsixTH/Lua/rooms/inflation.lua | --[[ Copyright (c) 2009 Peter "Corsix" Cawley
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. --]]
local room = {}
room.id = "inflation"
room.vip_must_visit = false
room.level_config_id = 17
room.class = "InflationRoom"
room.name = _S.rooms_short.inflation
room.long_name = _S.rooms_long.inflation
room.tooltip = _S.tooltip.rooms.inflation
room.objects_additional = { "extinguisher", "radiator", "plant", "bin" }
room.objects_needed = { inflator = 1 }
room.build_preview_animation = 908
room.categories = {
clinics = 1,
}
room.minimum_size = 4
room.wall_type = "blue"
room.floor_tile = 17
room.required_staff = {
Doctor = 1,
}
room.maximum_staff = room.required_staff
room.call_sound = "reqd014.wav"
room.handyman_call_sound = "maint013.wav"
class "InflationRoom" (Room)
---@type InflationRoom
local InflationRoom = _G["InflationRoom"]
function InflationRoom:InflationRoom(...)
self:Room(...)
end
function InflationRoom:commandEnteringPatient(patient)
local staff = self.staff_member
local inflator, pat_x, pat_y = self.world:findObjectNear(patient, "inflator")
local stf_x, stf_y = inflator:getSecondaryUsageTile()
staff:setNextAction(WalkAction(stf_x, stf_y))
staff:queueAction(IdleAction():setDirection(inflator.direction == "north" and "east" or "south"))
patient:setNextAction(WalkAction(pat_x, pat_y))
local inflation_after_use = --[[persistable:inflation_after_use]] function()
patient:setLayer(0, patient.layers[0] - 10) -- Change to normal head
-- if no other actions for staff member meander in room
if #staff.action_queue == 1 then
staff:setNextAction(MeanderAction())
else
staff:finishAction(staff:getCurrentAction())
end
self:dealtWithPatient(patient)
end
patient:queueAction(MultiUseObjectAction(inflator, staff):setAfterUse(inflation_after_use))
return Room.commandEnteringPatient(self, patient)
end
return room
| 0 | 0.939794 | 1 | 0.939794 | game-dev | MEDIA | 0.919028 | game-dev | 0.717182 | 1 | 0.717182 |
opentibiabr/canary | 1,169 | data-otservbr-global/scripts/quests/bigfoot_burden/actions_spores.lua | local config = {
[15817] = 15705,
[15818] = 15706,
[15819] = 15707,
[15820] = 15708,
}
local bigfootSpores = Action()
function bigfootSpores.onUse(player, item, fromPosition, target, toPosition, isHotkey)
local spores = config[item.itemid]
if not spores then
return false
end
local sporeCount = player:getStorageValue(Storage.Quest.U9_60.BigfootsBurden.SporeCount)
if sporeCount == 4 or player:getStorageValue(Storage.Quest.U9_60.BigfootsBurden.MissionSporeGathering) ~= 1 then
return false
end
if target.itemid ~= spores then
player:setStorageValue(Storage.Quest.U9_60.BigfootsBurden.SporeCount, 0)
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You have gathered the wrong spores. You ruined your collection.")
item:transform(15817)
toPosition:sendMagicEffect(CONST_ME_POFF)
return true
end
player:setStorageValue(Storage.Quest.U9_60.BigfootsBurden.SporeCount, sporeCount + 1)
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You have gathered the correct spores.")
item:transform(item.itemid + 1)
toPosition:sendMagicEffect(CONST_ME_GREEN_RINGS)
return true
end
bigfootSpores:id(15817, 15818, 15819, 15820)
bigfootSpores:register()
| 0 | 0.780869 | 1 | 0.780869 | game-dev | MEDIA | 0.889059 | game-dev | 0.860295 | 1 | 0.860295 |
Soar-Client/Legacy-SoarClient | 8,974 | src/main/java/me/eldodebug/soar/management/mods/impl/BlockOverlayMod.java | package me.eldodebug.soar.management.mods.impl;
import java.awt.Color;
import org.lwjgl.opengl.GL11;
import me.eldodebug.soar.Soar;
import me.eldodebug.soar.management.color.AccentColor;
import me.eldodebug.soar.management.event.EventTarget;
import me.eldodebug.soar.management.event.impl.EventBlockHighlightRender;
import me.eldodebug.soar.management.language.TranslateText;
import me.eldodebug.soar.management.mods.Mod;
import me.eldodebug.soar.management.mods.ModCategory;
import me.eldodebug.soar.management.mods.settings.impl.BooleanSetting;
import me.eldodebug.soar.management.mods.settings.impl.ColorSetting;
import me.eldodebug.soar.management.mods.settings.impl.NumberSetting;
import me.eldodebug.soar.utils.ColorUtils;
import me.eldodebug.soar.utils.Render3DUtils;
import me.eldodebug.soar.utils.TimerUtils;
import me.eldodebug.soar.utils.animation.simple.SimpleAnimation;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.WorldSettings;
public class BlockOverlayMod extends Mod {
protected AxisAlignedBB currentBB;
protected AxisAlignedBB slideBB;
protected TimerUtils timer = new TimerUtils();
private SimpleAnimation[] simpleAnimation = {new SimpleAnimation(0.0F), new SimpleAnimation(0.0F), new SimpleAnimation(0.0F), new SimpleAnimation(0.0F), new SimpleAnimation(0.0F), new SimpleAnimation(0.0F)};
private BooleanSetting animationSetting = new BooleanSetting(TranslateText.ANIMATION, this, false);
private BooleanSetting fillSetting = new BooleanSetting(TranslateText.FILL, this, true);
private BooleanSetting outlineSetting = new BooleanSetting(TranslateText.OUTLINE, this, true);
private NumberSetting fillAlphaSetting = new NumberSetting(TranslateText.FILL_ALPHA, this, 0.15, 0, 1.0, false);
private NumberSetting outlineAlphaSetting = new NumberSetting(TranslateText.OUTLINE_ALPHA, this, 0.15, 0, 1.0, false);
private NumberSetting outlineWidthSetting = new NumberSetting(TranslateText.OUTLINE_WIDTH, this, 4, 1, 10, false);
private BooleanSetting depthSetting = new BooleanSetting(TranslateText.DEPTH, this, false);
private BooleanSetting customColorSetting = new BooleanSetting(TranslateText.CUSTOM_COLOR, this, false);
private ColorSetting fillColorSetting = new ColorSetting(TranslateText.FILL_COLOR, this, Color.RED, false);
private ColorSetting outlineColorSetting = new ColorSetting(TranslateText.OUTLINE_COLOR, this, Color.RED, false);
public BlockOverlayMod() {
super(TranslateText.BLOCK_OVERLAY, TranslateText.BLOCK_OVERLAY_DESCRIPTION, ModCategory.RENDER);
}
@EventTarget
public void onBlockHighlightRender(EventBlockHighlightRender event) {
AccentColor currentColor = Soar.getInstance().getColorManager().getCurrentColor();
event.setCancelled(true);
if(!canRender(event.getObjectMouseOver())) {
return;
}
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
if(depthSetting.isToggled()) {
GlStateManager.disableDepth();
}
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
BlockPos blockpos = event.getObjectMouseOver().getBlockPos();
Block block = mc.theWorld.getBlockState(blockpos).getBlock();
if(block.getMaterial() != Material.air && mc.theWorld.getWorldBorder().contains(blockpos)) {
block.setBlockBoundsBasedOnState(mc.theWorld, blockpos);
double x = mc.getRenderViewEntity().lastTickPosX
+ (mc.getRenderViewEntity().posX - mc.getRenderViewEntity().lastTickPosX) * (double) event.getPartialTicks();
double y = mc.getRenderViewEntity().lastTickPosY
+ (mc.getRenderViewEntity().posY - mc.getRenderViewEntity().lastTickPosY) * (double) event.getPartialTicks();
double z = mc.getRenderViewEntity().lastTickPosZ
+ (mc.getRenderViewEntity().posZ - mc.getRenderViewEntity().lastTickPosZ) * (double) event.getPartialTicks();
AxisAlignedBB selectedBox = block.getSelectedBoundingBox(mc.theWorld, blockpos);
if(animationSetting.isToggled()) {
if (!selectedBox.equals(currentBB)) {
slideBB = currentBB;
currentBB = selectedBox;
}
AxisAlignedBB slide;
if((slide = slideBB) != null) {
simpleAnimation[0].setAnimation((float) (slide.minX + (selectedBox.minX - slide.minX)), 24);
simpleAnimation[1].setAnimation((float) (slide.minY + (selectedBox.minY - slide.minY)), 24);
simpleAnimation[2].setAnimation((float) (slide.minZ + (selectedBox.minZ - slide.minZ)), 24);
simpleAnimation[3].setAnimation((float) (slide.maxX + (selectedBox.maxX - slide.maxX)), 24);
simpleAnimation[4].setAnimation((float) (slide.maxY + (selectedBox.maxY - slide.maxY)), 24);
simpleAnimation[5].setAnimation((float) (slide.maxZ + (selectedBox.maxZ - slide.maxZ)), 24);
AxisAlignedBB renderBB = new AxisAlignedBB(
simpleAnimation[0].getValue() - 0.01,
simpleAnimation[1].getValue() - 0.01,
simpleAnimation[2].getValue() - 0.01,
simpleAnimation[3].getValue() + 0.01,
simpleAnimation[4].getValue() + 0.01,
simpleAnimation[5].getValue() + 0.01
);
if(fillSetting.isToggled()) {
ColorUtils.setColor(customColorSetting.isToggled() ? fillColorSetting.getColor().getRGB() : currentColor.getInterpolateColor().getRGB(), fillAlphaSetting.getValueFloat());
Render3DUtils.drawFillBox(interpolateAxis(renderBB));
}
if(outlineSetting.isToggled()) {
ColorUtils.setColor(customColorSetting.isToggled() ? outlineColorSetting.getColor().getRGB() : currentColor.getInterpolateColor().getRGB(), outlineAlphaSetting.getValueFloat());
GL11.glLineWidth(outlineWidthSetting.getValueFloat());
RenderGlobal.drawSelectionBoundingBox(interpolateAxis(renderBB));
}
}
}else {
selectedBox = selectedBox.expand(0.0020000000949949026D, 0.0020000000949949026D, 0.0020000000949949026D).offset(-x, -y, -z);
if(fillSetting.isToggled()) {
ColorUtils.setColor(customColorSetting.isToggled() ? fillColorSetting.getColor().getRGB() : currentColor.getInterpolateColor().getRGB(), fillAlphaSetting.getValueFloat());
Render3DUtils.drawFillBox(selectedBox);
}
if(outlineSetting.isToggled()) {
ColorUtils.setColor(customColorSetting.isToggled() ? outlineColorSetting.getColor().getRGB() : currentColor.getInterpolateColor().getRGB(), outlineAlphaSetting.getValueFloat());
GL11.glLineWidth(outlineWidthSetting.getValueFloat());
RenderGlobal.drawSelectionBoundingBox(selectedBox);
}
}
}
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
if(depthSetting.isToggled()) {
GlStateManager.enableDepth();
}
GL11.glLineWidth(2);
}
private boolean canRender(MovingObjectPosition movingObjectPositionIn) {
Entity entity = mc.getRenderViewEntity();
boolean result = entity instanceof EntityPlayer && !mc.gameSettings.hideGUI;
if(result && !((EntityPlayer)entity).capabilities.allowEdit) {
ItemStack itemstack = ((EntityPlayer)entity).getCurrentEquippedItem();
if(mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
BlockPos selectedBlock = mc.objectMouseOver.getBlockPos();
Block block = mc.theWorld.getBlockState(selectedBlock).getBlock();
if(mc.playerController.getCurrentGameType() == WorldSettings.GameType.SPECTATOR) {
result = block.hasTileEntity() && mc.theWorld.getTileEntity(selectedBlock) instanceof IInventory;
}
else {
result = itemstack != null && (itemstack.canDestroy(block) || itemstack.canPlaceOn(block));
}
}
}
result = result && movingObjectPositionIn.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK;
return result;
}
public AxisAlignedBB interpolateAxis(AxisAlignedBB bb) {
return new AxisAlignedBB(
bb.minX - mc.getRenderManager().viewerPosX,
bb.minY - mc.getRenderManager().viewerPosY,
bb.minZ - mc.getRenderManager().viewerPosZ,
bb.maxX - mc.getRenderManager().viewerPosX,
bb.maxY - mc.getRenderManager().viewerPosY,
bb.maxZ - mc.getRenderManager().viewerPosZ);
}
}
| 0 | 0.826647 | 1 | 0.826647 | game-dev | MEDIA | 0.787573 | game-dev,graphics-rendering | 0.983593 | 1 | 0.983593 |
lua9520/source-engine-2018-cstrike15_src | 3,091 | public/cmodel.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef CMODEL_H
#define CMODEL_H
#ifdef _WIN32
#pragma once
#endif
#include "trace.h"
#include "tier0/dbg.h"
#include "basehandle.h"
struct edict_t;
struct model_t;
/*
==============================================================
COLLISION DETECTION
==============================================================
*/
#include "bspflags.h"
//#include "mathlib/vector.h"
// gi.BoxEdicts() can return a list of either solid or trigger entities
// FIXME: eliminate AREA_ distinction?
#define AREA_SOLID 1
#define AREA_TRIGGERS 2
#include "vcollide.h"
struct cmodel_t
{
Vector mins, maxs;
Vector origin; // for sounds or lights
int headnode;
vcollide_t vcollisionData;
};
struct csurface_t
{
const char *name;
short surfaceProps;
unsigned short flags; // BUGBUG: These are declared per surface, not per material, but this database is per-material now
};
//-----------------------------------------------------------------------------
// A ray...
//-----------------------------------------------------------------------------
struct Ray_t
{
VectorAligned m_Start; // starting point, centered within the extents
VectorAligned m_Delta; // direction + length of the ray
VectorAligned m_StartOffset; // Add this to m_Start to get the actual ray start
VectorAligned m_Extents; // Describes an axis aligned box extruded along a ray
const matrix3x4_t *m_pWorldAxisTransform;
bool m_IsRay; // are the extents zero?
bool m_IsSwept; // is delta != 0?
Ray_t() : m_pWorldAxisTransform( NULL ) {}
void Init( Vector const& start, Vector const& end )
{
Assert( &end );
VectorSubtract( end, start, m_Delta );
m_IsSwept = (m_Delta.LengthSqr() != 0);
VectorClear( m_Extents );
m_pWorldAxisTransform = NULL;
m_IsRay = true;
// Offset m_Start to be in the center of the box...
VectorClear( m_StartOffset );
VectorCopy( start, m_Start );
}
void Init( Vector const& start, Vector const& end, Vector const& mins, Vector const& maxs )
{
Assert( &end );
VectorSubtract( end, start, m_Delta );
m_pWorldAxisTransform = NULL;
m_IsSwept = (m_Delta.LengthSqr() != 0);
VectorSubtract( maxs, mins, m_Extents );
m_Extents *= 0.5f;
m_IsRay = (m_Extents.LengthSqr() < 1e-6);
Assert(m_Extents.x >=0 && m_Extents.y >= 0 && m_Extents.z >= 0);
// Offset m_Start to be in the center of the box...
VectorAdd( mins, maxs, m_StartOffset );
m_StartOffset *= 0.5f;
VectorAdd( start, m_StartOffset, m_Start );
m_StartOffset *= -1.0f;
}
// compute inverse delta
Vector InvDelta() const
{
Vector vecInvDelta;
for ( int iAxis = 0; iAxis < 3; ++iAxis )
{
if ( m_Delta[iAxis] != 0.0f )
{
vecInvDelta[iAxis] = 1.0f / m_Delta[iAxis];
}
else
{
vecInvDelta[iAxis] = FLT_MAX;
}
}
return vecInvDelta;
}
private:
};
#endif // CMODEL_H
#include "gametrace.h"
| 0 | 0.884575 | 1 | 0.884575 | game-dev | MEDIA | 0.868757 | game-dev | 0.837379 | 1 | 0.837379 |
KC3Kai/KC3Kai | 53,041 | src/library/managers/QuestManager.js | /* QuestManager.js
KC3改 Quest Management Object
Stand-alone object, attached to root window, never to be instantiated
Contains functions to perform quest management tasks
Uses KC3Quest objects to play around with
*/
(function(){
"use strict";
const MS_PER_HOUR = 1000 * 60 * 60;
const MS_PER_DAY = MS_PER_HOUR * 24;
const SUNDAY = 0;
const JANUARY = 0;
const FEBRUARY = 1;
const MARCH = 2;
const APRIL = 3;
const MAY = 4;
const JUNE = 5;
const JULY = 6;
const AUGUST = 7;
const SEPTEMBER = 8;
const OCTOBER = 9;
const NOVEMBER = 10;
const DECEMBER = 11;
window.KC3QuestManager = {
list: {}, // Use curly brace instead of square bracket to avoid using number-based indexes
open: [], // Array of quests seen on the quests page, regardless of state
active: [], // Array of quests that are active and counting
// A quests list which confirmed sharing same counter at server-side
// Currently quests list is confirmed at: http://wikiwiki.jp/kancolle/?%C7%A4%CC%B3#sc3afcc0
sharedCounterQuests: [ [218, 212] ],
/* GET
Get a specific quest object in the list using its ID
------------------------------------------*/
get :function( questId ){
// Return requested quest object of that ID, or a new Quest object, whichever works
return (this.list["q"+questId] || (this.list["q"+questId] = new KC3Quest()));
},
getIfExists :function( questId ){
return this.exists(questId) ? this.get(questId) : false;
},
exists :function( questId ){
return !!this.list["q"+questId];
},
remove :function( quest ){
var questId = (typeof quest === "object") ? quest.id : quest;
return delete this.list["q"+questId];
},
/* GET ACTIVE
Get list of active quests
------------------------------------------*/
getActives :function(){
var activeQuestObjects = [];
var self = this;
$.each(this.active, function( index, element ){
activeQuestObjects.push( self.get(element) );
});
return activeQuestObjects;
},
// Remove expired repeatables
checkAndResetQuests: function (serverTime) {
try {
KC3QuestManager.load();
KC3QuestManager.getRepeatableTypes().forEach(({ type, resetQuests }) => {
const resetTime = KC3QuestManager.getResetTime(type, serverTime);
if (serverTime >= resetTime) {
resetQuests();
KC3QuestManager.updateResetTime(type, serverTime);
KC3QuestManager.triggerNetworkEvent();
}
});
KC3QuestManager.save();
} catch (error) {
console.error("Reset Quest Error:", error);
}
},
getResetTime: function (questType, serverTime) {
const repeatable = KC3QuestManager.repeatableTypes[questType];
const result = localStorage.getItem(repeatable.key);
if (result) { return parseInt(result, 10); }
const resetTime = repeatable.calculateNextReset(serverTime);
localStorage.setItem(repeatable.key, resetTime);
return resetTime;
},
updateResetTime: function (questType, serverTime) {
const repeatable = KC3QuestManager.repeatableTypes[questType];
localStorage.setItem(repeatable.key, repeatable.calculateNextReset(serverTime));
},
triggerNetworkEvent: function () {
if (typeof KC3Network === 'object') {
KC3Network.trigger('Quests');
}
},
repeatableTypes: {
daily: {
type: 'daily',
key: 'timeToResetDailyQuests',
questIds: [201, 216, 210, 211, 218, 212, 226, 230, 303, 304, 402, 403, 503, 504, 605, 606, 607, 608, 609, 619, 673, 674, 702],
resetQuests: function () { KC3QuestManager.resetDailies(); },
calculateNextReset: function (serverTime) {
// JST is +9 GMT, so 05:00 JST === 20:00 UTC
let result = new Date(serverTime);
if (result.getUTCHours() >= 20) {
result = new Date(result.getTime() + MS_PER_DAY);
}
result.setUTCHours(20);
result.setUTCMinutes(0);
result.setUTCSeconds(0);
result.setUTCMilliseconds(0);
return result.getTime();
},
},
weekly: {
type: 'weekly',
key: 'timeToResetWeeklyQuests',
questIds: [214, 220, 213, 221, 228, 229, 241, 242, 243, 261, 302, 404, 410, 411, 613, 638, 676, 677, 703],
resetQuests: function () { KC3QuestManager.resetWeeklies(); },
calculateNextReset: function (serverTime) {
const nextDailyReset = new Date(
KC3QuestManager.repeatableTypes.daily.calculateNextReset(serverTime));
const day = nextDailyReset.getUTCDay();
// if the (daily) reset is on Sunday, it's also a weekly reset
// (Monday 05:00 JST === Sunday 20:00 UTC)
if (day === SUNDAY) {
return nextDailyReset.getTime();
}
// otherwise we need to advance to the end of the week
return nextDailyReset.getTime() + (MS_PER_DAY * (7 - day));
},
},
monthly: {
type: 'monthly',
key: 'timeToResetMonthlyQuests',
questIds: [249, 256, 257, 259, 265, 264, 266, 280, 311, 318, 424, 626, 628, 645],
resetQuests: function () { KC3QuestManager.resetMonthlies(); },
calculateNextReset: function (serverTime) {
const nextDailyReset = new Date(
KC3QuestManager.repeatableTypes.daily.calculateNextReset(serverTime));
// Date will handle wrapping for us; e.g. Date(2016, 12) === Date(2017, 0)
const firstDayOfNextMonth = new Date(Date.UTC(nextDailyReset.getUTCFullYear(),
nextDailyReset.getUTCMonth() + 1));
return firstDayOfNextMonth.getTime() - (4 * MS_PER_HOUR);
},
},
quarterly: {
type: 'quarterly',
key: 'timeToResetQuarterlyQuests',
questIds: [284, 330, 337, 339, 342, 426, 428, 637, 643, 653, 663, 675, 678, 680, 686, 688, 822, 845, 854, 861, 862, 872, 873, 875, 888, 893, 894, 903],
resetQuests: function () { KC3QuestManager.resetQuarterlies(); },
calculateNextReset: function (serverTime) {
const nextMonthlyReset = new Date(
KC3QuestManager.repeatableTypes.monthly.calculateNextReset(serverTime));
const month = nextMonthlyReset.getUTCMonth();
switch (month) {
// if nextMonthlyReset is in March, April, May, we're in the June quarter
// (i.e. reset at May 31st, 20:00 UTC)
case MARCH: case APRIL: case MAY: {
const firstofJune = new Date(Date.UTC(nextMonthlyReset.getUTCFullYear(), JUNE));
return firstofJune.getTime() - (4 * MS_PER_HOUR);
}
// if nextMonthlyReset is in June, July, August, we're in the September quarter
// (i.e. reset at August 31st, 20:00 UTC)
case JUNE: case JULY: case AUGUST: {
const firstOfSeptember = new Date(Date.UTC(nextMonthlyReset.getUTCFullYear(), SEPTEMBER));
return firstOfSeptember.getTime() - (4 * MS_PER_HOUR);
}
// if nextMonthlyReset is in September, October, November, we're in the December quarter
// (i.e. reset at November 30th, 20:00 UTC)
case SEPTEMBER: case OCTOBER: case NOVEMBER: {
const firstOfDecember = new Date(Date.UTC(nextMonthlyReset.getUTCFullYear(), DECEMBER));
return firstOfDecember.getTime() - (4 * MS_PER_HOUR);
}
// if nextMonthlyReset is in December, January, February, we're in the March quarter
// (i.e. reset at February 28th/29th, 20:00 UTC)
case DECEMBER: case JANUARY: case FEBRUARY: {
const firstOfMarch = new Date(Date.UTC(nextMonthlyReset.getUTCFullYear(), MARCH));
if (month === DECEMBER) {
firstOfMarch.setUTCFullYear(nextMonthlyReset.getUTCFullYear() + 1);
}
return firstOfMarch.getTime() - (4 * MS_PER_HOUR);
}
default:
// should be unreachable
throw new Error(`Bad month: ${month}`);
}
},
},
// Reset on 1st January every year
yearlyJan: {
type: 'yearlyJan',
key: 'timeToResetYearlyJanQuests',
resetMonth: JANUARY,
questIds: [681, 1005, 1123],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyJan.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyJan.resetMonth);
},
},
// Reset on 1st February every year
yearlyFeb: {
type: 'yearlyFeb',
key: 'timeToResetYearlyFebQuests',
resetMonth: FEBRUARY,
questIds: [348, 434, 442, 716, 717, 904, 905],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyFeb.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyFeb.resetMonth);
},
},
// Reset on 1st March every year
yearlyMar: {
type: 'yearlyMar',
key: 'timeToResetYearlyMarQuests',
resetMonth: MARCH,
questIds: [350, 436, 444, 912, 914],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyMar.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyMar.resetMonth);
},
},
// Reset on 1st April every year
yearlyApr: {
type: 'yearlyApr',
key: 'timeToResetYearlyAprQuests',
resetMonth: APRIL,
questIds: [362, 371],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyApr.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyApr.resetMonth);
},
},
// Reset on 1st May every year
yearlyMay: {
type: 'yearlyMay',
key: 'timeToResetYearlyMayQuests',
resetMonth: MAY,
questIds: [356, 437, 973, 975, 1012],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyMay.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyMay.resetMonth);
},
},
// Reset on 1st June every year
yearlyJun: {
type: 'yearlyJun',
key: 'timeToResetYearlyJunQuests',
resetMonth: JUNE,
questIds: [353, 357, 372, 944, 945, 946, 947, 948, 1103, 1104, 1138],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyJun.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyJun.resetMonth);
},
},
// Reset on 1st July every year
yearlyJul: {
type: 'yearlyJul',
key: 'timeToResetYearlyJulQuests',
resetMonth: JULY,
questIds: [354, 368, 373, 1105],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyJul.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyJul.resetMonth);
},
},
// Reset on 1st August every year
yearlyAug: {
type: 'yearlyAug',
key: 'timeToResetYearlyAugQuests',
resetMonth: AUGUST,
questIds: [438],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyAug.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyAug.resetMonth);
},
},
// Reset on 1st September every year
yearlySep: {
type: 'yearlySep',
key: 'timeToResetYearlySepQuests',
resetMonth: SEPTEMBER,
questIds: [375, 439, 440, 657, 928, 1018, 1107],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlySep.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlySep.resetMonth);
},
},
// Reset on 1st October every year
yearlyOct: {
type: 'yearlyOct',
key: 'timeToResetYearlyOctQuests',
resetMonth: OCTOBER,
questIds: [345, 346, 355, 377, 654],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyOct.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyOct.resetMonth);
},
},
// Reset on 1st November every year
yearlyNov: {
type: 'yearlyNov',
key: 'timeToResetYearlyNovQuests',
resetMonth: NOVEMBER,
questIds: [655, 714, 715],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyNov.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyNov.resetMonth);
},
},
// Reset on 1st December every year
yearlyDec: {
type: 'yearlyDec',
key: 'timeToResetYearlyDecQuests',
resetMonth: DECEMBER,
questIds: [1120],
resetQuests: function () {
KC3QuestManager.resetYearlies(KC3QuestManager.repeatableTypes.yearlyDec.type);
},
calculateNextReset: function (serverTime) {
return KC3QuestManager.calculateNextYearlyReset(serverTime, KC3QuestManager.repeatableTypes.yearlyDec.resetMonth);
},
},
},
calculateNextYearlyReset: function (serverTime, resetMonth) {
const nextMonthlyReset = new Date(KC3QuestManager.repeatableTypes.monthly.calculateNextReset(serverTime));
const nextUTCMonth = nextMonthlyReset.getUTCMonth();
// UTCMonth will be always previous month of JST month on 1st day 5:00, so >= used here
const nextYearlyReset = new Date(Date.UTC(nextMonthlyReset.getUTCFullYear() + (1 & (nextUTCMonth >= resetMonth)), resetMonth));
return nextYearlyReset.getTime() - (4 * MS_PER_HOUR);
},
getRepeatableTypes: function () {
return Object.keys(KC3QuestManager.repeatableTypes).map((key) => {
return KC3QuestManager.repeatableTypes[key];
});
},
// Get the ids of all quests of a specified repeatable type
getRepeatableIds: function (type) {
const repeatable = KC3QuestManager.repeatableTypes[type];
return !!repeatable ? repeatable.questIds.concat() : [];
},
/** DEFINE PAGE
* When a user loads a quest page, we use its data to update our list
* Since 2020-03-27, quest page in API no longer exists (in-game UI paginated still), list includes all available items in specified tab ID
------------------------------------------*/
definePage :function( questList, questPage, questTabId ){
const untranslated = [], existedAllIds = [];
const reportedQuests = JSON.parse(localStorage.reportedQuests || "[]");
for(var ctr in questList){
if(!questList[ctr] || questList[ctr] === -1) continue;
const questRaw = questList[ctr];
const questId = questRaw.api_no;
const questObj = this.get(questId);
questObj.defineRaw(questRaw);
questObj.autoAdjustCounter();
if(questTabId === 0){
existedAllIds.push(questId);
}
// Check for untranslated quests
if(typeof questObj.meta().available == "undefined"){
if(reportedQuests.indexOf(questId) === -1){
untranslated.push(questRaw);
// remember reported quest so wont send data twice
reportedQuests.push(questId);
}
}
// Add to actives or opens depending on its state
switch(questRaw.api_state){
case 1: // Unselected
this.isOpen(questId, true);
this.isActive(questId, false);
break;
case 2: // Selected
this.isOpen(questId, true);
this.isActive(questId, true);
break;
case 3: // Completed
this.isOpen(questId, false);
this.isActive(questId, false);
break;
default:
this.isOpen(questId, false);
this.isActive(questId, false);
break;
}
}
// Data submitting of untranslated quests no longer available for now
if(untranslated.length){
console.info("Untranslated quest detected", reportedQuests, untranslated);
}
// It's now possible to clean quests non-open-nor-active in-game for API change reason,
// Close (mark as completed) quests for those `api_no` not in current quest list, as long as questTabId is 0 (All quests available).
if(existedAllIds.length){
this.open.filter(id => !existedAllIds.includes(id)).forEach(id => { this.isOpen(id, false); this.get(id).status = 3; });
this.active.filter(id => !existedAllIds.includes(id)).forEach(id => { this.isActive(id, false); this.get(id).status = 3; });
}
this.save();
},
buildHtmlTooltip :function(questId, meta, isShowId = true, isShowUnlocks = true){
const questMeta = meta || KC3Meta.quest(questId);
if(!questId || !questMeta) return "";
const questObj = this.getIfExists(questId);
let title = ((isShowId ? "[{0:id}] " : "") + "{1:code} {2:name}")
.format(questId, questMeta.code || "N/A",
questMeta.name || KC3Meta.term("UntranslatedQuest"));
title += $("<p></p>").css("font-size", "11px")
.css("margin-left", "1em")
.css("text-indent", "-1em")
.text(questMeta.desc || KC3Meta.term("UntranslatedQuestTip"))
.prop("outerHTML");
const rewardRscItems = [];
const buildRscItem = (name, value) => {
const rsc = $("<div><img /> <span></span></div>");
$("img", rsc)
.width(11).height(11).css("margin-top", "-3px")
.attr("src", `/assets/img/client/${name}.png`);
$("span", rsc).text(value || 0);
return rsc.html();
};
if(questObj && Array.isArray(questObj.materials) && questObj.materials.some(v => v > 0)){
rewardRscItems.push(...["fuel", "ammo", "steel", "bauxite"]
.map((n, i) => buildRscItem(n, questObj.materials[i]))
);
}
if(Array.isArray(questMeta.rewardConsumables) && questMeta.rewardConsumables.some(v => v > 0)){
rewardRscItems.push(...["bucket", "devmat", "screws", "ibuild"]
.map((n, i) => buildRscItem(n, questMeta.rewardConsumables[(i + 1) % 4]))
);
}
if(rewardRscItems.length > 0) title += $("<p></p>").css("font-size", "11px")
.html(rewardRscItems.join(" ")).prop("outerHTML");
if(!!questMeta.memo){
title += $("<p></p>")
.css("font-size", "11px")
.css("color", "#69a").html(questMeta.memo)
.prop("outerHTML");
}
if(isShowUnlocks && Array.isArray(questMeta.unlock)){
for(const i in questMeta.unlock) {
const cq = KC3Meta.quest(questMeta.unlock[i]);
if(!!cq) title += " " +
$("<span></span>").css("font-size", "11px")
.css("color", "#a96")
.text("-> [{0:id}] {1:code} {2:name}"
.format(questMeta.unlock[i], cq.code || "N/A", cq.name)
).prop("outerHTML") + "<br/>";
}
}
return title;
},
/* IS OPEN
Defines a questId as open (not completed), adds to list
------------------------------------------*/
isOpen :function(questId, mode){
if(mode){
if(this.open.indexOf(questId) == -1){
this.open.push(questId);
}
}else{
if(this.open.indexOf(questId) > -1){
this.open.splice(this.open.indexOf(questId), 1);
}
}
},
/* IS ACTIVE
Defines a questId as active (the quest is selected), adds to list
------------------------------------------*/
isActive :function(questId, mode){
if(mode){
if(this.active.indexOf(questId) == -1){
this.active.push(questId);
}
}else{
if(this.active.indexOf(questId) > -1){
this.active.splice(this.active.indexOf(questId), 1);
}
}
},
/* IS PERIOD
Indicates if a questId is belong to time-period type quest.
------------------------------------------*/
isPeriod :function(questId){
var period = this.getRepeatableIds('daily').indexOf(questId)>-1;
period |= this.getRepeatableIds('weekly').indexOf(questId)>-1;
period |= this.getRepeatableIds('monthly').indexOf(questId)>-1;
period |= this.getRepeatableIds('quarterly').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyJan').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyFeb').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyMar').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyApr').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyMay').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyJun').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyJul').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyAug').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlySep').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyOct').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyNov').indexOf(questId)>-1;
period |= this.getRepeatableIds('yearlyDec').indexOf(questId)>-1;
return !!period;
},
/* RESETTING FUNCTIONS
Allows resetting quest state and counting
------------------------------------------*/
resetQuest :function(questId){
if(typeof this.list["q"+questId] != "undefined"){
delete this.list["q"+questId];
this.isOpen(questId, false);
this.isActive(questId, false);
}
},
resetQuestCounter: function( questId, forced ){
var quest = this.list["q"+questId];
if(quest !== undefined && Array.isArray(quest.tracking)){
for(var ctr in quest.tracking){
var progress = quest.tracking[ctr];
if(progress.length > 1 && (!!forced || progress[0] < progress[1])){
progress[0] = 0;
}
}
if(!!forced){
this.isActive(questId, false);
}
}
},
resetLoop: function( questIds ){
for(var ctr in questIds){
this.resetQuest( questIds[ctr] );
}
},
resetCounterLoop: function( questIds, forced ){
for(var ctr in questIds){
this.resetQuestCounter( questIds[ctr], forced );
}
},
resetDailies :function(){
this.load();
console.log("Resetting dailies");
this.resetLoop(this.getRepeatableIds('daily'));
// Progress counter reset to 0 even if completed but reward not clicked in a day:
// Monthly PvP C8
this.resetCounterLoop([311], true);
// Progress counter reset to 0 only if progress not completed in a day:
// Quarterly PvP C29, C38, C42, C44
this.resetCounterLoop([330, 337, 339, 342], false);
// Yearly PvP C49, C50, C53, C58, C60, C62, C65, C66, C72, Cy11, Cy12, Cy13, Cy14, Cy15, Cy16
this.resetCounterLoop([345, 346, 348, 353, 354, 355, 356, 357, 362, 368, 371, 372, 373, 375, 377], false);
// Progress counter not changed at all on daily reset:
// Monthly PvP C16
//this.resetCounterLoop([318], false);
this.save();
},
resetWeeklies :function(){
this.load();
console.log("Resetting weeklies");
this.resetLoop(this.getRepeatableIds('weekly'));
this.save();
},
resetMonthlies :function(){
this.load();
console.log("Resetting monthlies");
this.resetLoop(this.getRepeatableIds('monthly'));
this.save();
},
resetQuarterlies :function(){
this.load();
console.log("Resetting quarterlies");
this.resetLoop(this.getRepeatableIds('quarterly'));
this.save();
},
resetYearlies :function(typeId){
this.load();
console.log("Resetting yearlies", typeId || "auto");
if(!typeId || typeId === 'all') {
if(typeId === 'all') {
KC3QuestManager.getRepeatableTypes().forEach(({ type }) => {
if(type.startsWith('yearly')) {
this.resetLoop(this.getRepeatableIds(type));
}
});
} else {
const thisMonth = Date.getJstDate().getMonth();
const monthAbbr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][thisMonth];
const type = monthAbbr ? "yearly" + monthAbbr : false;
console.log("Auto found yearlies", type);
if(type) this.resetLoop(this.getRepeatableIds(type));
}
} else {
this.resetLoop(this.getRepeatableIds(typeId));
}
this.save();
},
clear :function(){
this.list = {};
this.active = [];
this.open = [];
this.save();
},
/**
* Check if specified quest's completion prerequisites are fulfilled.
* Such quests usually require some conditions can be checked at client-side,
* such as: specified composition of ships, have xxx resources / equipment...
*
* @param questId - the api_id of quest to be checked
* @param extraContexts - extra context object, eg: fleet num to be sent to sortie
* @see https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E3%82%AF%E3%83%A9%E3%82%A4%E3%82%A2%E3%83%B3%E3%83%88%E5%81%B4%E3%81%A7%E9%81%94%E6%88%90%E5%88%A4%E5%AE%9A%E3%81%8C%E3%81%AA%E3%81%95%E3%82%8C%E3%82%8B%E4%BB%BB%E5%8B%99
* @see `Kcsapi.resultScreenQuestFulfillment` about conditions of sortie and battles.
* @return true if current state fulfill the prerequisites of the quest; false if not.
* undefined if condition of specified quest is undefined.
*
* Should move this to an independent module if condition library grows bigger.
*/
isPrerequisiteFulfilled(questId, extraContexts = {}){
var questObj = this.get(questId);
// Definitions of prerequisites, not take 'tracking' counts into account here.
// Just give some typical samples, not completed for all period quests yet.
var questCondsLibrary = {
"249": // Bm1 Sortie a fleet has: Myoukou, Nachi, Haguro
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip(62) && fleet.hasShip(63) && fleet.hasShip(65);
},
"257": // Bm3 Sortie CL as flagship, 0-2 more CL and 1 DD at least, no other ship type
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType(3, 0)
&& fleet.countShipType(3) <= 3
&& fleet.countShipType(2) >= 1
// Progress not counted in-game if there is ETS FCF retreated ship, so use KCKai vita logic to simulate
//&& fleet.countShipType([2, 3], true) === 0;
&& fleet.countShipType([2, 3], false, true) === fleet.countShips(false);
},
"259": // Bm4 Sortie 3 BB (4 classes below only) and 1 CL
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShipClass([
37, // Yamato-class
19, // Nagato-class
2, // Ise-class
26, // Fusou-class
]) === 3 && fleet.countShipType(3) === 1;
},
"280": // Bm8 Sortie 1 CVL/CL(T)/CT and 3 DD/DE
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([3, 4, 7, 21])
&& fleet.countShipType([1, 2]) >= 3;
},
"284": // Bq11 Sortie 1 CVL/CL(T)/CT and 3 DD/DE
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([3, 4, 7, 21])
&& fleet.countShipType([1, 2]) >= 3;
},
"318": // C16 PvP with 2 more CLs in 1st fleet
() => {
const firstFleet = PlayerManager.fleets[0];
return KC3SortieManager.isPvP() && KC3SortieManager.fleetSent == 1 &&
firstFleet.countShipType(3) >= 2;
},
"330": // C29 PvP with CV(L/B) as flagship, 1 more CV(L/B) and 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() &&
fleet.hasShipType([7, 11, 18], 0) &&
fleet.countShipType([7, 11, 18]) >= 2 &&
fleet.countShipType(2) >= 2;
},
"337": // C38 PvP with Arare, Kagerou, Kasumi, Shiranui
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip(17) // Kagerou any remodel
&& fleet.hasShip(18) // Shiranui any remodel
&& fleet.hasShip(48) // Arare any remodel
&& fleet.hasShip(49); // Kasumi any remodel
},
"339": // C42 PvP with Isonami, Uranami, Ayanami, Shikinami
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip(12) // Isonami any remodel
&& fleet.hasShip(13) // Ayanami any remodel
&& fleet.hasShip(14) // Shikinami any remodel
&& fleet.hasShip(486); // Uranami any remodel
},
"342": // C44 PvP with 3 DD/DE and 1 more DD/DE/CL(T)/CT
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() && (
fleet.countShipType([1, 2]) >= 4 ||
fleet.countShipType([1, 2]) >= 3 &&
fleet.hasShipType([3, 4, 21])
);
},
"345": // C49 PvP with 4 of Warspite, Kongou, Ark Royal, Nelson, J-Class DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() && (
fleet.countShip(439) + // Warspite any remodel
fleet.countShip(78) + // Kongou any remodel
fleet.countShip(515) + // Ark Royal any remodel
fleet.countShip(571) + // Nelson any remodel
fleet.countShipClass(82) // J-Class any remodel
) >= 4;
},
"346": // C50 PvP with Yuugumo K2, Makigumo K2, Kazagumo K2, Akigumo K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip([542]) // Yuugumo K2
&& fleet.hasShip([563]) // Makigumo K2
&& fleet.hasShip([564]) // Kazagumo K2
&& fleet.hasShip([648]); // Akigumo K2
},
"348": // C53 PvP with CL/CT as flagship, 2 more CL(T)/CT, 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShipType([3, 21], 0)
&& fleet.countShipType([3, 4, 21]) >= 3
&& fleet.countShipType(2) >= 2;
},
"350": // C55 PvP with Oboro, Akebono, Sazanami, Ushio
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip(15) // Akebono any remodel
&& fleet.hasShip(16) // Ushio any remodel
&& fleet.hasShip(93) // Oboro any remodel
&& fleet.hasShip(94); // Sazanami any remodel
},
"353": // C58 PvP with CA(V) as flagship, 3 more CA(V), 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShipType([5, 6], 0)
&& fleet.countShipType([5, 6]) >= 4
&& fleet.countShipType(2) >= 2;
},
"354": // C60 PvP with Gambier Bay Mk.II as flagship, 2 Fletcher-class, John C.Butler-class DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip([707], 0)
&& fleet.countShipClass([87, 91]) >= 2;
},
"355": // C62 PvP with Kuroshio K2/Oyashio K2 as flagship, another ship as 2nd ship
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip([568, 670], 0)
&& fleet.hasShip([670, 568], 1);
},
"356": // C65 PvP with Isonami K2, Uranami K2, Ayanami K2, Shikinami K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip([666]) // Isonami K2
&& fleet.hasShip([647]) // Uranami K2
&& fleet.hasShip([195]) // Ayanami K2
&& fleet.hasShip([627]); // Shikinami K2
},
"357": // C66 PvP with Yamato, Musashi, 1 CL, 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip(131) // Yamato any remodel
&& fleet.hasShip(143) // Musashi any remodel
&& fleet.countShipType(3) >= 1
&& fleet.countShipType(2) >= 2;
},
"362": // C72 PvP with Fubuki, Shirayuki, Hatsuyuki, Miyuki
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP()
&& fleet.hasShip(9) // Fubuki any remodel
&& fleet.hasShip(10) // Shirayuki any remodel
&& fleet.hasShip(32) // Hatsuyuki any remodel
&& fleet.hasShip(11); // Miyuki any remodel
},
"368": // Cy11 PvP with 2 of Amatsukaze, Yukikaze, Tokitsukaze, Hatsukaze
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() && (
fleet.countShip(181) + // Amatsukaze any remodel
fleet.countShip(20) + // Yukikaze any remodel
fleet.countShip(186) + // Tokitsukaze any remodel
fleet.countShip(190) // Hatsukaze any remodel
) >= 2;
},
"371": // Cy12 PvP with Harusame as flagship, 3 of Murasame, Yuudachi, Samidare, Shiratsuyu, Shigure
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() &&
fleet.hasShip(405, 0) && ( // Harusame flagship
fleet.countShip(44) + // Murasame any remodel
fleet.countShip(45) + // Yuudachi any remodel
fleet.countShip(46) + // Samidare any remodel
fleet.countShip(42) + // Shiratsuyu any remodel
fleet.countShip(43) // Shigure any remodel
) >= 3;
},
"372": // Cy13 PvP with Akizuki-class as flagship, 2 DD, 2 BBV
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() &&
fleet.hasShipClass(54, 0) && // Akizuki-class
fleet.countShipType(2) >= 3 && // 3 DD in total
fleet.countShipType(10) >= 2;
},
"373": // Cy14 PvP with French ship as flagship, 2 more French ships
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() &&
fleet.hasShipClass(KC3Meta.ctypesByCountryName("France"), 0) && // French flagship
fleet.countShipClass(KC3Meta.ctypesByCountryName("France")) >= 3; // 3 French ships in total
},
"375": // Cy15 PvP with Hiei, Kirishima, 1 CL, 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() &&
fleet.hasShip(86) && // Hiei any remodel
fleet.hasShip(85) && // Kirishima any remodel
fleet.countShipType(3) >= 1 &&
fleet.countShipType(2) >= 2;
},
"377": // Cy16 PvP with Hayashimo/Akishimo/Kiyoshimo as flagship, 2 of Hayashimo/Akishimo/Kiyoshimo/Asashimo
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return KC3SortieManager.isPvP() && (
fleet.hasShip(409, 0) // Hayashimo any remodel
|| fleet.hasShip(625, 0) // Akishimo any remodel
|| fleet.hasShip(410, 0) // Kiyoshimo any remodel
) && (fleet.countShip(409) // Hayashimo any remodel
+ fleet.countShip(625) // Akishimo any remodel
+ fleet.countShip(410) // Kiyoshimo any remodel
+ fleet.countShip(425) // Asashimo any remodel
) >= 3; // including flagship
},
"626": // F22 Have 1 Skilled Crew Member. Houshou as secretary, equip her with a >> Type 0 Fighter Model 21
() => {
const firstFleet = PlayerManager.fleets[0];
const isMaxProType0Model21Equipped = firstFleet.ship(0)
.equipment().some(gear => gear.masterId === 20 && gear.ace >= 7);
return PlayerManager.consumables.skilledCrew >= 1
&& firstFleet.hasShip(89, 0)
&& isMaxProType0Model21Equipped;
},
"643": // F32 Have 1 Type 96 Land-based Attack Aircraft and 2 Type 97 Torpedo Bombers
() => (KC3GearManager.countFree(168) >= 1
&& KC3GearManager.countFree(16) >= 2
),
"645": // F41 Have 750 fuel, 750 ammo, 2 Drum Canisters and 1 Type 91 AP Shell
() => (PlayerManager.hq.lastMaterial[0] >= 750
&& PlayerManager.hq.lastMaterial[1] >= 750
&& KC3GearManager.countFree(75) >= 2
&& KC3GearManager.countFree(36) >= 1
),
"654": // F93 Have 1 Skilled Crew Member, 1500 ammo, 1500 bauxite. Ary Royal as secretary, equip her 1st slot with a maxed star Swordfish
() => {
const firstFleet = PlayerManager.fleets[0];
const firstSlotGear = firstFleet.ship(0).equipment(0);
const isMaxSwordfishEquipped = firstSlotGear.masterId === 242 && firstSlotGear.stars >= 10;
return PlayerManager.hq.lastMaterial[1] >= 1500
&& PlayerManager.hq.lastMaterial[4] >= 1500
&& PlayerManager.consumables.skilledCrew >= 1
&& firstFleet.hasShip(515, 0)
&& isMaxSwordfishEquipped;
},
"663": // F55/Fq3 Have 18000 steel (scrapping not counted here, unused)
() => PlayerManager.hq.lastMaterial[2] >= 18000,
"1123": // Fy10 Have 950 bauxite, 2 New Model Aviation Armament Materials, 2 Skilled Crew Members. Tone Kai Ni/Yura Kai Ni as secretary, 1st slot with a maxed Type 0 Reconnaissance Seaplane (scrapping only checks secretary, unused)
() => {
const firstFleet = PlayerManager.fleets[0];
const firstSlotGear = firstFleet.ship(0).equipment(0);
const isMaxType0ReconSeaplaneEquipped = firstSlotGear.masterId === 25 && firstSlotGear.stars >= 10;
return PlayerManager.hq.lastMaterial[4] >= 950
&& PlayerManager.consumables.newArmamentMaterial >= 2
&& PlayerManager.consumables.skilledCrew >= 2
&& firstFleet.hasShip([188, 488], 0)
&& isMaxType0ReconSeaplaneEquipped;
},
"1138": // Fy11 Have 1300 bauxite, 480 steel, 4 buckets and 16 Development Materials. Akizuki-class as secretary (scrapping only checks secretary, unsed)
() => {
const firstFleet = PlayerManager.fleets[0];
return PlayerManager.hq.lastMaterial[3] >= 480
&& PlayerManager.hq.lastMaterial[4] >= 1300
&& PlayerManager.consumables.buckets >= 4
&& PlayerManager.consumables.devmats >= 16
&& firstFleet.hasShipClass(54, 0);
},
"854": // Bq2 Sortie 1st fleet (sortie maps and battle ranks not counted here)
() => KC3SortieManager.isOnSortie() && KC3SortieManager.fleetSent == 1,
"861": // Bq3 Sortie 2 of BBV or AO
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return (fleet.countShipType(10) +
fleet.countShipType(22)) >= 2;
},
"862": // Bq4 Sortie 1 AV, 2 CL
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType(16)
&& fleet.countShipType(3) >= 2;
},
"872": // Bq10 Sortie 1st fleet
() => KC3SortieManager.isOnSortie() && KC3SortieManager.fleetSent == 1,
"873": // Bq5 Sortie 1 CL
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType(3);
},
"875": // Bq6 Sortie DesDiv 31
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip([543]) // Naganami K2
&& fleet.hasShip([
345, 649, // Takanami Kai/K2
359, 569, // Okinami Kai/K2
344, 578, // Asashimo Kai/K2
]);
},
"888": // Bq7 Sortie New Mikawa Fleet
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShip(69) + // Choukai any remodel
fleet.countShip(61) + // Aoba any remodel
fleet.countShip(123) + // Kinugasa any remodel
fleet.countShip(60) + // Kako any remodel
fleet.countShip(59) + // Furutaka any remodel
fleet.countShip(51) + // Tenryuu any remodel
fleet.countShip(115) // Yuubari any remodel
>= 4;
},
"894": // Bq9 Sortie 1 CV(L/B)
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([7, 11, 18]);
},
"903": // Bq13 Sortie Yuubari K2+ as flagship, 2 of 6th Torpedo Squad, or Yura K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
// Yuubari Kai Ni any variant as flagship
return RemodelDb.remodelGroup(115).indexOf(fleet.ship(0).masterId) >= 2 && ((
fleet.countShip(1) + // Mutsuki any remodel
fleet.countShip(2) + // Kisaragi any remodel
fleet.countShip(30) + // Kikuzuki any remodel
fleet.countShip(31) + // Mochizuki any remodel
fleet.countShip(164) + // Yayoi any remodel
fleet.countShip(165) // Uzuki any remodel
) >= 2 || (
fleet.hasShip([488]) // Yura K2
));
},
"904": // By1 Sortie Ayanami K2, Shikinami K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip([
195, // Ayanami K2
627, // Shikinami K2
]);
},
"905": // By2 Sortie 3 DE, up to 5 ships
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShipType(1) >= 3 && fleet.countShips() <= 5;
},
"912": // By3 Sortie Akashi as flagship, 3 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType(19, 0) && fleet.countShipType(2) >= 3;
},
"914": // By4 Sortie 3 CA, 1 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShipType(5) >= 3 && fleet.countShipType(2) >= 1;
},
"928": // By5 Sortie 2 of Haguro/Ashigara/Myoukou/Takao/Kamikaze
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return (
fleet.countShip(65) + // Haguro any remodel
fleet.countShip(64) + // Ashigara any remodel
fleet.countShip(62) + // Myoukou any remodel
fleet.countShip(66) + // Takao any remodel
fleet.countShip(471) // Kamikaze any remodel
) >= 2;
},
"944": // By6 Sortie CA/DD as flagship, 3 DD/DE (excluding flagship DD)
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([2, 5], 0)
&& (fleet.hasShipType(2, 0) ?
fleet.countShipType(1) + (fleet.countShipType(2) - 1) >= 3 :
fleet.countShipType([1, 2]) >= 3);
},
"945": // By7 Sortie CL/CT/DD as flagship, 3 DD/DE (excluding flagship DD)
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([2, 3, 21], 0)
&& (fleet.hasShipType(2, 0) ?
fleet.countShipType(1) + (fleet.countShipType(2) - 1) >= 3 :
fleet.countShipType([1, 2]) >= 3);
},
"946": // By8 Sortie CV(L/B) as flagship, 2 CA(V)
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipType([7, 11, 18], 0)
&& fleet.countShipType([5, 6]) >= 2;
},
"947": // By9 Sortie 2 CVL
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShipType(7) >= 2;
},
"948": // By10 Sortie 1st fleet with CV(L/B) as flagship
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleetSent == 1 && fleet.hasShipType([7, 11, 18], 0);
},
"973": // By11 Sortie 3 American/British ships without any carrier
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.countShipType([7, 11, 18]) === 0
&& fleet.countShipClass(
KC3Meta.ctypesByCountryName("UnitedStates").concat(
KC3Meta.ctypesByCountryName("UnitedKingdom")
)
) >= 3;
},
"975": // By12 Sortie Isonami K2, Uranami K2, Ayanami K2, Shikinami K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip([666]) // Isonami K2
&& fleet.hasShip([647]) // Uranami K2
&& fleet.hasShip([195]) // Ayanami K2
&& fleet.hasShip([627]); // Shikinami K2
},
"1005": // By13 Sortie Oboro K, Sazanami K, Akebono K/K2, Ushio K/K2
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip([231, 665]) // Akebono
&& fleet.hasShip([233, 407]) // Ushio
&& fleet.hasShip([230]) // Oboro
&& fleet.hasShip([232]); // Sazanami
},
"1012": // By14 Sortie Ukuru-class as flagship, 3 DE (excluding flagship DE), no other ship type
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShipClass(117, 0)
&& fleet.countShipType(1) <= 4
&& fleet.countShipType(1, true, false) === 0;
},
"1018": // By15 Sortie Hiei, Kirishima, 2 DD
({fleetSent = KC3SortieManager.fleetSent}) => {
const fleet = PlayerManager.fleets[fleetSent - 1];
return fleet.hasShip(85) // Kirishima
&& fleet.hasShip(86) // Hiei
&& fleet.countShipType(2) >= 2;
},
};
if(questObj.id && questCondsLibrary[questId]){
return !!questCondsLibrary[questId].call(questObj, extraContexts);
}
// if no condition definition found, return undefined as 'unknown'
return;
},
/* SAVE
Write current quest data to localStorage
------------------------------------------*/
save :function(){
// Store only the list. The actives and opens will be redefined on load()
localStorage.quests = JSON.stringify(this.list);
// Check if synchronization is enabled and quests list is not empty
ConfigManager.loadIfNecessary();
if (ConfigManager.chromeSyncQuests && Object.notEmpty(this.list)) {
const now = Date.now();
KC3QuestSync.save(Object.assign(KC3QuestManager.getRepeatableResetTimes(now), {
quests: localStorage.quests,
syncTimeStamp: now,
}));
}
},
getRepeatableResetTimes: function (timestamp) {
return KC3QuestManager.getRepeatableTypes().reduce((result, { type, key }) => {
result[key] = KC3QuestManager.getResetTime(type, timestamp);
return result;
}, {});
},
/* LOAD
Read and refill list from localStorage
------------------------------------------*/
load :function(){
if(typeof localStorage.quests != "undefined"){
var tempQuests = JSON.parse(localStorage.quests);
this.list = {};
var tempQuest;
// Empty actives and opens since they will be re-added
this.active = [];
this.open = [];
for(var ctr in tempQuests){
tempQuest = tempQuests[ctr];
// Add to actives or opens depending on status
switch( tempQuest.status ){
case 1: // Unselected
this.isOpen( tempQuest.id, true );
this.isActive( tempQuest.id, false );
break;
case 2: // Selected
this.isOpen( tempQuest.id, true );
this.isActive( tempQuest.id, true );
break;
case 3: // Completed
this.isOpen( tempQuest.id, false );
this.isActive( tempQuest.id, false );
break;
default:
this.isOpen( tempQuest.id, false );
this.isActive( tempQuest.id, false );
break;
}
// Add to manager's main list using Quest object
this.list["q"+tempQuest.id] = new KC3Quest();
this.list["q"+tempQuest.id].define( tempQuest );
}
// console.info("Quest management data loaded");
return true;
}
return false;
},
mergeSyncData: function (remoteData) {
var localQuests = KC3QuestManager.removeExpiredRepeatables(KC3QuestManager.getLocalData());
var remoteQuests = KC3QuestManager.removeExpiredRepeatables(remoteData);
var quests = KC3QuestManager.mergeQuests(remoteQuests, localQuests);
KC3QuestManager.saveToLocal(quests, remoteData);
},
getLocalData: function () {
return $.extend(KC3QuestManager.getRepeatableResetTimes(Date.now()), {
quests: localStorage.quests || JSON.stringify({}),
});
},
// Discard data for repeatable quests that have passed their reset time
removeExpiredRepeatables: function (data) {
var now = Date.now();
return KC3QuestManager.getRepeatableTypes().reduce(function (quests, { key, type }) {
var resetTime = parseInt(data[key], 10) || -1;
if (now >= resetTime) {
return KC3QuestManager.removeQuests(quests, KC3QuestManager.getRepeatableIds(type));
}
return quests;
}, JSON.parse(data.quests));
},
removeQuests: function (quests, ids) {
return ids.reduce(function (result, id) {
result["q" + id] = null;
return result;
}, quests);
},
mergeQuests: function (remoteQuests, localQuests) {
var ids = KC3QuestManager.getIdList(remoteQuests, localQuests);
return ids.reduce(function (result, id) {
var newState = KC3QuestManager.mergeQuestState(remoteQuests[id], localQuests[id]);
if (newState) { result[id] = newState; }
return result;
}, {});
},
getIdList: function (remoteQuests, localQuests) {
return Object.keys(localQuests).reduce(function (result, id) {
if (!remoteQuests[id]) {
result.push(id);
}
return result;
}, Object.keys(remoteQuests));
},
mergeQuestState: function (remote, local) {
if (!remote) { return local; }
if (!local) { return remote; }
if (remote.status === 3 && local.status !== 3) { return remote; }
if (local.status === 3 && remote.status !== 3) { return local; }
var result = KC3QuestManager.compareTrackingState(remote, local);
if (result) { return result; }
if (remote.progress || local.progress) {
return (remote.progress || 0) > (local.progress || 0) ? remote : local;
}
return local;
},
compareTrackingState: function (remote, local) {
var isRemoteValid = KC3QuestManager.isTrackingValid(remote);
var isLocalValid = KC3QuestManager.isTrackingValid(local);
if (isRemoteValid && !isLocalValid) { return remote; }
if (isLocalValid && !isRemoteValid) { return local; }
if (!isRemoteValid && !isLocalValid) { return null; }
return KC3QuestManager.mergeTracking(remote, local);
},
// Check if the tracking property is defined correctly
isTrackingValid: function (quest) {
var meta = KC3Meta.quest(quest.id);
if (!Array.isArray(quest.tracking) || !meta || !Array.isArray(meta.tracking)) {
return false;
}
if (quest.tracking.length !== meta.tracking.length) {
return false;
}
return quest.tracking.every(function (actual, index) {
if (!actual || !Array.isArray(actual)) { return false; }
var expected = meta.tracking[index];
if (!expected || !Array.isArray(expected)) { return false; }
return actual.length === expected.length;
});
},
mergeTracking: function (remote, local) {
// since validation passed, we know the two tracking arrays have the same length
if (remote.tracking.length === 1) {
return KC3QuestManager.selectSingleStageTracking(remote, local);
} else if (remote.tracking.length >= 1) {
return KC3QuestManager.mergeMultiStageTracking(remote, local);
}
// should be unreachable
throw new Error('bad tracking array');
},
// Select the version with the higher progress
selectSingleStageTracking: function (remote, local) {
if (remote.tracking[0][0] > local.tracking[0][0]) {
return remote;
}
return local;
},
// Combine versions for quests with multi-stage tracking (e.g. Bw1)
mergeMultiStageTracking: function (remote, local) {
// NB: result.progress may be incorrect
// (shouldn't matter since multi-stage quests aren't auto-adjusted)
return remote.tracking.reduce(function (result, stage, index) {
result.tracking[index][0] = Math.max(stage[0], result.tracking[index][0]);
return result;
}, local);
},
saveToLocal: function (quests) {
localStorage.quests = JSON.stringify(quests);
KC3QuestManager.getRepeatableTypes().forEach(function ({ key }) {
localStorage.removeItem(key);
});
},
printError: function (e) {
KC3Log.console.error(e, e.stack);
},
};
})();
| 0 | 0.972706 | 1 | 0.972706 | game-dev | MEDIA | 0.663792 | game-dev | 0.952211 | 1 | 0.952211 |
bibigone/k4a.net | 2,409 | K4AdotNet/Sensor/DepthEngineHelper.cs | using System;
namespace K4AdotNet.Sensor
{
#if ORBBECSDK_K4A_WRAPPER
// Inspired by <c>depthengine_helper</c> class from <c>k4a.hpp</c>
//
/// <summary>Avoid deep engine initialization failures when using multiple OpenGL contexts within user applications and SDKs. OrbbecSDK-K4A-Wrapper only.</summary>
/// <remarks>This function only needs to be called when on the Linux platform</remarks>
public sealed class DepthEngineHelper : IDisposablePlus
{
/// <summary>Creates depthengine helper (OrbbecSDK-K4A-Wrapper only).</summary>
/// <returns>Created depthengine helper. Not <see langword="null"/>. To release, call <see cref="Dispose"/> method.</returns>
/// <exception cref="InvalidOperationException">Cannot create depthengine helper for some internal reason. For error details see logs.</exception>
public static DepthEngineHelper Create()
{
var res = NativeApi.DepthEngineHelperCreate(out var handle);
if (res != NativeCallResults.Result.Succeeded || !handle.IsValid)
throw new InvalidOperationException("Failed to create depthengine helper");
return new DepthEngineHelper(handle);
}
private readonly NativeHandles.HandleWrapper<NativeHandles.DepthEngineHandle> handle; // This class is an wrapper around this native handle
private DepthEngineHelper(NativeHandles.DepthEngineHandle handle)
{
this.handle = handle;
this.handle.Disposed += Handle_Disposed;
}
private void Handle_Disposed(object? sender, EventArgs e)
{
handle.Disposed -= Handle_Disposed;
Disposed?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Call this method to release depthengine helper and free all unmanaged resources associated with current instance.
/// </summary>
/// <seealso cref="Disposed"/>
/// <seealso cref="IsDisposed"/>
public void Dispose()
=> handle.Dispose();
/// <summary>Gets a value indicating whether the object has been disposed of.</summary>
/// <seealso cref="Dispose"/>
public bool IsDisposed => handle.IsDisposed;
/// <summary>Raised on object disposing (only once).</summary>
/// <seealso cref="Dispose"/>
public event EventHandler? Disposed;
}
#endif
}
| 0 | 0.841304 | 1 | 0.841304 | game-dev | MEDIA | 0.632166 | game-dev | 0.706416 | 1 | 0.706416 |
Blood-Asp/GT5-Unofficial | 3,056 | src/main/java/gregtech/common/covers/GT_Cover_RedstoneConductor.java | package gregtech.common.covers;
import gregtech.api.interfaces.tileentity.ICoverable;
import gregtech.api.util.GT_CoverBehavior;
import gregtech.api.util.GT_Utility;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fluids.Fluid;
public class GT_Cover_RedstoneConductor
extends GT_CoverBehavior {
public int doCoverThings(byte aSide, byte aInputRedstone, int aCoverID, int aCoverVariable, ICoverable aTileEntity, long aTimer) {
if (aCoverVariable == 0) {
aTileEntity.setOutputRedstoneSignal(aSide, aTileEntity.getStrongestRedstone());
} else if (aCoverVariable < 7) {
aTileEntity.setOutputRedstoneSignal(aSide, aTileEntity.getInternalInputRedstoneSignal((byte) (aCoverVariable - 1)));
}
return aCoverVariable;
}
public int onCoverScrewdriverclick(byte aSide, int aCoverID, int aCoverVariable, ICoverable aTileEntity, EntityPlayer aPlayer, float aX, float aY, float aZ) {
aCoverVariable = (aCoverVariable + (aPlayer.isSneaking()? -1 : 1)) % 7;
if(aCoverVariable <0){aCoverVariable = 6;}
switch (aCoverVariable) {
case 0: GT_Utility.sendChatToPlayer(aPlayer, trans("071", "Conducts strongest Input")); break;
case 1: GT_Utility.sendChatToPlayer(aPlayer, trans("072", "Conducts from bottom Input")); break;
case 2: GT_Utility.sendChatToPlayer(aPlayer, trans("073", "Conducts from top Input")); break;
case 3: GT_Utility.sendChatToPlayer(aPlayer, trans("074", "Conducts from north Input")); break;
case 4: GT_Utility.sendChatToPlayer(aPlayer, trans("075", "Conducts from south Input")); break;
case 5: GT_Utility.sendChatToPlayer(aPlayer, trans("076", "Conducts from west Input")); break;
case 6: GT_Utility.sendChatToPlayer(aPlayer, trans("077", "Conducts from east Input")); break;
}
return aCoverVariable;
}
public boolean letsEnergyIn(byte aSide, int aCoverID, int aCoverVariable, ICoverable aTileEntity) {
return true;
}
public boolean letsEnergyOut(byte aSide, int aCoverID, int aCoverVariable, ICoverable aTileEntity) {
return true;
}
public boolean letsFluidIn(byte aSide, int aCoverID, int aCoverVariable, Fluid aFluid, ICoverable aTileEntity) {
return true;
}
public boolean letsFluidOut(byte aSide, int aCoverID, int aCoverVariable, Fluid aFluid, ICoverable aTileEntity) {
return true;
}
public boolean letsItemsIn(byte aSide, int aCoverID, int aCoverVariable, int aSlot, ICoverable aTileEntity) {
return true;
}
public boolean letsItemsOut(byte aSide, int aCoverID, int aCoverVariable, int aSlot, ICoverable aTileEntity) {
return true;
}
public boolean manipulatesSidedRedstoneOutput(byte aSide, int aCoverID, int aCoverVariable, ICoverable aTileEntity) {
return true;
}
public int getTickRate(byte aSide, int aCoverID, int aCoverVariable, ICoverable aTileEntity) {
return 1;
}
}
| 0 | 0.826585 | 1 | 0.826585 | game-dev | MEDIA | 0.752356 | game-dev | 0.615928 | 1 | 0.615928 |
google/note-maps | 3,131 | flutter/nm_gql_go_link/linux/nm_gql_go_link_plugin.cc | // Copyright 2020-2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "include/nm_gql_go_link/nm_gql_go_link_plugin.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <sys/utsname.h>
#define NM_GQL_GO_LINK_PLUGIN(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj), nm_gql_go_link_plugin_get_type(), \
NmGqlGoLinkPlugin))
struct _NmGqlGoLinkPlugin {
GObject parent_instance;
};
G_DEFINE_TYPE(NmGqlGoLinkPlugin, nm_gql_go_link_plugin, g_object_get_type())
// Called when a method call is received from Flutter.
static void nm_gql_go_link_plugin_handle_method_call(
NmGqlGoLinkPlugin* self,
FlMethodCall* method_call) {
g_autoptr(FlMethodResponse) response = nullptr;
const gchar* method = fl_method_call_get_name(method_call);
if (strcmp(method, "getPlatformVersion") == 0) {
struct utsname uname_data = {};
uname(&uname_data);
g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version);
g_autoptr(FlValue) result = fl_value_new_string(version);
response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
fl_method_call_respond(method_call, response, nullptr);
}
static void nm_gql_go_link_plugin_dispose(GObject* object) {
G_OBJECT_CLASS(nm_gql_go_link_plugin_parent_class)->dispose(object);
}
static void nm_gql_go_link_plugin_class_init(NmGqlGoLinkPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = nm_gql_go_link_plugin_dispose;
}
static void nm_gql_go_link_plugin_init(NmGqlGoLinkPlugin* self) {}
static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
gpointer user_data) {
NmGqlGoLinkPlugin* plugin = NM_GQL_GO_LINK_PLUGIN(user_data);
nm_gql_go_link_plugin_handle_method_call(plugin, method_call);
}
void nm_gql_go_link_plugin_register_with_registrar(FlPluginRegistrar* registrar) {
NmGqlGoLinkPlugin* plugin = NM_GQL_GO_LINK_PLUGIN(
g_object_new(nm_gql_go_link_plugin_get_type(), nullptr));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlMethodChannel) channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
"nm_gql_go_link",
FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(channel, method_call_cb,
g_object_ref(plugin),
g_object_unref);
g_object_unref(plugin);
}
| 0 | 0.866722 | 1 | 0.866722 | game-dev | MEDIA | 0.459024 | game-dev | 0.88123 | 1 | 0.88123 |
ProjectIgnis/CardScripts | 3,011 | official/c35552985.lua | --刻まれし魔の讃聖
--Fiendsmith's Sanct
--scripted by pyrQ
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_MAIN_END|TIMINGS_CHECK_MONSTER_E)
e1:SetCountLimit(1,id)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
--Set this card
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY,EFFECT_FLAG2_CHECK_SIMULTANEOUS)
e2:SetCode(EVENT_DESTROYED)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,{id,1})
e2:SetCondition(s.setcon)
e2:SetTarget(s.settg)
e2:SetOperation(s.setop)
c:RegisterEffect(e2)
end
s.listed_names={id+1}
s.listed_series={SET_FIENDSMITH}
function s.confilter(c)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FIEND)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,LOCATION_MZONE,0,nil)
return #g==0 or g:FilterCount(s.confilter,nil)==#g
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,id+1,SET_FIENDSMITH,TYPES_TOKEN,0,0,1,RACE_FIEND,ATTRIBUTE_LIGHT) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,id+1,SET_FIENDSMITH,TYPES_TOKEN,0,0,1,RACE_FIEND,ATTRIBUTE_LIGHT) then
local token=Duel.CreateToken(tp,id+1)
Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP)
end
local c=e:GetHandler()
--Cannot declare attacks for the rest of this turn, except with Fiend monsters
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(function(_,c) return not c:IsRace(RACE_FIEND) end)
e1:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e1,tp)
aux.RegisterClientHint(c,nil,tp,1,0,aux.Stringid(id,2))
end
function s.setconfilter(c,tp)
return c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_MZONE) and c:IsPreviousPosition(POS_FACEUP)
and c:IsPreviousSetCard(SET_FIENDSMITH) and c:IsReason(REASON_EFFECT)
end
function s.setcon(e,tp,eg,ep,ev,re,r,rp)
return rp==1-tp and not eg:IsContains(e:GetHandler()) and eg:IsExists(s.setconfilter,1,nil,tp)
end
function s.settg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsSSetable() end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,c,1,tp,0)
end
function s.setop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsSSetable() then
Duel.SSet(tp,c)
end
end | 0 | 0.900993 | 1 | 0.900993 | game-dev | MEDIA | 0.989191 | game-dev | 0.909684 | 1 | 0.909684 |
taublast/DrawnUi | 6,125 | src/Shared/Internals/Helpers/KeyedActionQueue.cs | namespace DrawnUi.Draw
{
/// <summary>
/// Ultra-fast key generator for queues using long keys
/// </summary>
public static class LongKeyGenerator
{
private static long _counter = 0;
/// <summary>
/// Generates next unique key (thread-safe, fastest option)
/// </summary>
public static long Next() => Interlocked.Increment(ref _counter);
/// <summary>
/// Generates key with thread distribution for better performance under high contention
/// </summary>
public static long NextThreadDistributed()
{
var threadId = (uint)Environment.CurrentManagedThreadId;
var counter = (uint)Interlocked.Increment(ref _counter);
return ((long)threadId << 32) | counter;
}
/// <summary>
/// Encodes semantic string directly to long (up to 8 chars, case-sensitive)
/// </summary>
public static unsafe long EncodeSemantic(string semantic)
{
if (semantic.Length == 0) return 0;
long result = 0;
int len = Math.Min(semantic.Length, 8);
fixed (char* ptr = semantic)
{
for (int i = 0; i < len; i++)
{
result |= ((long)(ptr[i] & 0xFF)) << (i * 8);
}
}
return result;
}
}
public class KeyedActionQueue<TKey> where TKey : notnull
{
private class ActionNode
{
public TKey Key;
public Action Action;
public ActionNode? Next;
public ActionNode? Previous;
public ActionNode(TKey key, Action action)
{
Key = key;
Action = action;
}
}
private readonly Dictionary<TKey, ActionNode> _lookup;
private readonly object _lock = new();
private ActionNode? _head;
private ActionNode? _tail;
private int _count;
/// <summary>
/// Initializes a new instance of the FastKeyedActionQueue with specified initial capacity
/// </summary>
public KeyedActionQueue(int capacity = 1024)
{
_lookup = new Dictionary<TKey, ActionNode>(capacity);
}
/// <summary>
/// Enqueues an action with a key, removing any existing action with the same key
/// </summary>
public void Enqueue(TKey key, Action action)
{
var newNode = new ActionNode(key, action);
lock (_lock)
{
// Remove existing node if present
if (_lookup.TryGetValue(key, out var existingNode))
{
RemoveNodeUnsafe(existingNode);
_count--;
}
// Add new node to tail
if (_tail == null)
{
_head = _tail = newNode;
}
else
{
_tail.Next = newNode;
newNode.Previous = _tail;
_tail = newNode;
}
_lookup[key] = newNode;
_count++;
}
}
/// <summary>
/// Dequeues the next action in FIFO order
/// </summary>
public Action? Dequeue()
{
lock (_lock)
{
if (_head == null) return null;
var node = _head;
RemoveNodeUnsafe(node);
_lookup.Remove(node.Key);
_count--;
return node.Action;
}
}
/// <summary>
/// Gets the current count of queued actions
/// </summary>
public int Count
{
get
{
lock (_lock)
{
return _count;
}
}
}
/// <summary>
/// Removes all queued actions
/// </summary>
public void Clear()
{
lock (_lock)
{
_head = _tail = null;
_lookup.Clear();
_count = 0;
}
}
/// <summary>
/// Checks if a key exists in the queue
/// </summary>
public bool ContainsKey(TKey key)
{
lock (_lock)
{
return _lookup.ContainsKey(key);
}
}
/// <summary>
/// Tries to remove an action by key
/// </summary>
public bool TryRemove(TKey key)
{
lock (_lock)
{
if (_lookup.TryGetValue(key, out var node))
{
RemoveNodeUnsafe(node);
_lookup.Remove(key);
_count--;
return true;
}
return false;
}
}
/// <summary>
/// Dequeues and executes all actions in FIFO order
/// </summary>
public void ExecuteAll()
{
ActionNode? current;
lock (_lock)
{
current = _head;
_head = _tail = null;
_lookup.Clear();
_count = 0;
}
// Execute outside the lock
while (current != null)
{
var next = current.Next;
try
{
current.Action();
}
catch (Exception e)
{
Super.Log(e);
}
current = next;
}
}
private void RemoveNodeUnsafe(ActionNode node)
{
if (node.Previous != null)
node.Previous.Next = node.Next;
else
_head = node.Next;
if (node.Next != null)
node.Next.Previous = node.Previous;
else
_tail = node.Previous;
}
}
}
| 0 | 0.91735 | 1 | 0.91735 | game-dev | MEDIA | 0.110531 | game-dev | 0.985106 | 1 | 0.985106 |
mangosArchives/Mangos-Zero-server-old | 22,177 | src/game/MovementHandler.cpp | /*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "Log.h"
#include "Corpse.h"
#include "Player.h"
#include "MapManager.h"
#include "Transports.h"
#include "BattleGround.h"
#include "WaypointMovementGenerator.h"
#include "MapPersistentStateMgr.h"
#include "ObjectMgr.h"
void WorldSession::HandleMoveWorldportAckOpcode(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: got MSG_MOVE_WORLDPORT_ACK.");
HandleMoveWorldportAckOpcode();
}
void WorldSession::HandleMoveWorldportAckOpcode()
{
// ignore unexpected far teleports
if (!GetPlayer()->IsBeingTeleportedFar())
return;
// get start teleport coordinates (will used later in fail case)
WorldLocation old_loc;
GetPlayer()->GetPosition(old_loc);
// get the teleport destination
WorldLocation &loc = GetPlayer()->GetTeleportDest();
// possible errors in the coordinate validity check (only cheating case possible)
if (!MapManager::IsValidMapCoord(loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z, loc.orientation))
{
sLog.outError("WorldSession::HandleMoveWorldportAckOpcode: %s was teleported far to a not valid location "
"(map:%u, x:%f, y:%f, z:%f) We port him to his homebind instead..",
GetPlayer()->GetGuidStr().c_str(), loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z);
// stop teleportation else we would try this again and again in LogoutPlayer...
GetPlayer()->SetSemaphoreTeleportFar(false);
// and teleport the player to a valid place
GetPlayer()->TeleportToHomebind();
return;
}
// get the destination map entry, not the current one, this will fix homebind and reset greeting
MapEntry const* mEntry = sMapStore.LookupEntry(loc.mapid);
Map* map = NULL;
// prevent crash at attempt landing to not existed battleground instance
if (mEntry->IsBattleGround())
{
if (GetPlayer()->GetBattleGroundId())
map = sMapMgr.FindMap(loc.mapid, GetPlayer()->GetBattleGroundId());
if (!map)
{
DETAIL_LOG("WorldSession::HandleMoveWorldportAckOpcode: %s was teleported far to nonexisten battleground instance "
" (map:%u, x:%f, y:%f, z:%f) Trying to port him to his previous place..",
GetPlayer()->GetGuidStr().c_str(), loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z);
GetPlayer()->SetSemaphoreTeleportFar(false);
// Teleport to previous place, if cannot be ported back TP to homebind place
if (!GetPlayer()->TeleportTo(old_loc))
{
DETAIL_LOG("WorldSession::HandleMoveWorldportAckOpcode: %s cannot be ported to his previous place, teleporting him to his homebind place...",
GetPlayer()->GetGuidStr().c_str());
GetPlayer()->TeleportToHomebind();
}
return;
}
}
InstanceTemplate const* mInstance = ObjectMgr::GetInstanceTemplate(loc.mapid);
// reset instance validity, except if going to an instance inside an instance
if (GetPlayer()->m_InstanceValid == false && !mInstance)
GetPlayer()->m_InstanceValid = true;
GetPlayer()->SetSemaphoreTeleportFar(false);
// relocate the player to the teleport destination
if (!map)
map = sMapMgr.CreateMap(loc.mapid, GetPlayer());
GetPlayer()->SetMap(map);
GetPlayer()->Relocate(loc.coord_x, loc.coord_y, loc.coord_z, loc.orientation);
GetPlayer()->SendInitialPacketsBeforeAddToMap();
// the CanEnter checks are done in TeleporTo but conditions may change
// while the player is in transit, for example the map may get full
if (!GetPlayer()->GetMap()->Add(GetPlayer()))
{
// if player wasn't added to map, reset his map pointer!
GetPlayer()->ResetMap();
DETAIL_LOG("WorldSession::HandleMoveWorldportAckOpcode: %s was teleported far but couldn't be added to map "
" (map:%u, x:%f, y:%f, z:%f) Trying to port him to his previous place..",
GetPlayer()->GetGuidStr().c_str(), loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z);
// Teleport to previous place, if cannot be ported back TP to homebind place
if (!GetPlayer()->TeleportTo(old_loc))
{
DETAIL_LOG("WorldSession::HandleMoveWorldportAckOpcode: %s cannot be ported to his previous place, teleporting him to his homebind place...",
GetPlayer()->GetGuidStr().c_str());
GetPlayer()->TeleportToHomebind();
}
return;
}
// battleground state prepare (in case join to BG), at relogin/tele player not invited
// only add to bg group and object, if the player was invited (else he entered through command)
if (_player->InBattleGround())
{
// cleanup seting if outdated
if (!mEntry->IsBattleGround())
{
// We're not in BG
_player->SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE);
// reset destination bg team
_player->SetBGTeam(TEAM_NONE);
}
// join to bg case
else if (BattleGround *bg = _player->GetBattleGround())
{
if (_player->IsInvitedForBattleGroundInstance(_player->GetBattleGroundId()))
bg->AddPlayer(_player);
}
}
GetPlayer()->SendInitialPacketsAfterAddToMap();
// flight fast teleport case
if (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE)
{
if (!_player->InBattleGround())
{
// short preparations to continue flight
FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top());
flight->Reset(*GetPlayer());
return;
}
// battleground state prepare, stop flight
GetPlayer()->GetMotionMaster()->MovementExpired();
GetPlayer()->m_taxi.ClearTaxiDestinations();
}
if (mEntry->IsRaid() && mInstance)
{
if (time_t timeReset = sMapPersistentStateMgr.GetScheduler().GetResetTimeFor(mEntry->MapID))
{
uint32 timeleft = uint32(timeReset - time(NULL));
GetPlayer()->SendInstanceResetWarning(mEntry->MapID, timeleft);
}
}
// mount allow check
if (!mEntry->IsMountAllowed())
_player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
// honorless target
if (GetPlayer()->pvpInfo.inHostileArea)
GetPlayer()->CastSpell(GetPlayer(), 2479, true);
// resummon pet
GetPlayer()->ResummonPetTemporaryUnSummonedIfAny();
//lets process all delayed operations on successful teleport
GetPlayer()->ProcessDelayedOperations();
}
void WorldSession::HandleMoveTeleportAckOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("MSG_MOVE_TELEPORT_ACK");
ObjectGuid guid;
recv_data >> guid;
uint32 counter, time;
recv_data >> counter >> time;
DEBUG_LOG("Guid: %s", guid.GetString().c_str());
DEBUG_LOG("Counter %u, time %u", counter, time / IN_MILLISECONDS);
Unit *mover = _player->GetMover();
Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL;
if (!plMover || !plMover->IsBeingTeleportedNear())
return;
if (guid != plMover->GetObjectGuid())
return;
plMover->SetSemaphoreTeleportNear(false);
uint32 old_zone = plMover->GetZoneId();
WorldLocation const& dest = plMover->GetTeleportDest();
plMover->SetPosition(dest.coord_x, dest.coord_y, dest.coord_z, dest.orientation, true);
uint32 newzone, newarea;
plMover->GetZoneAndAreaId(newzone, newarea);
plMover->UpdateZone(newzone, newarea);
// new zone
if (old_zone != newzone)
{
// honorless target
if (plMover->pvpInfo.inHostileArea)
plMover->CastSpell(plMover, 2479, true);
}
// resummon pet
GetPlayer()->ResummonPetTemporaryUnSummonedIfAny();
//lets process all delayed operations on successful teleport
GetPlayer()->ProcessDelayedOperations();
}
void WorldSession::HandleMovementOpcodes(WorldPacket & recv_data)
{
uint32 opcode = recv_data.GetOpcode();
DEBUG_LOG("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(opcode), opcode, opcode);
Unit *mover = _player->GetMover();
Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL;
// ignore, waiting processing in WorldSession::HandleMoveWorldportAckOpcode and WorldSession::HandleMoveTeleportAck
if (plMover && plMover->IsBeingTeleported())
{
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
return;
}
/* extract packet */
MovementInfo movementInfo;
recv_data >> movementInfo;
/*----------------*/
if (!VerifyMovementInfo(movementInfo))
return;
// fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map).
if (opcode == MSG_MOVE_FALL_LAND && plMover && !plMover->IsTaxiFlying())
plMover->HandleFall(movementInfo);
/* process position-change */
HandleMoverRelocation(movementInfo);
if (plMover)
plMover->UpdateFallInformationIfNeed(movementInfo, opcode);
// after move info set
if (opcode == MSG_MOVE_SET_WALK_MODE || opcode == MSG_MOVE_SET_RUN_MODE)
mover->UpdateWalkMode(mover, false);
WorldPacket data(opcode, recv_data.size());
data << mover->GetPackGUID(); // write guid
movementInfo.Write(data); // write data
mover->SendMessageToSetExcept(&data, _player);
}
void WorldSession::HandleForceSpeedChangeAckOpcodes(WorldPacket &recv_data)
{
uint32 opcode = recv_data.GetOpcode();
DEBUG_LOG("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(opcode), opcode, opcode);
/* extract packet */
ObjectGuid guid;
MovementInfo movementInfo;
float newspeed;
recv_data >> guid;
recv_data >> Unused<uint32>(); // counter or moveEvent
recv_data >> movementInfo;
recv_data >> newspeed;
// now can skip not our packet
if (_player->GetObjectGuid() != guid)
return;
/*----------------*/
// client ACK send one packet for mounted/run case and need skip all except last from its
// in other cases anti-cheat check can be fail in false case
UnitMoveType move_type;
UnitMoveType force_move_type;
static char const* move_type_name[MAX_MOVE_TYPE] = { "Walk", "Run", "RunBack", "Swim", "SwimBack", "TurnRate" };
switch (opcode)
{
case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: move_type = MOVE_WALK; force_move_type = MOVE_WALK; break;
case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: move_type = MOVE_RUN; force_move_type = MOVE_RUN; break;
case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: move_type = MOVE_RUN_BACK; force_move_type = MOVE_RUN_BACK; break;
case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: move_type = MOVE_SWIM; force_move_type = MOVE_SWIM; break;
case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: move_type = MOVE_SWIM_BACK; force_move_type = MOVE_SWIM_BACK; break;
case CMSG_FORCE_TURN_RATE_CHANGE_ACK: move_type = MOVE_TURN_RATE; force_move_type = MOVE_TURN_RATE; break;
default:
sLog.outError("WorldSession::HandleForceSpeedChangeAck: Unknown move type opcode: %u", opcode);
return;
}
// skip all forced speed changes except last and unexpected
// in run/mounted case used one ACK and it must be skipped.m_forced_speed_changes[MOVE_RUN} store both.
if (_player->m_forced_speed_changes[force_move_type] > 0)
{
--_player->m_forced_speed_changes[force_move_type];
if (_player->m_forced_speed_changes[force_move_type] > 0)
return;
}
if (!_player->GetTransport() && fabs(_player->GetSpeed(move_type) - newspeed) > 0.01f)
{
if (_player->GetSpeed(move_type) > newspeed) // must be greater - just correct
{
sLog.outError("%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value",
move_type_name[move_type], _player->GetName(), _player->GetSpeed(move_type), newspeed);
_player->SetSpeedRate(move_type, _player->GetSpeedRate(move_type), true);
}
else // must be lesser - cheating
{
BASIC_LOG("Player %s from account id %u kicked for incorrect speed (must be %f instead %f)",
_player->GetName(), _player->GetSession()->GetAccountId(), _player->GetSpeed(move_type), newspeed);
_player->GetSession()->KickPlayer();
}
}
}
void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recv_data)
{
DEBUG_LOG("WORLD: Recvd CMSG_SET_ACTIVE_MOVER");
ObjectGuid guid;
recv_data >> guid;
if (_player->GetMover()->GetObjectGuid() != guid)
{
sLog.outError("HandleSetActiveMoverOpcode: incorrect mover guid: mover is %s and should be %s",
_player->GetMover()->GetGuidStr().c_str(), guid.GetString().c_str());
return;
}
}
void WorldSession::HandleMoveNotActiveMoverOpcode(WorldPacket &recv_data)
{
DEBUG_LOG("WORLD: Recvd CMSG_MOVE_NOT_ACTIVE_MOVER");
recv_data.hexlike();
ObjectGuid old_mover_guid;
MovementInfo mi;
recv_data >> old_mover_guid;
recv_data >> mi;
if (_player->GetMover()->GetObjectGuid() == old_mover_guid)
{
sLog.outError("HandleMoveNotActiveMover: incorrect mover guid: mover is %s and should be %s instead of %s",
_player->GetMover()->GetGuidStr().c_str(),
_player->GetGuidStr().c_str(),
old_mover_guid.GetString().c_str());
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
return;
}
_player->m_movementInfo = mi;
}
void WorldSession::HandleMountSpecialAnimOpcode(WorldPacket& /*recvdata*/)
{
//DEBUG_LOG("WORLD: Recvd CMSG_MOUNTSPECIAL_ANIM");
WorldPacket data(SMSG_MOUNTSPECIAL_ANIM, 8);
data << GetPlayer()->GetObjectGuid();
GetPlayer()->SendMessageToSet(&data, false);
}
void WorldSession::HandleMoveKnockBackAck(WorldPacket & recv_data)
{
DEBUG_LOG("CMSG_MOVE_KNOCK_BACK_ACK");
Unit *mover = _player->GetMover();
Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL;
// ignore, waiting processing in WorldSession::HandleMoveWorldportAckOpcode and WorldSession::HandleMoveTeleportAck
if (plMover && plMover->IsBeingTeleported())
{
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
return;
}
ObjectGuid guid;
MovementInfo movementInfo;
recv_data >> guid;
recv_data >> Unused<uint32>(); // knockback packets counter
recv_data >> movementInfo;
if (!VerifyMovementInfo(movementInfo, guid))
return;
HandleMoverRelocation(movementInfo);
WorldPacket data(MSG_MOVE_KNOCK_BACK, recv_data.size() + 15);
data << ObjectGuid(mover->GetObjectGuid());
data << movementInfo;
data << movementInfo.GetJumpInfo().sinAngle;
data << movementInfo.GetJumpInfo().cosAngle;
data << movementInfo.GetJumpInfo().xyspeed;
data << movementInfo.GetJumpInfo().velocity;
mover->SendMessageToSetExcept(&data, _player);
}
void WorldSession::HandleMoveHoverAck(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_MOVE_HOVER_ACK");
MovementInfo movementInfo;
recv_data >> Unused<uint64>(); // guid
recv_data >> Unused<uint32>(); // unk
recv_data >> movementInfo;
recv_data >> Unused<uint32>(); // unk2
}
void WorldSession::HandleMoveWaterWalkAck(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_MOVE_WATER_WALK_ACK");
MovementInfo movementInfo;
recv_data.read_skip<uint64>(); // guid
recv_data.read_skip<uint32>(); // unk
recv_data >> movementInfo;
recv_data >> Unused<uint32>(); // unk2
}
void WorldSession::HandleSummonResponseOpcode(WorldPacket& recv_data)
{
if (!_player->isAlive() || _player->isInCombat())
return;
ObjectGuid summonerGuid;
recv_data >> summonerGuid;
_player->SummonIfPossible(true);
}
bool WorldSession::VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGuid const& guid) const
{
// ignore wrong guid (player attempt cheating own session for not own guid possible...)
if (guid != _player->GetMover()->GetObjectGuid())
return false;
return VerifyMovementInfo(movementInfo);
}
bool WorldSession::VerifyMovementInfo(MovementInfo const& movementInfo) const
{
if (!MaNGOS::IsValidMapCoord(movementInfo.GetPos()->x, movementInfo.GetPos()->y, movementInfo.GetPos()->z, movementInfo.GetPos()->o))
return false;
if (movementInfo.HasMovementFlag(MOVEFLAG_ONTRANSPORT))
{
// transports size limited
// (also received at zeppelin/lift leave by some reason with t_* as absolute in continent coordinates, can be safely skipped)
if (movementInfo.GetTransportPos()->x > 50 || movementInfo.GetTransportPos()->y > 50 || movementInfo.GetTransportPos()->z > 100)
return false;
if (!MaNGOS::IsValidMapCoord(movementInfo.GetPos()->x + movementInfo.GetTransportPos()->x, movementInfo.GetPos()->y + movementInfo.GetTransportPos()->y,
movementInfo.GetPos()->z + movementInfo.GetTransportPos()->z, movementInfo.GetPos()->o + movementInfo.GetTransportPos()->o))
{
return false;
}
}
return true;
}
void WorldSession::HandleMoverRelocation(MovementInfo& movementInfo)
{
movementInfo.UpdateTime(WorldTimer::getMSTime());
Unit *mover = _player->GetMover();
if (Player *plMover = mover->GetTypeId() == TYPEID_PLAYER ? (Player*)mover : NULL)
{
if (movementInfo.HasMovementFlag(MOVEFLAG_ONTRANSPORT))
{
if (!plMover->m_transport)
{
// elevators also cause the client to send MOVEFLAG_ONTRANSPORT - just unmount if the guid can be found in the transport list
for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
{
if ((*iter)->GetObjectGuid() == movementInfo.GetTransportGuid())
{
plMover->m_transport = (*iter);
(*iter)->AddPassenger(plMover);
break;
}
}
}
}
else if (plMover->m_transport) // if we were on a transport, leave
{
plMover->m_transport->RemovePassenger(plMover);
plMover->m_transport = NULL;
movementInfo.ClearTransportData();
}
if (movementInfo.HasMovementFlag(MOVEFLAG_SWIMMING) != plMover->IsInWater())
{
// now client not include swimming flag in case jumping under water
plMover->SetInWater(!plMover->IsInWater() || plMover->GetTerrain()->IsUnderWater(movementInfo.GetPos()->x, movementInfo.GetPos()->y, movementInfo.GetPos()->z));
}
plMover->SetPosition(movementInfo.GetPos()->x, movementInfo.GetPos()->y, movementInfo.GetPos()->z, movementInfo.GetPos()->o);
plMover->m_movementInfo = movementInfo;
if (movementInfo.GetPos()->z < -500.0f)
{
if (plMover->InBattleGround()
&& plMover->GetBattleGround()
&& plMover->GetBattleGround()->HandlePlayerUnderMap(_player))
{
// do nothing, the handle already did if returned true
}
else
{
// NOTE: this is actually called many times while falling
// even after the player has been teleported away
// TODO: discard movement packets after the player is rooted
if (plMover->isAlive())
{
plMover->EnvironmentalDamage(DAMAGE_FALL_TO_VOID, plMover->GetMaxHealth());
// pl can be alive if GM/etc
if (!plMover->isAlive())
{
// change the death state to CORPSE to prevent the death timer from
// starting in the next player update
plMover->KillPlayer();
plMover->BuildPlayerRepop();
}
}
// cancel the death timer here if started
plMover->RepopAtGraveyard();
}
}
}
else // creature charmed
{
if (mover->IsInWorld())
mover->GetMap()->CreatureRelocation((Creature*)mover, movementInfo.GetPos()->x, movementInfo.GetPos()->y, movementInfo.GetPos()->z, movementInfo.GetPos()->o);
}
}
| 0 | 0.90931 | 1 | 0.90931 | game-dev | MEDIA | 0.964151 | game-dev | 0.976729 | 1 | 0.976729 |
eliemichel/OpenMfxForBlender | 3,226 | extern/bullet2/src/BulletCollision/Gimpact/btContactProcessingStructs.h | #ifndef BT_CONTACT_H_STRUCTS_INCLUDED
#define BT_CONTACT_H_STRUCTS_INCLUDED
/*! \file gim_contact.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "LinearMath/btTransform.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btTriangleShapeEx.h"
/**
Configuration var for applying interpolation of contact normals
*/
#define NORMAL_CONTACT_AVERAGE 1
#define CONTACT_DIFF_EPSILON 0.00001f
///The GIM_CONTACT is an internal GIMPACT structure, similar to btManifoldPoint.
///@todo: remove and replace GIM_CONTACT by btManifoldPoint.
class GIM_CONTACT
{
public:
btVector3 m_point;
btVector3 m_normal;
btScalar m_depth; //Positive value indicates interpenetration
btScalar m_distance; //Padding not for use
int m_feature1; //Face number
int m_feature2; //Face number
public:
GIM_CONTACT()
{
}
GIM_CONTACT(const GIM_CONTACT &contact) : m_point(contact.m_point),
m_normal(contact.m_normal),
m_depth(contact.m_depth),
m_feature1(contact.m_feature1),
m_feature2(contact.m_feature2)
{
}
GIM_CONTACT(const btVector3 &point, const btVector3 &normal,
btScalar depth, int feature1, int feature2) : m_point(point),
m_normal(normal),
m_depth(depth),
m_feature1(feature1),
m_feature2(feature2)
{
}
//! Calcs key for coord classification
SIMD_FORCE_INLINE unsigned int calc_key_contact() const
{
int _coords[] = {
(int)(m_point[0] * 1000.0f + 1.0f),
(int)(m_point[1] * 1333.0f),
(int)(m_point[2] * 2133.0f + 3.0f)};
unsigned int _hash = 0;
unsigned int *_uitmp = (unsigned int *)(&_coords[0]);
_hash = *_uitmp;
_uitmp++;
_hash += (*_uitmp) << 4;
_uitmp++;
_hash += (*_uitmp) << 8;
return _hash;
}
SIMD_FORCE_INLINE void interpolate_normals(btVector3 *normals, int normal_count)
{
btVector3 vec_sum(m_normal);
for (int i = 0; i < normal_count; i++)
{
vec_sum += normals[i];
}
btScalar vec_sum_len = vec_sum.length2();
if (vec_sum_len < CONTACT_DIFF_EPSILON) return;
//GIM_INV_SQRT(vec_sum_len,vec_sum_len); // 1/sqrt(vec_sum_len)
m_normal = vec_sum / btSqrt(vec_sum_len);
}
};
#endif // BT_CONTACT_H_STRUCTS_INCLUDED
| 0 | 0.816916 | 1 | 0.816916 | game-dev | MEDIA | 0.906809 | game-dev | 0.820819 | 1 | 0.820819 |
orangeduck/Corange | 1,778 | include/centity.h | /**
*** :: Entity ::
***
*** Interface for interacting with Entities in virtual world
***
*** An entity is any form of persistent object in the world.
*** These can be created, destoryed or interacted with.
***
**/
#ifndef centity_h
#define centity_h
#include "cengine.h"
typedef void entity;
void entity_init(void);
void entity_finish(void);
#define entity_handler(type, new, del) entity_handler_cast(typeid(type), (void*(*)())new , (void(*)(void*))del)
void entity_handler_cast(int type_id, void* entity_new() , void entity_del(void* entity));
/* Create, get and destroy entities */
#define entity_new(fmt, type, ...) (type*)entity_new_type_id(fmt, typeid(type), ##__VA_ARGS__)
#define entity_get_as(fmt, type, ...) ((type*)entity_get_as_type_id(fmt, typeid(type)), ##__VA_ARGS__)
bool entity_exists(char* fmt, ...);
entity* entity_get(char* fmt, ...);
entity* entity_get_as_type_id(char* fmt, int type_id, ...);
entity* entity_new_type_id(char* fmt, int type_id, ...);
void entity_delete(char* fmt, ...);
/* Get the name or typename from an entity */
char* entity_name(entity* e);
char* entity_typename(entity* a);
/* Get the number of a certain entity type */
#define entity_type_count(type) entity_type_count_type_id(typeid(type))
int entity_type_count_type_id(int type_id);
/* Create or get multiple entities of a certain type */
#define entities_new(name_format, count, type) entities_new_type_id(name_format, count, typeid(type))
#define entities_get(out, returned, type) entities_get_type_id((entity**)out, returned, typeid(type))
/* Argument 'name_format' should contain '%i' for created index */
void entities_new_type_id(const char* name_format, int count, int type_id);
void entities_get_type_id(entity** out, int* returned, int type_id);
#endif
| 0 | 0.829256 | 1 | 0.829256 | game-dev | MEDIA | 0.382132 | game-dev | 0.587883 | 1 | 0.587883 |
alliedmodders/hl2sdk | 1,732 | common/replay/ireplayperformancerecorder.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//=======================================================================================//
#ifndef IREPLAYPERFORMANCERECORDER_H
#define IREPLAYPERFORMANCERECORDER_H
#ifdef _WIN32
#pragma once
#endif
//----------------------------------------------------------------------------------------
#include "interface.h"
//----------------------------------------------------------------------------------------
class CReplay;
class Vector;
class QAngle;
class CReplayPerformance;
//----------------------------------------------------------------------------------------
class IReplayPerformanceRecorder : public IBaseInterface
{
public:
virtual void BeginPerformanceRecord( CReplay *pReplay ) = 0;
virtual void EndPerformanceRecord() = 0;
virtual void NotifyPauseState( bool bPaused ) = 0;
virtual CReplayPerformance *GetPerformance() = 0;
virtual bool IsRecording() const = 0;
virtual void SnipAtTime( float flTime ) = 0;
virtual void NotifySkipping() = 0;
virtual void ClearSkipping() = 0;
virtual void AddEvent_Camera_Change_FirstPerson( float flTime, int nEntityIndex ) = 0;
virtual void AddEvent_Camera_Change_ThirdPerson( float flTime, int nEntityIndex ) = 0;
virtual void AddEvent_Camera_Change_Free( float flTime ) = 0;
virtual void AddEvent_Camera_ChangePlayer( float flTime, int nEntIndex ) = 0;
virtual void AddEvent_Camera_SetView( float flTime, const Vector& origin, const QAngle &angles, float fov ) = 0;
virtual void AddEvent_Slowmo( float flTime, float flScale ) = 0;
};
//----------------------------------------------------------------------------------------
#endif // IREPLAYPERFORMANCERECORDER_H
| 0 | 0.958073 | 1 | 0.958073 | game-dev | MEDIA | 0.717819 | game-dev | 0.753125 | 1 | 0.753125 |
Unity-Technologies/UnityCsReference | 2,657 | Modules/Tilemap/Managed/GridBrushBase.cs | // Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine
{
public abstract class GridBrushBase : ScriptableObject
{
public enum Tool { Select, Move, Paint, Box, Pick, Erase, FloodFill, Other }
public enum RotationDirection { Clockwise = 0, CounterClockwise = 1 }
public enum FlipAxis { X = 0, Y = 1 }
public virtual void Paint(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) {}
public virtual void Erase(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) {}
public virtual void BoxFill(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
for (int z = position.zMin; z < position.zMax; z++)
{
for (int y = position.yMin; y < position.yMax; y++)
{
for (int x = position.xMin; x < position.xMax; x++)
{
Paint(gridLayout, brushTarget, new Vector3Int(x, y, z));
}
}
}
}
public virtual void BoxErase(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
for (int z = position.zMin; z < position.zMax; z++)
{
for (int y = position.yMin; y < position.yMax; y++)
{
for (int x = position.xMin; x < position.xMax; x++)
{
Erase(gridLayout, brushTarget, new Vector3Int(x, y, z));
}
}
}
}
public virtual void Select(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) {}
public virtual void FloodFill(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) {}
public virtual void Rotate(RotationDirection direction, GridLayout.CellLayout layout) {}
public virtual void Flip(FlipAxis flip, GridLayout.CellLayout layout) {}
public virtual void Pick(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, Vector3Int pivot) {}
public virtual void Move(GridLayout gridLayout, GameObject brushTarget, BoundsInt from, BoundsInt to) {}
public virtual void MoveStart(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) {}
public virtual void MoveEnd(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) {}
public virtual void ChangeZPosition(int change) {}
public virtual void ResetZPosition() {}
}
}
| 0 | 0.69353 | 1 | 0.69353 | game-dev | MEDIA | 0.833772 | game-dev | 0.751687 | 1 | 0.751687 |
ruyo/VRM4U | 5,835 | Source/VRM4U/Private/AnimNode_VrmModifyBoneListRetarget.cpp | // VRM4U Copyright (c) 2021-2024 Haruyoshi Yamamoto. This software is released under the MIT License.
#include "AnimNode_VrmModifyBoneListRetarget.h"
#include "AnimationRuntime.h"
#include "Animation/AnimInstanceProxy.h"
#include "Kismet/KismetSystemLibrary.h"
#include "DrawDebugHelpers.h"
#include "VrmMetaObject.h"
#include "VrmUtil.h"
#include <algorithm>
/////////////////////////////////////////////////////
// FAnimNode_ModifyBone
FAnimNode_VrmModifyBoneListRetarget::FAnimNode_VrmModifyBoneListRetarget()
{
}
//void FAnimNode_VrmModifyBoneListRetarget::Update_AnyThread(const FAnimationUpdateContext& Context) {
// Super::Update_AnyThread(Context);
// //Context.GetDeltaTime();
//}
void FAnimNode_VrmModifyBoneListRetarget::Initialize_AnyThread(const FAnimationInitializeContext& Context) {
Super::Initialize_AnyThread(Context);
}
void FAnimNode_VrmModifyBoneListRetarget::CacheBones_AnyThread(const FAnimationCacheBonesContext& Context) {
Super::CacheBones_AnyThread(Context);
}
void FAnimNode_VrmModifyBoneListRetarget::UpdateInternal(const FAnimationUpdateContext& Context){
Super::UpdateInternal(Context);
}
void FAnimNode_VrmModifyBoneListRetarget::GatherDebugData(FNodeDebugData& DebugData)
{
FString DebugLine = DebugData.GetNodeName(this);
DebugLine += "(";
AddDebugNodeData(DebugLine);
//DebugLine += FString::Printf(TEXT(" Target: %s)"), *BoneToModify.BoneName.ToString());
//DebugLine += FString::Printf(TEXT(" Target: %s)"), *BoneNameToModify.ToString());
DebugData.AddDebugItem(DebugLine);
ComponentPose.GatherDebugData(DebugData);
}
void FAnimNode_VrmModifyBoneListRetarget::EvaluateComponentPose_AnyThread(FComponentSpacePoseContext& Output) {
Super::EvaluateComponentPose_AnyThread(Output);
}
void FAnimNode_VrmModifyBoneListRetarget::EvaluateSkeletalControl_AnyThread(FComponentSpacePoseContext& Output, TArray<FBoneTransform>& OutBoneTransforms)
{
check(OutBoneTransforms.Num() == 0);
const auto Skeleton = Output.AnimInstanceProxy->GetSkeleton();
const auto RefSkeleton = Output.AnimInstanceProxy->GetSkeleton()->GetReferenceSkeleton();
const FTransform ComponentTransform = Output.AnimInstanceProxy->GetComponentTransform();
const auto& RefSkeletonTransform = Output.Pose.GetPose().GetBoneContainer().GetRefPoseArray();
TArray<int> boneIndexTable;
TArray<FBoneTransform> tmpOutTransform;
//dstRefSkeleton.GetParentIndex
{
if (VrmMetaObject == nullptr) {
return;
}
bool bFirstBone = true;
for (const auto &t : VrmMetaObject->humanoidBoneTable) {
#if UE_VERSION_OLDER_THAN(4,27,0)
auto *tmpVal = BoneTrans.Find(t.Key.ToLower());
if (tmpVal == nullptr) continue;
auto modelBone = *tmpVal;
#else
auto filterList= BoneTrans.FilterByPredicate([&t](TPair<FString, FTransform> a) {
return a.Key.Compare(t.Key, ESearchCase::IgnoreCase) == 0;
}
);
if (filterList.Num() != 1) continue;
auto modelBone = filterList.begin()->Value;
#endif
int index = RefSkeleton.FindBoneIndex(*t.Value);
if (index < 0) continue;
FBoneTransform f(FCompactPoseBoneIndex(index), modelBone);
//f.Transform.SetRotation(FQuat::Identity);
if (bFirstBone) {
bFirstBone = false;
if (bUseRemoteCenterPos) {
auto v = f.Transform.GetLocation() * ModelRelativeScale;
f.Transform.SetTranslation(v);
} else {
auto v = RefSkeletonTransform[index].GetLocation();
f.Transform.SetTranslation(v);
}
} else {
FVector v = RefSkeletonTransform[index].GetLocation();
f.Transform.SetTranslation(v);
}
//f.Transform.SetTranslation(RefSkeletonTransform[index].GetLocation());
tmpOutTransform.Add(f);
boneIndexTable.Add(index);
}
// bone hierarchy
// start with 1
for (int i = 1; i < tmpOutTransform.Num(); ++i) {
auto& a = tmpOutTransform[i];
int parentBoneIndex = RefSkeleton.GetParentIndex(boneIndexTable[i]);
int parentInTable = boneIndexTable.Find(parentBoneIndex);
for (int j = 0; j < 100; ++j) {
if (parentInTable >= 0) {
break;
}
// add outtransform with ref bone
FBoneTransform f(FCompactPoseBoneIndex(parentBoneIndex), RefSkeletonTransform[parentBoneIndex]);
tmpOutTransform.Add(f);
boneIndexTable.Add(parentBoneIndex);
parentBoneIndex = RefSkeleton.GetParentIndex(parentBoneIndex);
parentInTable = boneIndexTable.Find(parentBoneIndex);
}
}
// sort
tmpOutTransform.Sort(FCompareBoneTransformIndex());
boneIndexTable.Sort();
}
for (int i = 0; i < tmpOutTransform.Num(); ++i) {
auto& a = tmpOutTransform[i];
int parentBoneIndex = RefSkeleton.GetParentIndex(boneIndexTable[i]);
int parentInHandTable = boneIndexTable.Find(parentBoneIndex);
if (parentInHandTable >= 0) {
a.Transform *= tmpOutTransform[parentInHandTable].Transform;
} else {
// root
auto BoneSpace = EBoneControlSpace::BCS_ParentBoneSpace;
FAnimationRuntime::ConvertBoneSpaceTransformToCS(ComponentTransform, Output.Pose, a.Transform, a.BoneIndex, BoneSpace);
}
OutBoneTransforms.Add(a);
}
}
bool FAnimNode_VrmModifyBoneListRetarget::IsValidToEvaluate(const USkeleton* Skeleton, const FBoneContainer& RequiredBones)
{
// if both bones are valid
//return (BoneToModify.IsValidToEvaluate(RequiredBones));
return true;
}
void FAnimNode_VrmModifyBoneListRetarget::InitializeBoneReferences(const FBoneContainer& RequiredBones)
{
//BoneToModify.Initialize(RequiredBones);
}
void FAnimNode_VrmModifyBoneListRetarget::ConditionalDebugDraw(FPrimitiveDrawInterface* PDI, USkeletalMeshComponent* PreviewSkelMeshComp, bool bPreviewForeground) const
{
#if WITH_EDITOR
if (VrmMetaObject == nullptr || PreviewSkelMeshComp == nullptr) {
return;
}
if (PreviewSkelMeshComp->GetWorld() == nullptr) {
return;
}
ESceneDepthPriorityGroup Priority = SDPG_World;
if (bPreviewForeground) Priority = SDPG_Foreground;
#endif
}
| 0 | 0.939862 | 1 | 0.939862 | game-dev | MEDIA | 0.803266 | game-dev | 0.893178 | 1 | 0.893178 |
QuestionableM/SM-ProximityVoiceChat | 3,993 | Dependencies/bullet3/Bullet3OpenCL/RigidBody/b3GpuGenericConstraint.cpp | /*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#include "b3GpuGenericConstraint.h"
#include "Bullet3Collision/NarrowPhaseCollision/shared/b3RigidBodyData.h"
#include <new>
#include "Bullet3Common/b3Transform.h"
void b3GpuGenericConstraint::getInfo1(unsigned int* info, const b3RigidBodyData* bodies)
{
switch (m_constraintType)
{
case B3_GPU_POINT2POINT_CONSTRAINT_TYPE:
{
*info = 3;
break;
};
default:
{
b3Assert(0);
}
};
}
void getInfo2Point2Point(b3GpuGenericConstraint* constraint, b3GpuConstraintInfo2* info, const b3RigidBodyData* bodies)
{
b3Transform trA;
trA.setIdentity();
trA.setOrigin(bodies[constraint->m_rbA].m_pos);
trA.setRotation(bodies[constraint->m_rbA].m_quat);
b3Transform trB;
trB.setIdentity();
trB.setOrigin(bodies[constraint->m_rbB].m_pos);
trB.setRotation(bodies[constraint->m_rbB].m_quat);
// anchor points in global coordinates with respect to body PORs.
// set jacobian
info->m_J1linearAxis[0] = 1;
info->m_J1linearAxis[info->rowskip + 1] = 1;
info->m_J1linearAxis[2 * info->rowskip + 2] = 1;
b3Vector3 a1 = trA.getBasis() * constraint->getPivotInA();
//b3Vector3 a1a = b3QuatRotate(trA.getRotation(),constraint->getPivotInA());
{
b3Vector3* angular0 = (b3Vector3*)(info->m_J1angularAxis);
b3Vector3* angular1 = (b3Vector3*)(info->m_J1angularAxis + info->rowskip);
b3Vector3* angular2 = (b3Vector3*)(info->m_J1angularAxis + 2 * info->rowskip);
b3Vector3 a1neg = -a1;
a1neg.getSkewSymmetricMatrix(angular0, angular1, angular2);
}
if (info->m_J2linearAxis)
{
info->m_J2linearAxis[0] = -1;
info->m_J2linearAxis[info->rowskip + 1] = -1;
info->m_J2linearAxis[2 * info->rowskip + 2] = -1;
}
b3Vector3 a2 = trB.getBasis() * constraint->getPivotInB();
{
// b3Vector3 a2n = -a2;
b3Vector3* angular0 = (b3Vector3*)(info->m_J2angularAxis);
b3Vector3* angular1 = (b3Vector3*)(info->m_J2angularAxis + info->rowskip);
b3Vector3* angular2 = (b3Vector3*)(info->m_J2angularAxis + 2 * info->rowskip);
a2.getSkewSymmetricMatrix(angular0, angular1, angular2);
}
// set right hand side
// b3Scalar currERP = (m_flags & B3_P2P_FLAGS_ERP) ? m_erp : info->erp;
b3Scalar currERP = info->erp;
b3Scalar k = info->fps * currERP;
int j;
for (j = 0; j < 3; j++)
{
info->m_constraintError[j * info->rowskip] = k * (a2[j] + trB.getOrigin()[j] - a1[j] - trA.getOrigin()[j]);
//printf("info->m_constraintError[%d]=%f\n",j,info->m_constraintError[j]);
}
#if 0
if(m_flags & B3_P2P_FLAGS_CFM)
{
for (j=0; j<3; j++)
{
info->cfm[j*info->rowskip] = m_cfm;
}
}
#endif
#if 0
b3Scalar impulseClamp = m_setting.m_impulseClamp;//
for (j=0; j<3; j++)
{
if (m_setting.m_impulseClamp > 0)
{
info->m_lowerLimit[j*info->rowskip] = -impulseClamp;
info->m_upperLimit[j*info->rowskip] = impulseClamp;
}
}
info->m_damping = m_setting.m_damping;
#endif
}
void b3GpuGenericConstraint::getInfo2(b3GpuConstraintInfo2* info, const b3RigidBodyData* bodies)
{
switch (m_constraintType)
{
case B3_GPU_POINT2POINT_CONSTRAINT_TYPE:
{
getInfo2Point2Point(this, info, bodies);
break;
};
default:
{
b3Assert(0);
}
};
}
| 0 | 0.864507 | 1 | 0.864507 | game-dev | MEDIA | 0.864214 | game-dev | 0.984677 | 1 | 0.984677 |
SpigotRCE/ParadiseClient-Fabric | 1,037 | src/main/java/io/github/spigotrce/paradiseclientfabric/mixin/inject/etc/ClientPlayerEntityMixin.java | package io.github.spigotrce.paradiseclientfabric.mixin.inject.etc;
import io.github.spigotrce.paradiseclientfabric.ParadiseClient_Fabric;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.text.Text;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayerEntity.class)
public abstract class ClientPlayerEntityMixin {
@Shadow
public abstract void sendMessage(Text message, boolean overlay);
@Inject(method = "tick", at = @At("TAIL"))
public void tick(CallbackInfo ci) {
ParadiseClient_Fabric.MISC_MOD.delayedMessages.forEach(this::sendMessage);
ParadiseClient_Fabric.MISC_MOD.delayedMessages.clear();
}
@Unique
private void sendMessage(Text message) {
this.sendMessage(message, false);
}
}
| 0 | 0.56261 | 1 | 0.56261 | game-dev | MEDIA | 0.827805 | game-dev | 0.588646 | 1 | 0.588646 |
hengband/hengband | 4,566 | src/lore/lore-util.h | #pragma once
#include "monster-attack/monster-attack-table.h"
#include "monster-race/monster-aura-types.h"
#include "monster-race/race-ability-flags.h"
#include "monster-race/race-behavior-flags.h"
#include "monster-race/race-brightness-flags.h"
#include "monster-race/race-drop-flags.h"
#include "monster-race/race-feature-flags.h"
#include "monster-race/race-flags-resistance.h"
#include "monster-race/race-kind-flags.h"
#include "monster-race/race-misc-flags.h"
#include "monster-race/race-special-flags.h"
#include "monster-race/race-visual-flags.h"
#include "system/angband.h"
#include "term/term-color-types.h"
#include "util/flag-group.h"
#include <string>
#include <string_view>
#include <tl/optional.hpp>
#include <unordered_map>
#include <utility>
#include <vector>
enum class MonraceId : short;
enum class MonsterSex;
enum monster_lore_mode {
MONSTER_LORE_NONE,
MONSTER_LORE_NORMAL,
MONSTER_LORE_RESEARCH,
MONSTER_LORE_DEBUG
};
class MonraceDefinition;
struct lore_msg {
lore_msg(std::string_view msg, byte color = TERM_WHITE);
std::string msg;
byte color;
};
struct lore_type {
lore_type(MonraceId monrace_id, monster_lore_mode mode);
#ifndef JP
bool sin = false;
#endif
bool know_everything = false;
bool old = false;
int count = 0;
bool shoot = false;
bool rocket = false;
std::vector<lore_msg> lore_msgs;
bool breath = false;
bool magic = false;
int drop_quantity = 0;
concptr drop_quality = "";
concptr p = "";
byte pc = 0;
concptr q = "";
byte qc = 0;
MonraceId monrace_id;
BIT_FLAGS mode;
MonsterSex msex;
RaceBlowMethodType method;
bool nightmare;
MonraceDefinition *r_ptr;
byte speed;
ITEM_NUMBER drop_gold;
ITEM_NUMBER drop_item;
EnumClassFlagGroup<MonsterAbilityType> ability_flags;
EnumClassFlagGroup<MonsterAuraType> aura_flags;
EnumClassFlagGroup<MonsterBehaviorType> behavior_flags;
EnumClassFlagGroup<MonsterVisualType> visual_flags;
EnumClassFlagGroup<MonsterKindType> kind_flags;
EnumClassFlagGroup<MonsterResistanceType> resistance_flags;
EnumClassFlagGroup<MonsterDropType> drop_flags;
EnumClassFlagGroup<MonsterFeatureType> feature_flags;
EnumClassFlagGroup<MonsterBrightnessType> brightness_flags;
EnumClassFlagGroup<MonsterSpecialType> special_flags;
EnumClassFlagGroup<MonsterMiscType> misc_flags;
bool has_reinforce() const;
bool is_details_known() const;
bool is_blow_damage_known(int num_blow) const;
tl::optional<std::vector<lore_msg>> build_kill_unique_description() const;
std::string build_revenge_description(bool has_defeated) const;
std::vector<lore_msg> build_speed_description() const;
private:
std::vector<lore_msg> build_random_movement_description() const;
};
using hook_c_roff_pf = void (*)(TERM_COLOR attr, std::string_view str);
extern hook_c_roff_pf hook_c_roff;
void hooked_roff(std::string_view str);
enum WHO_WORD_TYPE { WHO = 0,
WHOSE = 1,
WHOM = 2 };
using who_word_definition = std::unordered_map<WHO_WORD_TYPE, const std::unordered_map<bool, const std::unordered_map<MonsterSex, std::string>>>;
class Who {
public:
static const who_word_definition words;
/*!
* @brief 三人称主格を取得(単数のみ)
* @param msex モンスターの性別
* @return 主語
*/
static std::string who(MonsterSex msex)
{
return who(msex, false);
}
/*!
* @brief 三人称主格を取得
* @param msex モンスターの性別
* @param multi 複数かどうか
* @return 主語
*/
static std::string who(MonsterSex msex, bool multi)
{
return words.at(WHO_WORD_TYPE::WHO).at(multi).at(msex).data();
}
/*!
* @brief 三人称所有格を取得(単数のみ)
* @param msex モンスターの性別
* @return 所有格
*/
static std::string whose(MonsterSex msex)
{
return whose(msex, false);
}
/*!
* @brief 三人称所有格を取得
* @param msex モンスターの性別
* @param multi 複数かどうか
* @return 所有格
*/
static std::string whose(MonsterSex msex, bool multi)
{
return words.at(WHO_WORD_TYPE::WHOSE).at(multi).at(msex).data();
}
/*!
* @brief 三人称目的格を取得(単数のみ)
* @param msex モンスターの性別
* @return 目的語
*/
static std::string whom(MonsterSex msex)
{
return whom(msex, false);
}
/*!
* @brief 三人称目的格を取得
* @param msex モンスターの性別
* @param multi 複数かどうか
* @return 目的語
*/
static std::string whom(MonsterSex msex, bool multi)
{
return words.at(WHO_WORD_TYPE::WHOM).at(multi).at(msex).data();
}
};
| 0 | 0.879541 | 1 | 0.879541 | game-dev | MEDIA | 0.908245 | game-dev | 0.823407 | 1 | 0.823407 |
OpenXRay/xray-16 | 4,855 | src/xrGame/alife_spawn_registry_spawn.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : alife_spawn_registry_spawn.cpp
// Created : 19.10.2004
// Modified : 19.10.2004
// Author : Dmitriy Iassenev
// Description : ALife spawn registry spawn routines
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "alife_spawn_registry.h"
#include "Random.hpp"
IC bool CALifeSpawnRegistry::enabled_spawn(CSE_Abstract& abstract) const
{
return (!!abstract.m_spawn_flags.is(CSE_Abstract::flSpawnEnabled));
}
IC bool CALifeSpawnRegistry::count_limit(CSE_Abstract& abstract) const
{
if (!!abstract.m_spawn_flags.is(CSE_Abstract::flSpawnInfiniteCount))
return (false);
// if (abstract.m_spawn_count < abstract.m_max_spawn_count)
// return (false);
return (true);
}
IC bool CALifeSpawnRegistry::time_limit(CSE_Abstract& abstract, ALife::_TIME_ID game_time) const
{
if (!!abstract.m_spawn_flags.is(CSE_Abstract::flSpawnOnSurgeOnly))
return (false);
// if (game_time >= abstract.m_next_spawn_time)
// return (false);
return (true);
}
IC bool CALifeSpawnRegistry::spawned_item(CSE_Abstract& abstract, SPAWN_IDS& objects) const
{
SPAWN_IDS::iterator I = std::lower_bound(objects.begin(), objects.end(), abstract.m_tSpawnID);
return ((I != objects.end()) && (*I == abstract.m_tSpawnID));
}
IC bool CALifeSpawnRegistry::spawned_item(SPAWN_GRAPH::CVertex* vertex, SPAWN_IDS& objects)
{
if (vertex->edges().empty())
return (spawned_item(vertex->data()->object(), objects));
SPAWN_GRAPH::const_iterator I = vertex->edges().begin();
SPAWN_GRAPH::const_iterator E = vertex->edges().end();
for (; I != E; ++I)
if (spawned_item(m_spawns.vertex((*I).vertex_id()), objects))
return (true);
return (false);
}
IC bool CALifeSpawnRegistry::object_existance_limit(CSE_Abstract& abstract, SPAWN_IDS& objects) const
{
if (!abstract.m_spawn_flags.is(CSE_Abstract::flSpawnIfDestroyedOnly))
return (false);
if (spawned_item(abstract, objects))
return (true);
return (false);
}
IC bool CALifeSpawnRegistry::can_spawn(CSE_Abstract& abstract, ALife::_TIME_ID game_time, SPAWN_IDS& objects) const
{
return (enabled_spawn(abstract) && !count_limit(abstract) && !time_limit(abstract, game_time) &&
!object_existance_limit(abstract, objects));
}
void CALifeSpawnRegistry::fill_new_spawns_single(
SPAWN_GRAPH::CVertex* vertex, SPAWN_IDS& spawns, ALife::_TIME_ID game_time, SPAWN_IDS& objects)
{
if (!!vertex->data()->object().m_spawn_flags.is(CSE_Abstract::flSpawnIfDestroyedOnly) &&
spawned_item(vertex, objects))
return;
float accumulator = 0.f;
SPAWN_GRAPH::const_iterator I = vertex->edges().begin(), B = I;
SPAWN_GRAPH::const_iterator E = vertex->edges().end();
for (; I != E; ++I)
accumulator += (*I).weight();
float probability = randF(accumulator);
// float group_probability = vertex->data()->object().m_spawn_probability;
float group_probability = 1.f;
if (probability >= accumulator * group_probability)
return;
accumulator = 0.f;
I = B;
for (; I != E; ++I)
{
accumulator += (*I).weight() * group_probability;
if (accumulator > probability)
{
// vertex->data()->object().m_spawn_count++;
fill_new_spawns(m_spawns.vertex((*I).vertex_id()), spawns, game_time, objects);
return;
}
}
}
void CALifeSpawnRegistry::fill_new_spawns(
SPAWN_GRAPH::CVertex* vertex, SPAWN_IDS& spawns, ALife::_TIME_ID game_time, SPAWN_IDS& objects)
{
VERIFY(vertex);
if (!can_spawn(vertex->data()->object(), game_time, objects))
return;
if (vertex->edges().empty())
{
// vertex->data()->object().m_spawn_count++;
spawns.push_back(vertex->data()->object().m_tSpawnID);
return;
}
if (!!vertex->data()->object().m_spawn_flags.is(CSE_Abstract::flSpawnSingleItemOnly))
{
fill_new_spawns_single(vertex, spawns, game_time, objects);
return;
}
// vertex->data()->object().m_spawn_count++;
SPAWN_GRAPH::const_iterator I = vertex->edges().begin();
SPAWN_GRAPH::const_iterator E = vertex->edges().end();
for (; I != E; ++I)
if (randF(1.f) < (*I).weight())
fill_new_spawns(m_spawns.vertex((*I).vertex_id()), spawns, game_time, objects);
}
void CALifeSpawnRegistry::fill_new_spawns(SPAWN_IDS& spawns, ALife::_TIME_ID game_time, SPAWN_IDS& objects)
{
process_spawns(objects);
SPAWN_IDS::iterator I = m_spawn_roots.begin();
SPAWN_IDS::iterator E = m_spawn_roots.end();
for (; I != E; ++I)
fill_new_spawns(m_spawns.vertex(*I), spawns, game_time, objects);
process_spawns(spawns);
}
| 0 | 0.670785 | 1 | 0.670785 | game-dev | MEDIA | 0.967392 | game-dev | 0.834682 | 1 | 0.834682 |
Maetrim/DDOBuilder | 2,394 | DDOCP/BreakdownItemWeaponOtherDamageEffects.cpp | // BreakdownItemWeaponOtherDamageEffects.cpp
//
#include "stdafx.h"
#include "BreakdownItemWeaponOtherDamageEffects.h"
BreakdownItemWeaponOtherDamageEffects::BreakdownItemWeaponOtherDamageEffects(
BreakdownType type,
MfcControls::CTreeListCtrl * treeList,
HTREEITEM hItem) :
BreakdownItem(type, treeList, hItem)
{
}
BreakdownItemWeaponOtherDamageEffects::~BreakdownItemWeaponOtherDamageEffects()
{
}
// required overrides
CString BreakdownItemWeaponOtherDamageEffects::Title() const
{
if (Type() == Breakdown_WeaponOtherDamageEffects)
{
return "Other Damage Effects";
}
else
{
return "Other Critical Damage Effects";
}
}
CString BreakdownItemWeaponOtherDamageEffects::Value() const
{
// value is the concatenation of all the individual effects
CString value;
// just append all the items together, each should be an effect
// which as a dice item
std::list<ActiveEffect>::const_iterator it = m_otherEffects.begin();
while (it != m_otherEffects.end())
{
if ((*it).TotalAmount(false) != 0)
{
AddEffectToString(&value, (*it));
}
++it;
}
it = m_effects.begin();
while (it != m_effects.end())
{
if ((*it).TotalAmount(false) != 0)
{
AddEffectToString(&value, (*it));
}
++it;
}
it = m_itemEffects.begin();
while (it != m_itemEffects.end())
{
if ((*it).TotalAmount(false) != 0)
{
AddEffectToString(&value, (*it));
}
++it;
}
return value;
}
void BreakdownItemWeaponOtherDamageEffects::CreateOtherEffects()
{
// no other effects for this simple item
m_otherEffects.clear();
}
bool BreakdownItemWeaponOtherDamageEffects::AffectsUs(const Effect & effect) const
{
bool isUs = false;
if (Type() == Breakdown_WeaponOtherDamageEffects
&& effect.Type() == Effect_WeaponOtherDamageBonus)
{
isUs = true;
}
if (Type() == Breakdown_WeaponCriticalOtherDamageEffects
&& effect.Type() == Effect_WeaponOtherCriticalDamageBonus)
{
isUs = true;
}
return isUs;
}
void BreakdownItemWeaponOtherDamageEffects::AddEffectToString(
CString * value,
const ActiveEffect & effect) const
{
(*value) += " + ";
(*value) += effect.Description().c_str();
}
| 0 | 0.719212 | 1 | 0.719212 | game-dev | MEDIA | 0.691413 | game-dev | 0.755713 | 1 | 0.755713 |
etodd/Lemma | 6,318 | BEPUphysics/Entities/Prefabs/Capsule.cs | using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.EntityStateManagement;
using BEPUutilities;
using Microsoft.Xna.Framework;
using BEPUphysics.CollisionShapes.ConvexShapes;
namespace BEPUphysics.Entities.Prefabs
{
/// <summary>
/// Pill-shaped object that can collide and move. After making an entity, add it to a Space so that the engine can manage it.
/// </summary>
public class Capsule : Entity<ConvexCollidable<CapsuleShape>>
{
/// <summary>
/// Gets or sets the length of the capsule.
/// </summary>
public float Length
{
get
{
return CollisionInformation.Shape.Length;
}
set
{
CollisionInformation.Shape.Length = value;
}
}
/// <summary>
/// Gets or sets the radius of the capsule.
/// </summary>
public float Radius
{
get
{
return CollisionInformation.Shape.Radius;
}
set
{
CollisionInformation.Shape.Radius = value;
}
}
private Capsule(float len, float rad)
: base(new ConvexCollidable<CapsuleShape>(new CapsuleShape(len, rad)))
{
}
private Capsule(float len, float rad, float mass)
: base(new ConvexCollidable<CapsuleShape>(new CapsuleShape(len, rad)), mass)
{
}
///<summary>
/// Computes an orientation and length from a line segment.
///</summary>
///<param name="start">Starting point of the line segment.</param>
///<param name="end">Endpoint of the line segment.</param>
///<param name="orientation">Orientation of a line that fits the line segment.</param>
///<param name="length">Length of the line segment.</param>
public static void GetCapsuleInformation(ref Vector3 start, ref Vector3 end, out Quaternion orientation, out float length)
{
Vector3 segmentDirection;
Vector3.Subtract(ref end, ref start, out segmentDirection);
length = segmentDirection.Length();
if (length > 0)
{
Vector3.Divide(ref segmentDirection, length, out segmentDirection);
Toolbox.GetQuaternionBetweenNormalizedVectors(ref Toolbox.UpVector, ref segmentDirection, out orientation);
}
else
orientation = Quaternion.Identity;
}
///<summary>
/// Constructs a new kinematic capsule.
///</summary>
///<param name="start">Line segment start point.</param>
///<param name="end">Line segment end point.</param>
///<param name="radius">Radius of the capsule to expand the line segment by.</param>
public Capsule(Vector3 start, Vector3 end, float radius)
: this((end - start).Length(), radius)
{
float length;
Quaternion orientation;
GetCapsuleInformation(ref start, ref end, out orientation, out length);
this.Orientation = orientation;
Vector3 position;
Vector3.Add(ref start, ref end, out position);
Vector3.Multiply(ref position, .5f, out position);
this.Position = position;
}
///<summary>
/// Constructs a new dynamic capsule.
///</summary>
///<param name="start">Line segment start point.</param>
///<param name="end">Line segment end point.</param>
///<param name="radius">Radius of the capsule to expand the line segment by.</param>
/// <param name="mass">Mass of the entity.</param>
public Capsule(Vector3 start, Vector3 end, float radius, float mass)
: this((end - start).Length(), radius, mass)
{
float length;
Quaternion orientation;
GetCapsuleInformation(ref start, ref end, out orientation, out length);
this.Orientation = orientation;
Vector3 position;
Vector3.Add(ref start, ref end, out position);
Vector3.Multiply(ref position, .5f, out position);
this.Position = position;
}
/// <summary>
/// Constructs a physically simulated capsule.
/// </summary>
/// <param name="position">Position of the capsule.</param>
/// <param name="length">Length of the capsule.</param>
/// <param name="radius">Radius of the capsule.</param>
/// <param name="mass">Mass of the object.</param>
public Capsule(Vector3 position, float length, float radius, float mass)
: this(length, radius, mass)
{
Position = position;
}
/// <summary>
/// Constructs a nondynamic capsule.
/// </summary>
/// <param name="position">Position of the capsule.</param>
/// <param name="length">Length of the capsule.</param>
/// <param name="radius">Radius of the capsule.</param>
public Capsule(Vector3 position, float length, float radius)
: this(length, radius)
{
Position = position;
}
/// <summary>
/// Constructs a dynamic capsule.
/// </summary>
/// <param name="motionState">Motion state specifying the entity's initial state.</param>
/// <param name="length">Length of the capsule.</param>
/// <param name="radius">Radius of the capsule.</param>
/// <param name="mass">Mass of the object.</param>
public Capsule(MotionState motionState, float length, float radius, float mass)
: this(length, radius, mass)
{
MotionState = motionState;
}
/// <summary>
/// Constructs a nondynamic capsule.
/// </summary>
/// <param name="motionState">Motion state specifying the entity's initial state.</param>
/// <param name="length">Length of the capsule.</param>
/// <param name="radius">Radius of the capsule.</param>
public Capsule(MotionState motionState, float length, float radius)
: this(length, radius)
{
MotionState = motionState;
}
}
} | 0 | 0.61907 | 1 | 0.61907 | game-dev | MEDIA | 0.653424 | game-dev | 0.542341 | 1 | 0.542341 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 3,018 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/minions/stationary/RoseWraith.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2022 Evan Debenham
*
* Summoning Pixel Dungeon
* Copyright (C) 2019-2022 TrashboxBobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.mobs.minions.stationary;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.FlavourBuff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.powers.MagicPower;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Wraith;
import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.RoseWraithSprite;
public class RoseWraith extends StationaryMinion {
{
spriteClass = RoseWraithSprite.class;
baseDefense = 2;
}
@Override
public int defenseSkill(Char enemy) {
int round = Math.round(super.attackSkill(enemy) * 2.25f);
if (buff(MagicPower.class) != null) round = Math.round(super.attackSkill(enemy) * 1f);
return round;
}
@Override
protected boolean canAttack( Char enemy ) {
return new Ballistica( pos, enemy.pos, Ballistica.FRIENDLY_MAGIC).collisionPos == enemy.pos;
}
@Override
protected boolean doAttack(Char enemy) {
boolean visible = Dungeon.level.heroFOV[pos];
Timer timer = buff(Timer.class);
if (timer == null){
int timing = 6;
switch (lvl){
case 1: timing = 5; break;
case 2: timing = 0; break;
}
if (buff(MagicPower.class) != null) timing /= 3;
if (timing != 0) Buff.affect(this, Timer.class, timing*attackDelay());
Wraith.summonAt(this);
this.damage(1, this);
}
spend(attackDelay());
next();
return !visible;
}
@Override
protected boolean act() {
if (buff(Timer.class) != null) sprite.showStatus(CharSprite.DEFAULT, String.valueOf(buff(Timer.class).cooldown()+1));
return super.act();
}
public static class Timer extends FlavourBuff {
}
}
| 0 | 0.941093 | 1 | 0.941093 | game-dev | MEDIA | 0.997303 | game-dev | 0.943911 | 1 | 0.943911 |
EmbeddedGUI/EmbeddedGUI | 3,418 | porting/pc/sdl2/32/include/SDL2/SDL_gesture.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_gesture.h
*
* Include file for SDL gesture event handling.
*/
#ifndef SDL_gesture_h_
#define SDL_gesture_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_video.h"
#include "SDL_touch.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
typedef Sint64 SDL_GestureID;
/* Function prototypes */
/**
* Begin recording a gesture on a specified touch device or all touch devices.
*
* If the parameter `touchId` is -1 (i.e., all devices), this function will
* always return 1, regardless of whether there actually are any devices.
*
* \param touchId the touch device id, or -1 for all touch devices
* \returns 1 on success or 0 if the specified device could not be found.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetTouchDevice
*/
extern DECLSPEC int SDLCALL SDL_RecordGesture(SDL_TouchID touchId);
/**
* Save all currently loaded Dollar Gesture templates.
*
* \param dst a SDL_RWops to save to
* \returns the number of saved templates on success or 0 on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_LoadDollarTemplates
* \sa SDL_SaveDollarTemplate
*/
extern DECLSPEC int SDLCALL SDL_SaveAllDollarTemplates(SDL_RWops *dst);
/**
* Save a currently loaded Dollar Gesture template.
*
* \param gestureId a gesture id
* \param dst a SDL_RWops to save to
* \returns 1 on success or 0 on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_LoadDollarTemplates
* \sa SDL_SaveAllDollarTemplates
*/
extern DECLSPEC int SDLCALL SDL_SaveDollarTemplate(SDL_GestureID gestureId,SDL_RWops *dst);
/**
* Load Dollar Gesture templates from a file.
*
* \param touchId a touch id
* \param src a SDL_RWops to load from
* \returns the number of loaded templates on success or a negative error code
* (or 0) on failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_SaveAllDollarTemplates
* \sa SDL_SaveDollarTemplate
*/
extern DECLSPEC int SDLCALL SDL_LoadDollarTemplates(SDL_TouchID touchId, SDL_RWops *src);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_gesture_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.885905 | 1 | 0.885905 | game-dev | MEDIA | 0.892652 | game-dev | 0.589495 | 1 | 0.589495 |
SaberZG/GodOfWarWindSimulation | 1,476 | WindSystem/DebugerUI/Scripts/UIFacade.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIFacade
{
private static UIFacade m_Instance;
public static UIFacade Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new UIFacade();
}
return m_Instance;
}
}
public GameObject MainCanvas;
public Camera MainCamera;
public Camera UICamera;
public Transform WindHandlerNode;
public UIFacade()
{
MainCanvas = GameObject.Find("Canvas");
MainCamera = Camera.main;
GameObject cameraObj = GameObject.Find("UICamera");
UICamera = cameraObj ? cameraObj.GetComponent<Camera>() : null;
GameObject whnObj = GameObject.Find("Canvas/WindHandlerNode");
WindHandlerNode = whnObj ? whnObj.transform : null;
}
public void GetWorldPosToScreenPos(Vector3 worldPos, out Vector2 screenPos)
{
screenPos = Vector2.zero;
if (MainCamera)
{
RectTransform canvasRtm = MainCanvas.GetComponent<RectTransform>();
float width = canvasRtm.sizeDelta.x;
float height = canvasRtm.sizeDelta.y;
screenPos = MainCamera.WorldToScreenPoint(worldPos);
screenPos.x *= width / Screen.width;
screenPos.y *= height / Screen.height;
screenPos.x -= width * 0.5f;
screenPos.y -= height * 0.5f;
}
}
}
| 0 | 0.554899 | 1 | 0.554899 | game-dev | MEDIA | 0.617087 | game-dev,graphics-rendering | 0.594126 | 1 | 0.594126 |
qiankanglai/unity_lua_benchmark | 3,746 | tolua-master/Assets/ToLua/BaseType/System_Collections_ObjectModel_ReadOnlyCollectionWrap.cs | using System;
using LuaInterface;
using System.Collections.ObjectModel;
using System.Collections;
public class System_Collections_ObjectModel_ReadOnlyCollectionWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(ReadOnlyCollection<>), typeof(System.Object), "ReadOnlyCollection");
L.RegFunction("Contains", Contains);
L.RegFunction("CopyTo", CopyTo);
L.RegFunction("GetEnumerator", GetEnumerator);
L.RegFunction("IndexOf", IndexOf);
L.RegFunction(".geti", get_Item);
L.RegFunction("get_Item", get_Item);
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("Count", get_Count, null);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Contains(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
Type argType = null;
object obj = ToLua.CheckGenericObject(L, 1, typeof(ReadOnlyCollection<>), out argType);
object arg0 = ToLua.CheckVarObject(L, 2, argType);
bool o = (bool)LuaMethodCache.CallSingleMethod("Contains", obj, arg0);
LuaDLL.lua_pushboolean(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CopyTo(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 3);
Type argType = null;
object obj = ToLua.CheckGenericObject(L, 1, typeof(ReadOnlyCollection<>), out argType);
object arg0 = ToLua.CheckObject(L, 2, argType.MakeArrayType());
int arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
LuaMethodCache.CallSingleMethod("CopyTo", obj, arg0, arg1);
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetEnumerator(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
object obj = ToLua.CheckGenericObject(L, 1, typeof(ReadOnlyCollection<>));
IEnumerator o = (IEnumerator)LuaMethodCache.CallSingleMethod("GetEnumerator", obj);
ToLua.Push(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int IndexOf(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
Type argType = null;
object obj = ToLua.CheckGenericObject(L, 1, typeof(ReadOnlyCollection<>), out argType);
object arg0 = ToLua.CheckVarObject(L, 2, argType);
int o = (int)LuaMethodCache.CallSingleMethod("IndexOf", obj, arg0);
LuaDLL.lua_pushinteger(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_Item(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
object obj = ToLua.CheckGenericObject(L, 1, typeof(ReadOnlyCollection<>));
int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
int o = (int)LuaMethodCache.CallSingleMethod("get_Item", obj, arg0);
LuaDLL.lua_pushinteger(L, o);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_Count(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
int ret = (int)LuaMethodCache.CallSingleMethod("get_Count", o);
LuaDLL.lua_pushinteger(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Count on a nil value" : e.Message);
}
}
}
| 0 | 0.85326 | 1 | 0.85326 | game-dev | MEDIA | 0.659812 | game-dev | 0.790856 | 1 | 0.790856 |
monadgroup/re19 | 1,961 | engine/src/animation/timeline.rs | use super::animation_clip::AnimationClip;
use super::property::PropertyValue;
use super::schema::GeneratorSchema;
use crate::generator::Generator;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
#[derive(Default)]
pub struct Timeline {
pub tracks: Vec<Track>,
}
#[derive(Default)]
pub struct Track {
pub clips: Vec<Clip>,
}
pub enum ClipSource {
Generator(Box<dyn Generator>),
Animation(AnimationClip),
}
impl ClipSource {
pub fn is_generator(&self) -> bool {
match self {
ClipSource::Generator(_) => true,
_ => false,
}
}
pub fn is_animation(&self) -> bool {
match self {
ClipSource::Animation(_) => true,
_ => false,
}
}
pub fn generator(&self) -> Option<&dyn Generator> {
match self {
ClipSource::Generator(gen) => Some(gen.as_ref()),
_ => None,
}
}
pub fn generator_mut(&mut self) -> Option<&mut dyn Generator> {
match self {
ClipSource::Generator(gen) => Some(gen.as_mut()),
_ => None,
}
}
pub fn animation(&self) -> Option<&AnimationClip> {
match self {
ClipSource::Animation(animation) => Some(animation),
_ => None,
}
}
pub fn animation_mut(&mut self) -> Option<&mut AnimationClip> {
match self {
ClipSource::Animation(animation) => Some(animation),
_ => None,
}
}
}
pub struct Clip {
pub id: u32,
#[cfg(debug_assertions)]
pub name: String,
pub schema: &'static GeneratorSchema,
pub source: ClipSource,
pub offset_frames: u32,
pub duration_frames: u32,
pub property_groups: Vec<PropertyGroup>,
pub is_selected: bool,
}
pub struct PropertyGroup {
pub defaults: Vec<PropertyDefault>,
}
pub struct PropertyDefault {
pub value: PropertyValue,
pub is_override: bool,
}
| 0 | 0.750485 | 1 | 0.750485 | game-dev | MEDIA | 0.682505 | game-dev | 0.871774 | 1 | 0.871774 |
bartdeboer/JigLibJS2 | 1,293 | collision/CollisionSystemBrute.js |
JigLib.CollisionSystemBrute = function()
{
JigLib.CollisionSystemAbstract.apply(this, [ ]);
}
JigLib.extend(JigLib.CollisionSystemBrute, JigLib.CollisionSystemAbstract);
JigLib.CollisionSystemBrute.prototype.detectAllCollisions = function(bodies, collArr)
{
var info;
var fu;
var bodyID;
var bodyType;
this._numCollisionsChecks = 0;
for (var bodies_i = 0, bodies_l = bodies.length, _body; (bodies_i < bodies_l) && (_body = bodies[bodies_i]); bodies_i++)
{
if(!_body.isActive)continue;
bodyID = _body.get_id();
bodyType = _body.get_type();
for (var collBody_i = 0, collBody_l = this.collBody.length, _collBody; (collBody_i < collBody_l) && (_collBody = this.collBody[collBody_i]); collBody_i++)
{
if (_body == _collBody)
{
continue;
}
if (_collBody.isActive && bodyID > _collBody.get_id())
{
continue;
}
if (this.checkCollidables(_body, _collBody) && this.detectionFunctors[bodyType + "_" + _collBody.get_type()] != undefined)
{
info = new JigLib.CollDetectInfo();
info.body0 = _body;
info.body1 = _collBody;
fu = this.detectionFunctors[info.body0.get_type() + "_" + info.body1.get_type()];
fu.collDetect(info, collArr);
this._numCollisionsChecks += 1;
}
}
}
}
| 0 | 0.757803 | 1 | 0.757803 | game-dev | MEDIA | 0.734378 | game-dev | 0.69253 | 1 | 0.69253 |
magefree/mage | 2,160 | Mage.Sets/src/mage/cards/h/HeraldOfHadar.java | package mage.cards.h;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.GainLifeEffect;
import mage.abilities.effects.common.LoseLifeOpponentsEffect;
import mage.abilities.effects.common.RollDieWithResultTableEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.game.permanent.token.TreasureToken;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class HeraldOfHadar extends CardImpl {
public HeraldOfHadar(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WARLOCK);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Circle of Death - {5}{B}: Roll a d20.
RollDieWithResultTableEffect effect = new RollDieWithResultTableEffect();
this.addAbility(new SimpleActivatedAbility(
effect, new ManaCostsImpl<>("{5}{B}")
).withFlavorWord("Circle of Death"));
// 1-9 | Each opponent loses 2 life.
effect.addTableEntry(
1, 9,
new LoseLifeOpponentsEffect(2)
);
// 10-19 | Each opponent loses 2 life and you gain 2 life.
effect.addTableEntry(
10, 19,
new LoseLifeOpponentsEffect(2),
new GainLifeEffect(2).concatBy("and")
);
// 20 | Each opponent loses 2 life and you gain 2 life. Create two Treasure tokens.
effect.addTableEntry(
20, 20,
new LoseLifeOpponentsEffect(2),
new GainLifeEffect(2).concatBy("and"),
new CreateTokenEffect(new TreasureToken(), 2).concatBy(".")
);
}
private HeraldOfHadar(final HeraldOfHadar card) {
super(card);
}
@Override
public HeraldOfHadar copy() {
return new HeraldOfHadar(this);
}
}
| 0 | 0.975157 | 1 | 0.975157 | game-dev | MEDIA | 0.982928 | game-dev | 0.998688 | 1 | 0.998688 |
Voluntarynet/voluntary.app | 1,500 | source/library/view/dom_views/subclasses/CloseButton.js | "use strict"
/*
CloseButton
TODO: make subclass of ButtonView?
*/
window.CloseButton = class CloseButton extends DomView {
initPrototype () {
this.newSlot("isEnabled", true)
this.newSlot("iconView", null)
}
init () {
super.init()
this.turnOffUserSelect()
//this.setDisplay("table") // to center svg
const iv = SvgIconView.clone().setIconName("close")
//iv.setDisplay("table-cell") // to center svg
//iv.setVerticalAlign("middle") // to center svg
iv.setHeight("100%").setWidth("100%")
iv.setStrokeColor("white")
iv.setFillColor("white")
this.setIconView(iv)
this.addSubview(iv)
this.setAction("close")
this.addDefaultTapGesture()
return this
}
setIconName (aString) {
this.iconView().setIconName(aString)
return this
}
// --- editable ---
setIsEnabled (aBool) {
if (this._isEnabled !== aBool) {
this._isEnabled = aBool
this.syncEnabled()
}
return this
}
syncEnabled () {
if (this._isEnabled) {
this.setDisplay("block")
} else {
this.setDisplay("none")
}
return this
}
onTapComplete (aGesture) {
//this.debugLog(".onTapComplete()")
if (!this.isEditable()) {
this.sendActionToTarget()
}
return false
}
}.initThisClass()
| 0 | 0.927197 | 1 | 0.927197 | game-dev | MEDIA | 0.509416 | game-dev,web-frontend | 0.967388 | 1 | 0.967388 |
MergHQ/CRYENGINE | 2,323 | Code/GameSDK/GameDll/ActorLuaCache.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*************************************************************************
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Definitions for Lua-caching helpers used by Actors to avoid
Lua accessing at game time
-------------------------------------------------------------------------
History:
- 01:07:2010: Created by Kevin Kirst
*************************************************************************/
#include "StdAfx.h"
#include "ActorLuaCache.h"
#include "Actor.h"
//////////////////////////////////////////////////////////////////////////
void SLuaCache_ActorPhysicsParams::GetMemoryUsage(ICrySizer *s) const
{
s->Add(*this);
}
//////////////////////////////////////////////////////////////////////////
bool SLuaCache_ActorPhysicsParams::CacheFromTable(SmartScriptTable pEntityTable, const char* szEntityClassName)
{
assert((bool)pEntityTable);
if (!bIsCached)
{
bIsCached = CActor::LoadPhysicsParams(pEntityTable, szEntityClassName, params, playerDim, playerDyn);
}
return bIsCached;
}
//////////////////////////////////////////////////////////////////////////
void SLuaCache_ActorGameParams::GetMemoryUsage(ICrySizer *s) const
{
s->Add(*this);
}
//////////////////////////////////////////////////////////////////////////
bool SLuaCache_ActorGameParams::CacheFromTable(SmartScriptTable pEntityTable)
{
assert((bool)pEntityTable);
if (!bIsCached)
{
bIsCached = CActor::LoadGameParams(pEntityTable, gameParams);
bIsCached &= CActor::LoadAutoAimParams(pEntityTable, autoAimParams);
}
return bIsCached;
}
//////////////////////////////////////////////////////////////////////////
void SLuaCache_ActorProperties::GetMemoryUsage(ICrySizer *s) const
{
s->Add(*this);
s->AddContainer(fileModelInfo.IKLimbInfo);
}
//////////////////////////////////////////////////////////////////////////
bool SLuaCache_ActorProperties::CacheFromTable(SmartScriptTable pEntityTable, SmartScriptTable pProperties)
{
assert((bool)pEntityTable);
if (!bIsCached)
{
bIsCached = CActor::LoadFileModelInfo(pEntityTable, pProperties, fileModelInfo);
if (pProperties)
{
pProperties->GetValue("physicMassMult", fPhysicMassMult);
}
}
return bIsCached;
} | 0 | 0.707989 | 1 | 0.707989 | game-dev | MEDIA | 0.809851 | game-dev | 0.549863 | 1 | 0.549863 |
FyroxEngine/Fyrox | 3,857 | fyrox-impl/src/scene/node/container.rs | // Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// 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.
//! A wrapper for node pool record that allows to define custom visit method to have full
//! control over instantiation process at deserialization.
use crate::{
core::{
pool::PayloadContainer,
reflect::prelude::*,
uuid::Uuid,
visitor::{Visit, VisitResult, Visitor},
},
engine::SerializationContext,
scene::node::Node,
};
use fyrox_core::visitor::error::VisitError;
/// A wrapper for node pool record that allows to define custom visit method to have full
/// control over instantiation process at deserialization.
#[derive(Debug, Clone, Default, Reflect)]
pub struct NodeContainer(Option<Node>);
fn read_node(name: &str, visitor: &mut Visitor) -> Result<Node, VisitError> {
let mut region = visitor.enter_region(name)?;
let mut id = Uuid::default();
id.visit("TypeUuid", &mut region)?;
let serialization_context = region
.blackboard
.get::<SerializationContext>()
.expect("Visitor environment must contain serialization context!");
let mut node = serialization_context
.node_constructors
.try_create(&id)
.ok_or_else(|| VisitError::User(format!("Unknown node type uuid {id}!")))?;
node.visit("NodeData", &mut region)?;
Ok(node)
}
fn write_node(name: &str, node: &mut Node, visitor: &mut Visitor) -> VisitResult {
let mut region = visitor.enter_region(name)?;
let mut id = node.id();
id.visit("TypeUuid", &mut region)?;
node.visit("NodeData", &mut region)?;
Ok(())
}
impl Visit for NodeContainer {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
let mut region = visitor.enter_region(name)?;
let mut is_some = u8::from(self.is_some());
is_some.visit("IsSome", &mut region)?;
if is_some != 0 {
if region.is_reading() {
*self = NodeContainer(Some(read_node("Data", &mut region)?));
} else {
write_node("Data", self.0.as_mut().unwrap(), &mut region)?;
}
}
Ok(())
}
}
impl PayloadContainer for NodeContainer {
type Element = Node;
fn new_empty() -> Self {
Self(None)
}
fn new(element: Self::Element) -> Self {
Self(Some(element))
}
fn is_some(&self) -> bool {
self.0.is_some()
}
fn as_ref(&self) -> Option<&Self::Element> {
self.0.as_ref()
}
fn as_mut(&mut self) -> Option<&mut Self::Element> {
self.0.as_mut()
}
fn replace(&mut self, element: Self::Element) -> Option<Self::Element> {
self.0.replace(element)
}
fn take(&mut self) -> Option<Self::Element> {
self.0.take()
}
}
| 0 | 0.917361 | 1 | 0.917361 | game-dev | MEDIA | 0.695232 | game-dev | 0.857017 | 1 | 0.857017 |
ericraio/vanilla-wow-addons | 27,564 | i/ItemRack/localization.lua |
ItemRackText = {}
-- These three strings are the only ones required for the mod to work in other languages. The rest are translations of benign text.
ItemRackText.INVTYPE_CONTAINER = "Bag"
ItemRackText.MOUNTCHECK = "^Increases speed" -- used only for checking if a mount buff is a real one
--[[ Key bindings ]]--
-- Bindings are created dynamically in the mod and are stored per-character with the binding attached to the set.
-- To add more bindings, change .MaxKeyBindings to the desired amount and add more _EQUIPSET here and in Bindings.xml
-- The key bindings is arguably the most complex part of the mod -- localize with care or hold off localizing until last
ItemRackText.BINDINGFORMAT = "Equip Set: %s"
ItemRackText.BINDINGSEARCH = "Equip Set: (.+)"
ItemRackText.MaxKeyBindings = 10
BINDING_HEADER_ItemRack = "ItemRack"
BINDING_NAME_EQUIPSET1 = "Equip Set: 1" -- these values change to string.format of BINDINGFORMAT on the binding owner's set
BINDING_NAME_EQUIPSET2 = "Equip Set: 2"
BINDING_NAME_EQUIPSET3 = "Equip Set: 3"
BINDING_NAME_EQUIPSET4 = "Equip Set: 4"
BINDING_NAME_EQUIPSET5 = "Equip Set: 5"
BINDING_NAME_EQUIPSET6 = "Equip Set: 6"
BINDING_NAME_EQUIPSET7 = "Equip Set: 7"
BINDING_NAME_EQUIPSET8 = "Equip Set: 8"
BINDING_NAME_EQUIPSET9 = "Equip Set: 9"
BINDING_NAME_EQUIPSET10 = "Equip Set: 10"
-- options text. none of the text below will affect how the mod runs. It's just displayed text.
ItemRackText.CONTROL_ROTATE_TEXT = "Rotate"
ItemRackText.CONTROL_ROTATE_tooltip = "Change the orientation of the bar between vertical or horizontal."
ItemRackText.CONTROL_LOCK_TEXT = "Lock"
ItemRackText.CONTROL_LOCK_TOOLTIP = "Lock or unlock the window. While locked, hold ALT and move the mouse over the bar to access controls."
ItemRackText.CONTROL_OPTIONS_TEXT = "Settings"
ItemRackText.CONTROL_OPTIONS_TOOLTIP = "Change ItemRack settings."
ItemRackText.OPT_TOOLTIPFOLLOW_TEXT = "Tooltips at pointer"
ItemRackText.OPT_TOOLTIPFOLLOW_TOOLTIP = "Check this to make tooltips follow the pointer instead of displaying at the default location."
ItemRackText.OPT_COOLDOWNNUMBERS_TEXT = "Cooldown numbers"
ItemRackText.OPT_COOLDOWNNUMBERS_TOOLTIP = "Check this to display the numerical time left in an item's cooldown."
ItemRackText.OPT_SOULBOUND_TEXT = "Hide tradables"
ItemRackText.OPT_SOULBOUND_TOOLTIP = "Check this to only display soulbound, quest or conjured items in the menus. Bind-On-Equip and tradable items will be ignored to prevent showing up as you loot through an instance."
ItemRackText.OPT_BINDINGS_TEXT = "Show key bindings"
ItemRackText.OPT_BINDINGS_TOOLTIP = "Check this to display any key bindings on the bar."
ItemRackText.OPT_MENUSHIFT_TEXT = "Menu on Shift only"
ItemRackText.OPT_MENUSHIFT_TOOLTIP = "Check this to prevent the menu from appearing unless you're holding the Shift key."
ItemRackText.OPT_CLOSE_TEXT = "Close Options"
ItemRackText.OPT_CLOSE_TOOLTIP = "Exit options. To close ItemRack completely, remove all items from the bar or /itemrack."
ItemRackText.INVFRAME_RESIZE_TEXT = "Resize"
ItemRackText.INVFRAME_RESIZE_TOOLTIP = "Drag the 'grip' in the lower right corner to resize the window."
ItemRackText.OPT_SHOWEMPTY_TEXT = "Allow empty slots"
ItemRackText.OPT_SHOWEMPTY_TOOLTIP = "Check this to add empty slots to the swap menu. Items will be dropped in the left-most available bag slot, if one exists. You cannot queue empty slots. Trinkets will not show empty slots if TrinketMenu Clicks is enabled."
ItemRackText.OPT_FLIPMENU_TEXT = "Flip menu"
ItemRackText.OPT_FLIPMENU_TOOLTIP = "The menu grows towards the middle of the screen by default. Check this to make the menu grow from the opposite side that it automatically chooses."
ItemRackText.OPT_RIGHTCLICK_TEXT = "TrinketMenu mode"
ItemRackText.OPT_RIGHTCLICK_TOOLTIP = "Check this to make left-clicking a trinket go to the top trinket slot (as displayed on your character screen), and right-click to go to the bottom trinket slot. Trinket pairs on the bar together will share one menu as well."
ItemRackText.OPT_TINYTOOLTIP_TEXT = "Use tiny tooltips"
ItemRackText.OPT_TINYTOOLTIP_TOOLTIP = "Check this to make item tooltips only show name, durability and cooldown."
ItemRackText.OPT_SHOWTOOLTIPS_TEXT = "Show tooltips"
ItemRackText.OPT_SHOWTOOLTIPS_TOOLTIP = "Check this to show tooltips."
ItemRackText.OPT_NOTIFY_TEXT = "Notify when ready"
ItemRackText.OPT_NOTIFY_TOOLTIP = "Check this to display a message when a used item has finished cooldown."
ItemRackText.OPT_ROTATEMENU_TEXT = "Rotate menu"
ItemRackText.OPT_ROTATEMENU_TOOLTIP = "The menu grows perpendicular to the bar by default. Check this to make it grow parallel to the bar."
ItemRackText.OPT_SHOWICON_TEXT = "Minimap button"
ItemRackText.OPT_SHOWICON_TOOLTIP = "Check this to display a button around the edge of the minimap to access options and sets."
ItemRackText.OPT_DISABLETOGGLE_TEXT = "Minimap sets menu"
ItemRackText.OPT_DISABLETOGGLE_TOOLTIP = "Check this to toggle the set menu on left click. Uncheck to toggle the bar on left click."
ItemRackText.OPT_FLIPBAR_TEXT = "Flip bar growth"
ItemRackText.OPT_FLIPBAR_TOOLTIP = "The bar grows down or to the right by default. Check this to make it grow leftwards or upwards."
ItemRackText.OPT_ENABLEEVENTS_TEXT = "Enable Events"
ItemRackText.OPT_ENABLEEVENTS_TOOLTIP = "Check this to allow automated events enabled below to swap gear based on conditions defined within the events.\n\nUncheck to stop all event processing."
ItemRackText.OPT_SHOWALLEVENTS_TEXT = "Show All"
ItemRackText.OPT_SHOWALLEVENTS_TOOLTIP = "Check this to show all events for all classes.\n\nUncheck to prevent sets for other classes from listing."
ItemRackText.OPT_COMPACTLIST_TEXT = "Compact"
ItemRackText.OPT_COMPACTLIST_TOOLTIP = "Check this to list sets in a more compact form to see more at once."
ItemRackText.OPT_SAVEDSETSCLOSE_TEXT = "Cancel"
ItemRackText.OPT_SAVEDSETSCLOSE_TOOLTIP = "Cancel choosing a set."
ItemRackText.OPT_NOTIFYTHIRTY_TEXT = "Notify at 30 secs"
ItemRackText.OPT_NOTIFYTHIRTY_TOOLTIP = "Check this to notify at the 30-second mark instead of when an item's cooldown ends."
ItemRackText.OPT_ALLOWHIDDEN_TEXT = "Allow hidden items"
ItemRackText.OPT_ALLOWHIDDEN_TOOLTIP = "Check this to allow menu items to be hidden with ALT+click. To recover a hidden item on the menu, hold ALT as you enter the bar and ALT+click the item again."
ItemRackText.OPT_LARGEFONT_TEXT = "Large Font"
ItemRackText.OPT_LARGEFONT_TOOLTIP = "Check this to use a bigger font in the script edit window below."
ItemRackText.OPT_SQUAREMINIMAP_TEXT = "Square minimap"
ItemRackText.OPT_SQUAREMINIMAP_TOOLTIP = "Check this to have the minimap button drag around the full square of the minimap."
ItemRackText.OPT_BIGCOOLDOWN_TEXT = "Large cooldown"
ItemRackText.OPT_BIGCOOLDOWN_TOOLTIP = "Check this to make cooldown numbers bigger, resembling Cooldown Count."
ItemRackText.OPT_SETLABELS_TEXT = "Show set icon labels"
ItemRackText.OPT_SETLABELS_TOOLTIP = "Check this to show set labels on set icons."
ItemRackText.OPT_AUTOTOGGLE_TEXT = "Auto toggle sets"
ItemRackText.OPT_AUTOTOGGLE_TOOLTIP = "Check this to make chosing a set always toggle it: If equipped it will revert to gear it replaced. If unequipped it will equip the set.\nThis is the same as choosing a set while Shift is held.\nNote: This behavior does not happen while in combat or dead, since it can't be sure what you're going to wear in the future."
ItemRackText.SETS_CLOSE_TEXT = "Close Set Builder"
ItemRackText.SETS_CLOSE_TOOLTIP = "Exit Set Builder. To close ItemRack completely, remove all items from the bar or /itemrack."
ItemRackText.SETS_NAMELABEL_TEXT = "Choose a name and icon:"
ItemRackText.SETS_HIDESET_TEXT = "Hide"
ItemRackText.SETS_HIDESET_TOOLTIP = "When checked, this set will not appear in the popup menu on the rack. Note: The set icon on the rack will always reflect the last set equipped, hidden or not.\n\nHold ALT while you mouseover sets on the bar to see hidden sets. You can ALT+click sets in the menu to toggle their hidden status."
ItemRackText.SETS_BINDBUTTON_TEXT = "Bind Key"
ItemRackText.SETS_BINDBUTTON_TOOLTIP = "Bind a key to this set."
ItemRackText.SETS_SAVEBUTTON_TEXT = "Save"
ItemRackText.SETS_SAVEBUTTON_TOOLTIP = "Save this set as the name given above. Except for key bindings, changes made to an existing set are not permanent until you save."
ItemRackText.SETS_REMOVEBUTTON_TEXT = "Remove"
ItemRackText.SETS_REMOVEBUTTON_TOOLTIP = "Remove this set definition. To keep a set but prevent it from showing on the menu, check Hide below the set's icon and then save."
ItemRackText.SETS_LOADBUTTON_TEXT = "Equip"
ItemRackText.SETS_LOADBUTTON_TOOLTIP = "Equip the selected set."
ItemRackText.READY = "%s ready!"
ItemRackText.READYTHIRTY = "%s ready soon!"
ItemRackText.QUEUED = "Queued: %s"
ItemRackText.SAVED = "Set %s saved with %d items."
ItemRackText.BINDCLEAR = "Binding cleared for this set."
ItemRackText.BINDSET = "Set bound to key %s"
ItemRackText.ERROR_MISSING = "ItemRack: Some items were not found: "
ItemRackText.ERROR_NOROOM = "ItemRack: Not enough free bag space to complete swap."
ItemRackText.COUNTFORMAT = "%s slots"
ItemRackText.NOSAVEDSETS = "No saved sets."
ItemRackText.SETTOOLTIPFORMAT = "Set: %s"
ItemRackText.SETREMOVE = "Set %s removed."
ItemRackText.EMPTYSET = ""
ItemRackText.SETTOOLTIPCOUNT = "%s items"
ItemRackText.SETTOOLTIPMISSING = "%s missing"
ItemRackText.EVENTSSUSPENDED = "Note: Event processing is suspended\nwhile this window is up."
ItemRackText.UNDEFINEDEVENT_TEXT = "Not Defined Yet"
ItemRackText.UNDEFINEDEVENT_TOOLTIP = "Click here to associate a set with this event. You can edit the event to use multiple sets per event, but all events must have one set associated with it before it can be used."
ItemRackText.ENABLEEVENT_TEXT = "Enable Event"
ItemRackText.ENABLEEVENT_TOOLTIP = "Check this to enable this particular event. Uncheck to disable the event. Use the 'Enable' checkbox at the top as a master on/off for events."
ItemRackText.EVENTSDELETE_TEXT = "Delete Event"
ItemRackText.EVENTSDELETE_TOOLTIP = "Delete this event. If any other characters on this account use this event, it will revert to an undefined state for this character."
ItemRackText.EVENTSEDIT_TEXT = "Edit Event"
ItemRackText.EVENTSEDIT_TOOLTIP = "Edit this event.\n\nSome knowledge of lua or WoW macros helps immensely in dealing with events.\n\nYou cannot associate a set with this event by editing it. Click the set icon in the list above to associate a set."
ItemRackText.EVENTSNEW_TEXT = "New Event"
ItemRackText.EVENTSNEW_TOOLTIP = "Create a new event.\n\nSome knowledge of lua or WoW macros helps immensely in dealing with events."
ItemRackText.EVENTSSAVE_TEXT = "Save Event"
ItemRackText.EVENTSSAVE_TOOLTIP = "Save this event. You can save unfinished events, just be sure not to associate them with any set until it's ready.\n\nIf the name of an existing event is changed, a COPY is made under the new name."
ItemRackText.EVENTSTEST_TEXT = "Test Script"
ItemRackText.EVENTSTEST_TOOLTIP = "Test the above script by running it once now. This is mostly to catch syntax or other errors that would produce a red error window. It can't test the trigger or ensure the script will have desired results."
ItemRackText.EVENTSCANCEL_TEXT = "Return to Events"
ItemRackText.EVENTSCANCEL_TOOLTIP = "This will cancel any unsaved changes and return to the events list."
ItemRackText.EVENTNAME_TEXT = "Event Name"
ItemRackText.EVENTNAME_TOOLTIP = "This is the name of the event as listed in the previous window. ie, \"Riding\", \"Warrior:Berserker\", etc\n\nPrefix a name with Class: to let the 'Show All' option filter events by classes, ie, \"Priest:Shadowform\""
ItemRackText.EVENTTRIGGER_TEXT = "Event Trigger"
ItemRackText.EVENTTRIGGER_TOOLTIP = "This is the trigger fired from WoW when you want the event to occur.\n\nSome common ones:\nPLAYER_AURAS_CHANGED : When your buffs or forms change.\nPLAYER_REGEN_DISABLED : When you enter combat mode.\nPLAYER_REGEN_ENABLED : When you leave combat mode.\n\nwww.wowwiki.com/Events lists them all."
ItemRackText.EVENTDELAY_TEXT = "Event Delay"
ItemRackText.EVENTDELAY_TOOLTIP = "This is the time (in seconds) after the latest trigger before performing this event. A zero here will immediately perform the event each trigger. Some triggers can happen many times in a flurry, such as BAG_UPDATE. A delay here will ensure the event runs a single time once the flurry of triggers are over."
ItemRackText.RESETBUTTON_TEXT = "Reset Bar"
ItemRackText.RESETBUTTON_TOOLTIP = "Click this to restore the windows and scales to a default state in the event you lose them off the screen or shrink them too small to resize. Events, sets and items on the bar are not affected."
ItemRackText.RESETEVENTSBUTTON_TEXT = "Reset Events"
ItemRackText.RESETEVENTSBUTTON_TOOLTIP = "Click this to restore events (Mount, Plaguelands, etc) to their default state. Custom events will be removed. NOTE: THIS WILL REMOVE CUSTOM EVENTS"
ItemRackText.DisableToggleText = {
["ON"] = "Left click: toggle sets menu\nRight click: toggle config\nDrag: move icon",
["OFF"] = "Left click: toggle bar\nRight click: toggle config\nDrag: move icon"
}
ItemRackText.HELP = "This is a mod to make swapping equipment easier. You add equipment slots to a bar and mouseover on the bar will create a menu of all items in your bags that can go in that slot.\n\nTo move the minimap button, drag it like you would an ordinary window.\n\nTo set up:\n1. Open your character sheet. (C key is default)\n2. Alt+Click slots in the character sheet to add them to the bar.\n3. Alt+Click yourself in the character sheet to add sets to the bar.\n4. Use Alt+Click to remove slots/sets from the bar as well.\n\nTo use:\nMouseover a slot you added to the bar and it will present a menu of all items in your bags that can go in that slot.\nClick an item in the menu to swap to that item.\nClick an item on the bar to use that item if it's usable.\n\nTo create a set:\n1. Select which slots to save by clicking the slots around this window.\n2. Highlighted slots will save to the set, darkened slots will be ignored.\n3. If needed, swap to the gear you want to save to this set.\n4. Enter a name at the top of the sets window.\n5. Choose an icon below the name.\n6. Click Save.\n\nTo use a set, one of:\n- Bind a key to the set with 'Bind Key' button.\n- Swap from the bar as you would an item.\n- /script EquipSet(\"setname\") in a macro."
-- German translation by Leelaa at http://www.curse-gaming.com/mod.php?addid=2045
if (GetLocale() == "deDE") then
ItemRackText.INVTYPE_CONTAINER = "Beh\195\164lter"
ItemRackText.MOUNTCHECK = "^Erh\195\182ht Tempo" -- fix by Yarok
ItemRackText.CONTROL_ROTATE_TEXT = "Rotieren"
ItemRackText.CONTROL_ROTATE_TOOLTIP = "\195\132ndern der Ausrichtung der Leiste zwischen horizontal und vertikal."
ItemRackText.CONTROL_LOCK_TEXT = "Sperren"
ItemRackText.CONTROL_LOCK_TOOLTIP = "Sperren oder entsperren des Fensters. Wenn gesperrt, ALT halten und mit der Maus \195\188ber das Fenster fahren um die Kontrollen zu sehen."
ItemRackText.CONTROL_OPTIONS_TEXT = "Einstellungen"
ItemRackText.CONTROL_OPTIONS_TOOLTIP = "ItemRack Einstellungen ver\195\164ndern."
ItemRackText.OPT_TOOLTIPFOLLOW_TEXT = "Tooltips am Zeiger"
ItemRackText.OPT_TOOLTIPFOLLOW_TOOLTIP = "Hier einen Haken setzen, um die Tooltips dem Mauszeiger folgen zu lassen."
ItemRackText.OPT_COOLDOWNNUMBERS_TEXT = "Cooldown Z\195\164hler"
ItemRackText.OPT_COOLDOWNNUMBERS_TOOLTIP = "Hier einen Haken setzen, um einen numerischen Z\195\164hler f\195\188r die restliche Cooldown-Zeit einzublenden."
ItemRackText.OPT_SOULBOUND_TEXT = "Handelbares verstecken"
ItemRackText.OPT_SOULBOUND_TOOLTIP = "Hier einen Haken setzen um nur seelengebundene-, Quest- oder herbeigezauberte Gegenst\195\164nde in den Men\195\188s anzuzeigen. Bei-Aufheben-Gebundene und handelbare Gegenst\195\164nde werden ignoriert um die Anzeige zu verhindern."
ItemRackText.OPT_BINDINGS_TEXT = "Tastenbelegungen"
ItemRackText.OPT_BINDINGS_TOOLTIP = "Hier einen Haken setzen um die Tastenbelegungen anzuzeigen."
ItemRackText.OPT_MENUSHIFT_TEXT = "Men\195\188 bei Shift"
ItemRackText.OPT_MENUSHIFT_TOOLTIP = "Hier einen Haken setzen um zu verhindern, dass das Men\195\188 erscheint ohne das Shift gedr\195\188ckt wird."
ItemRackText.OPT_CLOSE_TEXT = "Optionen schliessen"
ItemRackText.OPT_CLOSE_TOOLTIP = "Optionen verlassen. Um ItemRack vollst\195\164ndig zu schliessen m\195\188ssen alle Gegenst\195\164nde entfernt werden oder /itemrack eingeben."
ItemRackText.INVFRAME_RESIZE_TEXT = "Gr\195\182\195\159enanpassung"
ItemRackText.INVFRAME_RESIZE_TOOLTIP = "Den 'Griff' in der rechten unteren Ecke ziehen um die Fenstergr\195\182\195\159e anzupassen."
ItemRackText.OPT_SHOWEMPTY_TEXT = "Leere Pl\195\164tze erlauben"
ItemRackText.OPT_SHOWEMPTY_TOOLTIP = "Hier einen Haken setzen um es zu erm\195\182glichen, leere Inventarpl\195\164tze in den Men\195\188s hinzuzuf\195\188gen. Gegenst\195\164nde werden im \195\164u\195\159erst linken freien Taschenplatz abgelegt, wenn einer existiert. Man kann leere Pl\195\164tze nicht in die Queue legen. Trinkets haben keine leeren Pl\195\164tze wenn TrinketMenu Clicks aktiviert ist."
ItemRackText.OPT_FLIPMENU_TEXT = "Men\195\188 umdrehen"
ItemRackText.OPT_FLIPMENU_TOOLTIP = "Die Richtung des Men\195\188s w\195\164chst rechtwinklig zur Leiste. Hier einen Haken setzen um das Men\195\188 auf der entgegengesetzen Seite erscheinen zu lassen, welche automatisch gew\195\164hlt w\195\188rde."
ItemRackText.OPT_RIGHTCLICK_TEXT = "TrinketMenu Clicks"
ItemRackText.OPT_RIGHTCLICK_TOOLTIP = "Hier einen Haken setzen, damit ein Linksclick auf ein Trinket dieses in den obersten Trinketplatz einwechselt, und ein Rechtsclick in den unteren Trinketplatz einwechselt. (Falls man an TrinketMenu gew\195\182hnt ist)"
ItemRackText.OPT_TINYTOOLTIP_TEXT = "Winzige Tooltips"
ItemRackText.OPT_TINYTOOLTIP_TOOLTIP = "Hier einen Haken setzen damit die Tooltips nur den Namen, die Haltbarkeit und den Cooldown anzeigen."
ItemRackText.OPT_SHOWTOOLTIPS_TEXT = "Tooltips anzeigen"
ItemRackText.OPT_SHOWTOOLTIPS_TOOLTIP = "Hier einen Haken setzen um Tooltips anzuzeigen."
ItemRackText.OPT_NOTIFY_TEXT = "Benachrichtigen wenn bereit"
ItemRackText.OPT_NOTIFY_TOOLTIP = "Hier einen Haken setzen um eine Nachricht zu erhalten wenn ein Cooldown abgelaufen ist."
ItemRackText.READY = "%s bereit!"
ItemRackText.QUEUED = "In Warteschlange: %s"
end
-- French translation by Tinou at http://www.curse-gaming.com/mod.php?addid=2045
if (GetLocale() == "frFR") then
ItemRackText.INVTYPE_CONTAINER = "Conteneur"
ItemRackText.MOUNTCHECK = "^Augmente la vitesse de"
end
--[[ Extra Icons
Here you can add more icons available for use in the set builder.
There are two ways to add an icon:
1. Draw your own 64x64 uncompressed 32-bit TGA file and put it into Interface\Icons
2. Use a "built-in" icon by adding its exact path/name to the list below.
The icons below will list immediately after the icons for the worn gear in the order
they are listed here. If you draw your own icon and put it into Interface\Icons,
you do not need to list it here. They will be picked up automatically.
]]
ItemRackExtraIcons = {
"Interface\\Icons\\INV_Banner_02",
"Interface\\Icons\\INV_Banner_03",
-- add new icons here in this format: "Interface\\Icons\\(ExactIconName)",
}
--[[ Events
These are the default events. They are locale-specific.
/itemrack reset events : Will restore events to a default state
]]
ItemRack_DefaultEvents = {
["Druid:Caster Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "if not ItemRack_GetForm() and IR_FORM then EquipSet() IR_FORM=nil end --[[Equip a set when not in an animal form.]]",
},
["Druid:Aquatic Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local form=ItemRack_GetForm() if form==\"Aquatic Form\" and IR_FORM~=form then EquipSet() IR_FORM=form end --[[Equip a set when in aquatic form.]]",
},
["Druid:Moonkin Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local form=ItemRack_GetForm() if form==\"Moonkin Form\" and IR_FORM~=form then EquipSet() IR_FORM=form end --[[Equip a set when in moonkin form.]]",
},
["Insignia Used"] = {
["trigger"] = "ITEMRACK_ITEMUSED",
["delay"] = 0.5,
["script"] = "if arg1==\"Insignia of the Alliance\" or arg1==\"Insignia of the Horde\" then EquipSet() end --[[Equips a set when the Insignia of the Alliance/Horde has been used.]]",
},
["Plaguelands"] = {
["trigger"] = "ZONE_CHANGED_NEW_AREA",
["delay"] = 1,
["script"] = "local zone = GetRealZoneText(),0\nif (zone==\"Western Plaguelands\" or zone==\"Eastern Plaguelands\" or zone==\"Scholomance\" or zone==\"Stratholme\") and not IR_PLAGUE then\n EquipSet() IR_PLAGUE=1\nelseif IR_PLAGUE then\n LoadSet() IR_PLAGUE=nil\nend\n--[[Equips set to be worn while in plaguelands.]]",
},
["Druid:Cat Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local form=ItemRack_GetForm() if form==\"Cat Form\" and IR_FORM~=form then EquipSet() IR_FORM=form end --[[Equip a set when in cat form.]]",
},
["Low Mana"] = {
["trigger"] = "UNIT_MANA",
["delay"] = 0.5,
["script"] = "local mana = UnitMana(\"player\") / UnitManaMax(\"player\")\nif mana < .5 and not IR_OOM then\n SaveSet()\n EquipSet()\n IR_OOM = 1\nelseif IR_OOM and mana > .75 then\n LoadSet()\n IR_OOM = nil\nend\n--[[Equips a set when mana is below 50% and re-equips previous gear at 75% mana. Remember: You can't swap non-weapons in combat.]]",
},
["Rogue:Stealth"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local _,_,isActive = GetShapeshiftFormInfo(1)\nif isActive and not IR_FORM then\n EquipSet() IR_FORM=1\nelseif not isActive and IR_FORM then\n LoadSet() IR_FORM=nil\nend\n--[[Equips set to be worn while stealthed.]]",
},
["Mage:Evocation"] = {
["trigger"] = "ITEMRACK_BUFFS_CHANGED",
["delay"] = 0.25,
["script"] = "local evoc=arg1[\"Interface\\\\Icons\\\\Spell_Nature_Purge\"]\nif evoc and not IR_EVOC then\n EquipSet() IR_EVOC=1\nelseif not evoc and IR_EVOC then\n LoadSet() IR_EVOC=nil\nend\n--[[Equips a set to wear while channeling Evocation.]]",
},
["Warrior:Berserker"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local _,_,isActive = GetShapeshiftFormInfo(3) if isActive and IR_FORM~=\"Berserker\" then EquipSet() IR_FORM=\"Berserker\" end --[[Equips set to be worn in Berserker stance.]]",
},
["Druid:Bear Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local form = ItemRack_GetForm()\nif (form==\"Dire Bear Form\" or form==\"Bear Form\") and IR_FORM~=\"Bear Form\" then EquipSet() IR_FORM=\"Bear Form\" end --[[Equip a set when in bear form.]]",
},
["Priest:Spirit Tap Begin"] = {
["trigger"] = "PLAYER_REGEN_ENABLED",
["delay"] = 0.25,
["script"] = "local found=ItemRack.Buffs[\"Interface\\\\Icons\\\\Spell_Shadow_Requiem\"]\nif not IR_SPIRIT and found then\nEquipSet() IR_SPIRIT=1\nend\n--[[Equips a set when you leave combat with Spirit Tap. Associate a set of spirit gear to this event.]]",
},
["Priest:Spirit Tap End"] = {
["trigger"] = "ITEMRACK_BUFFS_CHANGED",
["delay"] = 0.5,
["script"] = "local found=arg1[\"Interface\\\\Icons\\\\Spell_Shadow_Requiem\"]\nif IR_SPIRIT and not found then\nLoadSet() IR_SPIRIT = nil\nend\n--[[Returns to normal gear when Spirit Tap ends. Associate the same spirit set as Spirit Tap Begin.]]",
},
["Warrior:Battle"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local _,_,isActive = GetShapeshiftFormInfo(1) if isActive and IR_FORM~=\"Battle\" then EquipSet() IR_FORM=\"Battle\" end --[[Equips set to be worn in battle stance.]]",
},
["Skinning"] = {
["trigger"] = "UPDATE_MOUSEOVER_UNIT",
["delay"] = 0,
["script"] = "if UnitIsDead(\"mouseover\") and GameTooltipTextLeft3:GetText()==UNIT_SKINNABLE then\n local r,g,b = GameTooltipTextLeft3:GetTextColor()\n if r>.9 and g<.2 and b<.2 and not IR_SKIN then\n EquipSet() IR_SKIN=1\n end\nelseif IR_SKIN then\n LoadSet() IR_SKIN=nil\nend\n--[[Equips a set when you mouseover something that can be skinned but you have insufficient skill.]]\n",
},
["Warrior:Overpower End"] = {
["trigger"] = "CHAT_MSG_COMBAT_SELF_MISSES",
["delay"] = 5,
["script"] = "--[[Equip a set five seconds after opponent dodged: your normal weapons. ]]\nif IR_OVERPOWER==1 then\nEquipSet()\nIR_OVERPOWER=nil\nend",
},
["Druid:Travel Form"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local form=ItemRack_GetForm() if form==\"Travel Form\" and IR_FORM~=form then EquipSet() IR_FORM=form end --[[Equip a set when in travel form.]]",
},
["Mount"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local mount\nif UnitIsMounted then mount = UnitIsMounted(\"player\") else mount = ItemRack_PlayerMounted() end\nif not IR_MOUNT and mount then\n EquipSet()\nelseif IR_MOUNT and not mount then\n LoadSet()\nend\nIR_MOUNT=mount\n--[[Equips set to be worn while mounted.]]",
},
["Swimming"] = {
["trigger"] = "MIRROR_TIMER_START",
["delay"] = 0,
["script"] = "local i,found\nfor i=1,3 do\n if getglobal(\"MirrorTimer\"..i):IsVisible() and getglobal(\"MirrorTimer\"..i..\"Text\"):GetText() == BREATH_LABEL then\n found = 1\n end\nend\nif found then\n EquipSet()\nend\n--[[Equips a set when the breath gauge appears. NOTE: This will not re-equip gear when you leave water. There's no reliable way to know when you leave water. Also note: Won't work with eCastingBar.]]",
},
["Eating-Drinking"] = {
["trigger"] = "ITEMRACK_BUFFS_CHANGED",
["delay"] = 0,
["script"] = "local found=arg1[\"Interface\\\\Icons\\\\INV_Misc_Fork&Knife\"] or arg1[\"Drink\"]\nif not IR_DRINK and found then\nEquipSet() IR_DRINK=1\nelseif IR_DRINK and not found then\nLoadSet() IR_DRINK=nil\nend\n--[[Equips a set while eating or drinking.]]",
},
["Warrior:Defensive"] = {
["trigger"] = "PLAYER_AURAS_CHANGED",
["delay"] = 0,
["script"] = "local _,_,isActive = GetShapeshiftFormInfo(2) if isActive and IR_FORM~=\"Defensive\" then EquipSet() IR_FORM=\"Defensive\" end --[[Equips set to be worn in Defensive stance.]]",
},
["Insignia"] = {
["trigger"] = "ITEMRACK_NOTIFY",
["delay"] = 0,
["script"] = "if arg1==\"Insignia of the Alliance\" or arg1==\"Insignia of the Horde\" then EquipSet() end --[[Equips a set when the Insignia of the Alliance/Horde finishes cooldown.]]",
},
["Priest:Shadowform"] = {
["trigger"] = "ITEMRACK_BUFFS_CHANGED",
["delay"] = 0,
["script"] = "local f=arg1[\"Interface\\\\Icons\\\\Spell_Shadow_Shadowform\"]\nif not IR_Shadowform and f then\n EquipSet() IR_Shadowform=1\nelseif IR_Shadowform and not f then\n LoadSet() IR_Shadowform=nil\nend\n--[[Equips a set while under Shadowform]]",
},
["Warrior:Overpower Begin"] = {
["trigger"] = "CHAT_MSG_COMBAT_SELF_MISSES",
["delay"] = 0,
["script"] = "--[[Equip a set when the opponent dodges. Associate a heavy-hitting 2h set with this event. ]]\nlocal _,_,i = GetShapeshiftFormInfo(1)\nif string.find(arg1 or \"\",\"^You.+dodge[sd]\") and i then\nEquipSet()\nIR_OVERPOWER=1\nend",
},
["About Town"] = {
["trigger"] = "PLAYER_UPDATE_RESTING",
["delay"] = 0,
["script"] = "if IsResting() and not IR_TOWN then EquipSet() IR_TOWN=1 elseif IR_TOWN then LoadSet() IR_TOWN=nil end\n--[[Equips a set while in a city or inn.]]"
}
}
| 0 | 0.896228 | 1 | 0.896228 | game-dev | MEDIA | 0.8635 | game-dev | 0.801005 | 1 | 0.801005 |
Mixinors/Astromine | 6,681 | src/main/java/com/github/mixinors/astromine/common/manager/RocketManager.java | package com.github.mixinors.astromine.common.manager;
import com.github.mixinors.astromine.common.rocket.Rocket;
import com.github.mixinors.astromine.registry.common.AMStaticComponents;
import com.github.mixinors.astromine.registry.common.AMWorlds;
import dev.architectury.networking.NetworkManager;
import dev.vini2003.hammer.core.api.client.util.InstanceUtil;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtIo;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.WorldSavePath;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.Collection;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import static com.github.mixinors.astromine.registry.common.AMNetworking.SYNC_ROCKETS;
public class RocketManager {
public static Rocket readFromNbt(NbtCompound rocketTag) {
return new Rocket(rocketTag);
}
@NotNull
public static Rocket create(UUID ownerUuid, UUID uuid) {
var rocket = new Rocket(uuid, ownerUuid, findUnoccupiedSpace());
return add(rocket);
}
private static Rocket add(Rocket rocket) {
var server = InstanceUtil.getServer();
if (server == null) throw new RuntimeException("Server is null.");
var component = AMStaticComponents.getRockets();
component.add(rocket);
sync(server);
return rocket;
}
@Nullable
public static Rocket get(UUID uuid) {
var component = AMStaticComponents.getRockets();
return component.get(uuid);
}
@Nullable
public static Rocket get(ChunkPos interiorPos) {
return getRockets()
.stream()
.filter(rocket -> rocket.getInteriorPos().equals(interiorPos))
.findFirst()
.orElse(null);
}
public static Collection<Rocket> getRockets() {
var component = AMStaticComponents.getRockets();
return component.getAll();
}
private static ChunkPos findUnoccupiedSpace() {
var occupiedPositions = RocketManager
.getRockets()
.stream()
.map(Rocket::getInteriorPos)
.collect(Collectors.toSet());
var random = new Random();
ChunkPos chunkPos = null;
while (chunkPos == null || occupiedPositions.contains(chunkPos)) {
var bound = 16_000_000 / 16;
var x = random.nextInt(bound);
var y = random.nextInt(bound);
chunkPos = new ChunkPos(x - (x % 32), y - (y % 32));
}
return chunkPos;
}
public static void teleportToRocketInterior(PlayerEntity player, UUID uuid) {
var rocket = get(uuid);
if (rocket == null) rocket = create(player.getUuid(), uuid);
if (rocket == null) return;
var chunkPos = rocket.getInteriorPos();
var placer = rocket.getPlacer(player.getUuid());
if (placer == null) {
placer = new Rocket.Placer(player.getWorld().getRegistryKey(), player.getX(), player.getY(), player.getZ(), player.getYaw(), player.getPitch());
rocket.setPlacer(player.getUuid(), placer);
}
if (player instanceof ServerPlayerEntity serverPlayer) {
var server = player.getServer();
if (server == null) return;
var world = server.getWorld(AMWorlds.ROCKET_INTERIORS);
if (world == null) return;
serverPlayer.teleport(world, chunkPos.x * 16.0F + 3.5F, 1.0F, chunkPos.z * 16.0F + 3.5F, 270.0F, 0.0F);
}
}
public static void teleportToPlacer(PlayerEntity player, UUID uuid) {
var rocket = get(uuid);
if (rocket == null) return;
var placer = rocket.getPlacer(player.getUuid());
if (placer != null) {
if (player instanceof ServerPlayerEntity serverPlayer) {
var server = player.getServer();
if (server == null) return;
var world = server.getWorld(placer.worldKey());
if (world == null) return;
serverPlayer.teleport(world, placer.x(), placer.y(), placer.z(), placer.yaw(), placer.pitch());
}
} else {
if (player instanceof ServerPlayerEntity serverPlayer) {
var server = serverPlayer.getServer();
if (server == null) return;
var world = server.getWorld(World.OVERWORLD);
if (world == null) return;
serverPlayer.teleport(world.getSpawnPos().getX(), world.getSpawnPos().getY(), world.getSpawnPos().getZ());
}
}
}
public static void onSync(PacketByteBuf buf, NetworkManager.PacketContext context) {
var nbt = buf.readNbt();
context.queue(() -> {
var component = AMStaticComponents.getRockets();
component.readFromNbt(nbt);
});
}
public static void onPlayerJoin(ServerPlayNetworkHandler handler, PacketSender sender, MinecraftServer server) {
sync(server);
}
public static void onServerStarting(MinecraftServer server) {
var fabricLoader = FabricLoader.getInstance();
if (fabricLoader == null) return;
var worldDir = server.getSavePath(WorldSavePath.ROOT).toFile();
var rocketsFile = worldDir.toPath().resolve("data").resolve("stations.dat").toFile();
if (rocketsFile.exists()) {
var rocketsNbt = new NbtCompound();
try {
rocketsNbt = NbtIo.read(rocketsFile);
} catch (IOException e) {
e.printStackTrace();
}
AMStaticComponents.getRockets().readFromNbt(rocketsNbt);
}
}
public static void onServerStopping(MinecraftServer server) {
var fabricLoader = FabricLoader.getInstance();
if (fabricLoader == null) return;
var worldDir = server.getSavePath(WorldSavePath.ROOT).toFile();
var rocketFile = worldDir.toPath().resolve("data").resolve("rockets.dat").toFile();
var rocketsNbt = new NbtCompound();
AMStaticComponents.getRockets().writeToNbt(rocketsNbt);
try {
// TODO: Use NbtIo#writeCompressed.
NbtIo.write(rocketsNbt, rocketFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sync(MinecraftServer server) {
var component = AMStaticComponents.getRockets();
var nbt = new NbtCompound();
component.writeToNbt(nbt);
var playerManager = server.getPlayerManager();
if (playerManager == null) return;
var playerList = playerManager.getPlayerList();
if (playerList == null) return;
var buf = PacketByteBufs.create();
buf.writeNbt(nbt);
for (var player : playerList) {
ServerPlayNetworking.send(player, SYNC_ROCKETS, PacketByteBufs.duplicate(buf));
}
}
}
| 0 | 0.855722 | 1 | 0.855722 | game-dev | MEDIA | 0.782517 | game-dev,networking | 0.959245 | 1 | 0.959245 |
chukong/SampleGame-WagonWar | 8,477 | cocos2d/cocos/2d/CCAction.h | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __ACTIONS_CCACTION_H__
#define __ACTIONS_CCACTION_H__
#include "CCRef.h"
#include "CCGeometry.h"
NS_CC_BEGIN
class Node;
/**
* @addtogroup actions
* @{
*/
/**
@brief Base class for Action objects.
*/
class CC_DLL Action : public Ref, public Clonable
{
public:
/// Default tag used for all the actions
static const int INVALID_TAG = -1;
/**
* @js NA
* @lua NA
*/
virtual std::string description() const;
/** returns a clone of action */
virtual Action* clone() const = 0;
/** returns a new action that performs the exactly the reverse action */
virtual Action* reverse() const = 0;
//! return true if the action has finished
virtual bool isDone() const;
//! called before the action start. It will also set the target.
virtual void startWithTarget(Node *target);
/**
called after the action has finished. It will set the 'target' to nil.
IMPORTANT: You should never call "[action stop]" manually. Instead, use: "target->stopAction(action);"
*/
virtual void stop();
//! called every frame with it's delta time. DON'T override unless you know what you are doing.
virtual void step(float dt);
/**
called once per frame. time a value between 0 and 1
For example:
- 0 means that the action just started
- 0.5 means that the action is in the middle
- 1 means that the action is over
*/
virtual void update(float time);
inline Node* getTarget() const { return _target; }
/** The action will modify the target properties. */
inline void setTarget(Node *target) { _target = target; }
inline Node* getOriginalTarget() const { return _originalTarget; }
/** Set the original target, since target can be nil.
Is the target that were used to run the action. Unless you are doing something complex, like ActionManager, you should NOT call this method.
The target is 'assigned', it is not 'retained'.
@since v0.8.2
*/
inline void setOriginalTarget(Node *originalTarget) { _originalTarget = originalTarget; }
inline int getTag() const { return _tag; }
inline void setTag(int tag) { _tag = tag; }
protected:
Action();
virtual ~Action();
Node *_originalTarget;
/** The "target".
The target will be set with the 'startWithTarget' method.
When the 'stop' method is called, target will be set to nil.
The target is 'assigned', it is not 'retained'.
*/
Node *_target;
/** The action tag. An identifier of the action */
int _tag;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Action);
};
/**
@brief
Base class actions that do have a finite time duration.
Possible actions:
- An action with a duration of 0 seconds
- An action with a duration of 35.5 seconds
Infinite time actions are valid
*/
class CC_DLL FiniteTimeAction : public Action
{
public:
//! get duration in seconds of the action
inline float getDuration() const { return _duration; }
//! set duration in seconds of the action
inline void setDuration(float duration) { _duration = duration; }
//
// Overrides
//
virtual FiniteTimeAction* reverse() const override = 0;
virtual FiniteTimeAction* clone() const override = 0;
protected:
FiniteTimeAction()
: _duration(0)
{}
virtual ~FiniteTimeAction(){}
//! duration in seconds
float _duration;
private:
CC_DISALLOW_COPY_AND_ASSIGN(FiniteTimeAction);
};
class ActionInterval;
class RepeatForever;
/**
@brief Changes the speed of an action, making it take longer (speed>1)
or less (speed<1) time.
Useful to simulate 'slow motion' or 'fast forward' effect.
@warning This action can't be Sequenceable because it is not an IntervalAction
*/
class CC_DLL Speed : public Action
{
public:
/** create the action */
static Speed* create(ActionInterval* action, float speed);
inline float getSpeed(void) const { return _speed; }
/** alter the speed of the inner function in runtime */
inline void setSpeed(float speed) { _speed = speed; }
void setInnerAction(ActionInterval *action);
inline ActionInterval* getInnerAction() const { return _innerAction; }
//
// Override
//
virtual Speed* clone() const override;
virtual Speed* reverse() const override;
virtual void startWithTarget(Node* target) override;
virtual void stop() override;
virtual void step(float dt) override;
virtual bool isDone() const override;
CC_CONSTRUCTOR_ACCESS:
Speed();
virtual ~Speed(void);
/** initializes the action */
bool initWithAction(ActionInterval *action, float speed);
protected:
float _speed;
ActionInterval *_innerAction;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Speed);
};
/**
@brief Follow is an action that "follows" a node.
Eg:
@code
layer->runAction(Follow::actionWithTarget(hero));
@endcode
Instead of using Camera as a "follower", use this action instead.
@since v0.99.2
*/
class CC_DLL Follow : public Action
{
public:
/**
* Creates the action with a set boundary or with no boundary.
*
* @param followedNode The node to be followed.
* @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work
* with no boundary.
*/
static Follow* create(Node *followedNode, const Rect& rect = Rect::ZERO);
inline bool isBoundarySet() const { return _boundarySet; }
/** alter behavior - turn on/off boundary */
inline void setBoudarySet(bool value) { _boundarySet = value; }
//
// Override
//
virtual Follow* clone() const override;
virtual Follow* reverse() const override;
virtual void step(float dt) override;
virtual bool isDone() const override;
virtual void stop() override;
CC_CONSTRUCTOR_ACCESS:
/**
* @js ctor
*/
Follow()
: _followedNode(nullptr)
, _boundarySet(false)
, _boundaryFullyCovered(false)
, _leftBoundary(0.0)
, _rightBoundary(0.0)
, _topBoundary(0.0)
, _bottomBoundary(0.0)
, _worldRect(Rect::ZERO)
{}
/**
* @js NA
* @lua NA
*/
virtual ~Follow();
/**
* Initializes the action with a set boundary or with no boundary.
*
* @param followedNode The node to be followed.
* @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work
* with no boundary.
*/
bool initWithTarget(Node *followedNode, const Rect& rect = Rect::ZERO);
protected:
// node to follow
Node *_followedNode;
// whether camera should be limited to certain area
bool _boundarySet;
// if screen size is bigger than the boundary - update not needed
bool _boundaryFullyCovered;
// fast access to the screen dimensions
Point _halfScreenSize;
Point _fullScreenSize;
// world boundaries
float _leftBoundary;
float _rightBoundary;
float _topBoundary;
float _bottomBoundary;
Rect _worldRect;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Follow);
};
// end of actions group
/// @}
NS_CC_END
#endif // __ACTIONS_CCACTION_H__
| 0 | 0.96856 | 1 | 0.96856 | game-dev | MEDIA | 0.883876 | game-dev | 0.926762 | 1 | 0.926762 |
ProjectSkyfire/SkyFire_548 | 3,919 | src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp | /*
* This file is part of Project SkyFire https://www.projectskyfire.org.
* See LICENSE.md file for Copyright information
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "the_botanica.h"
enum Says
{
SAY_AGGRO = 0,
SAY_20_PERCENT_HP = 1,
SAY_KILL = 2,
SAY_CAST_SACRIFICE = 3,
SAY_50_PERCENT_HP = 4,
SAY_CAST_HELLFIRE = 5,
SAY_DEATH = 6,
EMOTE_ENRAGE = 7
};
enum Spells
{
SPELL_SACRIFICE = 34661,
SPELL_HELLFIRE_NORMAL = 34659,
SPELL_HELLFIRE_HEROIC = 39131,
SPELL_ENRAGE = 34670
};
enum Events
{
EVENT_SACRIFICE = 1,
EVENT_HELLFIRE = 2,
EVENT_ENRAGE = 3
};
class boss_thorngrin_the_tender : public CreatureScript
{
public:
boss_thorngrin_the_tender() : CreatureScript("thorngrin_the_tender") { }
struct boss_thorngrin_the_tenderAI : public BossAI
{
boss_thorngrin_the_tenderAI(Creature* creature) : BossAI(creature, DATA_THORNGRIN_THE_TENDER) { }
void Reset() OVERRIDE
{
_Reset();
_phase1 = true;
_phase2 = true;
}
void EnterCombat(Unit* /*who*/) OVERRIDE
{
_EnterCombat();
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_SACRIFICE, 5700);
events.ScheduleEvent(EVENT_HELLFIRE, IsHeroic() ? std::rand() % 19300 + 17400 : 18000);
events.ScheduleEvent(EVENT_ENRAGE, 12000);
}
void KilledUnit(Unit* /*victim*/) OVERRIDE
{
Talk(SAY_KILL);
}
void JustDied(Unit* /*killer*/) OVERRIDE
{
_JustDied();
Talk(SAY_DEATH);
}
void DamageTaken(Unit* /*killer*/, uint32& damage) OVERRIDE
{
if (me->HealthBelowPctDamaged(50, damage) && _phase1)
{
_phase1 = false;
Talk(SAY_50_PERCENT_HP);
}
if (me->HealthBelowPctDamaged(20, damage) && _phase2)
{
_phase2 = false;
Talk(SAY_20_PERCENT_HP);
}
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SACRIFICE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true))
{
Talk(SAY_CAST_SACRIFICE);
DoCast(target, SPELL_SACRIFICE, true);
}
events.ScheduleEvent(EVENT_SACRIFICE, 29400);
break;
case EVENT_HELLFIRE:
Talk(SAY_CAST_HELLFIRE);
DoCastVictim(DUNGEON_MODE(SPELL_HELLFIRE_NORMAL, SPELL_HELLFIRE_HEROIC), true);
events.ScheduleEvent(EVENT_HELLFIRE, IsHeroic() ? std::rand() % 19300 + 17400 : 18000);
break;
case EVENT_ENRAGE:
Talk(EMOTE_ENRAGE);
DoCast(me, SPELL_ENRAGE);
events.ScheduleEvent(EVENT_ENRAGE, 33000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
bool _phase1;
bool _phase2;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return new boss_thorngrin_the_tenderAI(creature);
}
};
void AddSC_boss_thorngrin_the_tender()
{
new boss_thorngrin_the_tender();
}
| 0 | 0.934204 | 1 | 0.934204 | game-dev | MEDIA | 0.98373 | game-dev | 0.918584 | 1 | 0.918584 |
Fluorohydride/ygopro-scripts | 1,385 | c32995007.lua | --天狼王 ブルー・セイリオス
function c32995007.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(32995007,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c32995007.atkcon)
e1:SetTarget(c32995007.atktg)
e1:SetOperation(c32995007.atkop)
c:RegisterEffect(e1)
end
function c32995007.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and e:GetHandler():IsReason(REASON_DESTROY)
end
function c32995007.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,0,LOCATION_MZONE,1,1,nil)
end
function c32995007.atkop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-2400)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end
| 0 | 0.947442 | 1 | 0.947442 | game-dev | MEDIA | 0.973984 | game-dev | 0.90785 | 1 | 0.90785 |
BuildTheEarth/terraplusplus | 1,260 | src/main/java/net/buildtheearth/terraplusplus/util/CustomAttributeContainer.java | package net.buildtheearth.terraplusplus.util;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import java.util.Map;
import static net.daporkchop.lib.common.util.PValidation.*;
import static net.daporkchop.lib.common.util.PorkUtil.*;
/**
* @author DaPorkchop_
*/
@AllArgsConstructor
public abstract class CustomAttributeContainer {
@NonNull
protected final Map<String, Object> custom;
/**
* Gets the custom attribute with the given key.
*
* @param key the key of the attribute to get
* @return the attribute
* @throws IllegalArgumentException if a property with the given name couldn't be found
*/
public <T> T getCustom(@NonNull String key) {
T value = uncheckedCast(this.custom.get(key));
checkArg(value != null || this.custom.containsKey(key), "unknown property: \"%s\"", key);
return value;
}
/**
* Gets the custom attribute with the given key.
*
* @param key the key of the attribute to get
* @param fallback the value to return if the key couldn't be found
* @return the attribute
*/
public <T> T getCustom(@NonNull String key, T fallback) {
return uncheckedCast(this.custom.getOrDefault(key, fallback));
}
}
| 0 | 0.860292 | 1 | 0.860292 | game-dev | MEDIA | 0.270171 | game-dev | 0.694654 | 1 | 0.694654 |
fragcolor-xyz/crdt-lite | 16,925 | list_crdt.hpp | #ifndef LIST_CRDT_HPP
#define LIST_CRDT_HPP
#include "crdt.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <optional>
#include <algorithm>
#include <map>
#include <set>
#include <unordered_map>
#include <cassert>
#include <functional> // For std::hash
// -----------------------------------------
// ElementID Definition
// -----------------------------------------
// Represents a unique identifier for a list element
struct ElementID {
CrdtNodeId replica_id; // Unique identifier for the replica
uint64_t sequence; // Monotonically increasing sequence number
// Comparison operator for ordering elements
bool operator<(const ElementID &other) const {
if (sequence != other.sequence)
return sequence < other.sequence;
return replica_id < other.replica_id;
}
// Equality operator for comparing two ElementIDs
bool operator==(const ElementID &other) const { return sequence == other.sequence && replica_id == other.replica_id; }
// For printing purposes
friend std::ostream &operator<<(std::ostream &os, const ElementID &id) {
os << "(" << id.replica_id << ", " << id.sequence << ")";
return os;
}
};
// Improved Hash function for ElementID to use in unordered containers
struct ElementIDHash {
std::size_t operator()(const ElementID &id) const {
// Using a better hash combination technique to reduce collisions
// Example: boost::hash_combine equivalent
std::size_t seed = std::hash<CrdtNodeId>()(id.replica_id);
seed ^= std::hash<uint64_t>()(id.sequence) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
// -----------------------------------------
// ListElement Definition
// -----------------------------------------
// Represents an element in the list
template <typename T> struct ListElement {
ElementID id; // Unique identifier for the element
std::optional<T> value; // Value stored (None if tombstoned)
std::optional<ElementID> origin_left; // Left origin at insertion
std::optional<ElementID> origin_right; // Right origin at insertion
// Checks if the element is tombstoned (deleted)
bool is_deleted() const { return !value.has_value(); }
// For printing purposes
friend std::ostream &operator<<(std::ostream &os, const ListElement &elem) {
os << "ID: " << elem.id << ", ";
if (elem.is_deleted()) {
os << "[Deleted]";
} else {
os << "Value: " << elem.value.value();
}
os << ", Origin Left: ";
if (elem.origin_left.has_value()) {
os << elem.origin_left.value();
} else {
os << "None";
}
os << ", Origin Right: ";
if (elem.origin_right.has_value()) {
os << elem.origin_right.value();
} else {
os << "None";
}
return os;
}
};
// -----------------------------------------
// ListElementComparator Definition
// -----------------------------------------
// Comparator for ListElements to establish a total order
template <typename T> struct ListElementComparator {
bool operator()(const ListElement<T> &a, const ListElement<T> &b) const {
// First, handle root elements
bool a_is_root = (a.id.replica_id == 0 && a.id.sequence == 0);
bool b_is_root = (b.id.replica_id == 0 && b.id.sequence == 0);
if (a_is_root && !b_is_root)
return true;
if (!a_is_root && b_is_root)
return false;
if (a_is_root && b_is_root)
return false; // They are the same
// Compare origin_left
if (a.origin_left && b.origin_left) {
if (a.origin_left.value() != b.origin_left.value()) {
return a.origin_left.value() < b.origin_left.value();
}
} else if (a.origin_left) {
// b.origin_left is not set
return false;
} else if (b.origin_left) {
// a.origin_left is not set
return true;
}
// Compare origin_right
if (a.origin_right && b.origin_right) {
if (a.origin_right.value() != b.origin_right.value()) {
return a.origin_right.value() < b.origin_right.value();
}
} else if (a.origin_right) {
// b.origin_right is not set
return false;
} else if (b.origin_right) {
// a.origin_right is not set
return true;
}
// If both have the same origins, use ElementID to break the tie
return a.id < b.id;
}
};
// -----------------------------------------
// ListCRDT Class Definition
// -----------------------------------------
// Represents the List CRDT using optimized data structures
template <typename T> class ListCRDT {
public:
// Constructor to initialize a new CRDT instance with a unique replica ID
ListCRDT(const CrdtNodeId &replica_id) : replica_id_(replica_id), counter_(0) {
assert(replica_id_ != 0 && "Replica ID 0 is reserved for the root element.");
// Initialize with a root element to simplify origins
ElementID root_id{0, 0}; // Use 0 as the root replica_id
ListElement<T> root_element{root_id, std::nullopt, std::nullopt, std::nullopt};
elements_.emplace(root_element);
element_index_.emplace(root_id, root_element); // Store a copy
visible_elements_.emplace_back(&element_index_.at(root_id)); // Root is initially visible
}
// Inserts a value at the given index
void insert(uint32_t index, const T &value) {
ElementID new_id = generate_id();
std::optional<ElementID> left_origin;
std::optional<ElementID> right_origin;
// Adjust index if out of bounds
if (index > visible_elements_.size() - 1) { // Exclude root
index = visible_elements_.size() - 1;
}
if (index == 0) {
// Insert after root
if (!visible_elements_.empty()) {
right_origin = visible_elements_[0]->id;
}
} else if (index == visible_elements_.size() - 1) {
// Insert at the end
if (!visible_elements_.empty()) {
left_origin = visible_elements_[index - 1]->id;
}
} else {
// Insert in the middle
left_origin = visible_elements_[index - 1]->id;
right_origin = visible_elements_[index]->id;
}
// Create a new element with the given value and origins
ListElement<T> new_element{new_id, value, left_origin, right_origin};
integrate(new_element);
}
// Deletes the element at the given index by tombstoning it
void delete_element(uint32_t index) {
if (index >= visible_elements_.size() - 1) { // Exclude root
std::cerr << "Delete operation failed: Index " << index << " is out of bounds.\n";
return; // Index out of bounds, do nothing
}
ElementID target_id = visible_elements_[index]->id;
auto it = find_element(target_id);
if (it != elements_.end()) {
if (it->is_deleted()) {
// Already deleted
return;
}
ListElement<T> updated = *it;
updated.value.reset(); // Tombstone the element by resetting its value
elements_.erase(it);
elements_.emplace(updated);
element_index_[updated.id] = updated;
// Remove from visible_elements_
auto ve_it = std::find_if(visible_elements_.begin(), visible_elements_.end(),
[&](const ListElement<T> *elem_ptr) { return elem_ptr->id == target_id; });
if (ve_it != visible_elements_.end()) {
visible_elements_.erase(ve_it);
}
}
}
// Merges another ListCRDT into this one
void merge(const ListCRDT &other) {
for (const auto &elem : other.elements_) {
if (elem.id.replica_id == 0 && elem.id.sequence == 0) {
continue; // Skip the root element
}
integrate(elem);
}
// Rebuild visible_elements_ after merge
rebuild_visible_elements();
}
// Generates a delta containing operations not seen by the other replica
std::pair<std::vector<ListElement<T>>, std::vector<ElementID>> generate_delta(const ListCRDT &other) const {
std::vector<ListElement<T>> new_elements;
std::vector<ElementID> tombstones;
for (const auto &elem : elements_) {
if (elem.id.replica_id == 0 && elem.id.sequence == 0) {
continue; // Skip the root element
}
if (!other.has_element(elem.id)) {
new_elements.emplace_back(elem);
if (elem.is_deleted()) {
tombstones.emplace_back(elem.id);
}
}
}
return {new_elements, tombstones};
}
// Applies a delta to this CRDT
void apply_delta(const std::vector<ListElement<T>> &new_elements, const std::vector<ElementID> &tombstones) {
// Apply insertions
for (const auto &elem : new_elements) {
if (elem.id.replica_id == 0 && elem.id.sequence == 0) {
continue; // Skip the root element
}
auto it = find_element(elem.id);
if (it == elements_.end()) {
integrate(elem);
} else {
// Element already exists, possibly update tombstone
if (elem.is_deleted()) {
ListElement<T> updated = *it;
updated.value.reset();
elements_.erase(it);
elements_.emplace(updated);
element_index_[updated.id] = updated;
// Remove from visible_elements_ if present
auto ve_it = std::find_if(visible_elements_.begin(), visible_elements_.end(),
[&](const ListElement<T> *ptr) { return ptr->id == elem.id; });
if (ve_it != visible_elements_.end()) {
visible_elements_.erase(ve_it);
}
}
}
}
// Apply tombstones to existing elements
for (const auto &id : tombstones) {
auto it = find_element(id);
if (it != elements_.end()) {
if (it->is_deleted()) {
continue; // Already deleted
}
ListElement<T> updated = *it;
updated.value.reset();
elements_.erase(it);
elements_.emplace(updated);
element_index_[updated.id] = updated;
// Remove from visible_elements_ if present
auto ve_it = std::find_if(visible_elements_.begin(), visible_elements_.end(),
[&](const ListElement<T> *ptr) { return ptr->id == id; });
if (ve_it != visible_elements_.end()) {
visible_elements_.erase(ve_it);
}
}
}
}
// Retrieves the current list as a vector of values
std::vector<T> get_values() const {
std::vector<T> values;
values.reserve(visible_elements_.size());
for (const auto &elem_ptr : visible_elements_) {
if (elem_ptr->id.replica_id == 0 && elem_ptr->id.sequence == 0) {
continue; // Skip the root element
}
if (!elem_ptr->is_deleted()) {
values.emplace_back(elem_ptr->value.value());
}
}
return values;
}
// Prints the current visible list for debugging
void print_visible() const {
for (const auto &elem_ptr : visible_elements_) {
if (elem_ptr->id.replica_id == 0 && elem_ptr->id.sequence == 0) {
continue; // Skip the root element
}
if (!elem_ptr->is_deleted()) {
std::cout << elem_ptr->value.value() << " ";
}
}
std::cout << std::endl;
}
// Prints all elements including tombstones for debugging
void print_all_elements() const {
for (const auto &elem : elements_) {
std::cout << elem << std::endl;
}
}
// Performs garbage collection by removing tombstones that are safe to delete
void garbage_collect() {
std::vector<ElementID> to_remove_ids;
for (const auto &elem : elements_) {
if (elem.is_deleted() && elem.id.replica_id != 0) {
to_remove_ids.emplace_back(elem.id);
}
}
for (const auto &id : to_remove_ids) {
auto it = find_element(id);
if (it != elements_.end()) {
elements_.erase(it);
element_index_.erase(id);
// No need to remove from visible_elements_ since it's already tombstoned
}
}
}
protected:
// Make these methods protected so derived classes can access them
inline ElementID generate_id() { return ElementID{replica_id_, ++counter_}; }
void integrate(const ListElement<T> &new_elem) {
auto it = elements_.find(new_elem);
if (it != elements_.end()) {
// Element exists, possibly update tombstone
if (new_elem.is_deleted() && !it->is_deleted()) {
ListElement<T> updated = *it;
updated.value.reset();
elements_.erase(it);
elements_.emplace(updated);
element_index_[updated.id] = updated;
// Remove from visible_elements_ if present
auto ve_it = std::find_if(visible_elements_.begin(), visible_elements_.end(),
[&](const ListElement<T> *ptr) { return ptr->id == updated.id; });
if (ve_it != visible_elements_.end()) {
visible_elements_.erase(ve_it);
}
}
return;
}
// Insert the new element
elements_.emplace(new_elem);
element_index_.emplace(new_elem.id, new_elem);
if (!new_elem.is_deleted()) {
// Insert into visible_elements_ maintaining order
auto pos =
std::lower_bound(visible_elements_.begin(), visible_elements_.end(), &new_elem,
[&](const ListElement<T> *a, const ListElement<T> *b) { return ListElementComparator<T>()(*a, *b); });
visible_elements_.insert(pos, &element_index_.at(new_elem.id));
}
}
// Add new protected methods needed by ListCRDTWithChanges
const std::vector<const ListElement<T>*>& get_visible_elements() const {
return visible_elements_;
}
const std::set<ListElement<T>, ListElementComparator<T>>& get_all_elements() const {
return elements_;
}
const ListElement<T>* get_element(const ElementID& id) const {
auto it = element_index_.find(id);
if (it != element_index_.end()) {
return &it->second;
}
return nullptr;
}
CrdtNodeId get_replica_id() const {
return replica_id_;
}
struct ElementVersionInfo {
uint64_t version;
uint64_t db_version;
CrdtNodeId node_id;
uint64_t local_db_version;
};
ElementVersionInfo get_version_info(const ElementID& id) const {
auto it = element_index_.find(id);
if (it != element_index_.end()) {
return ElementVersionInfo{
element_versions_.count(id) ? element_versions_.at(id) : 1, // version
db_versions_.count(id) ? db_versions_.at(id) : 0, // db_version
it->second.id.replica_id, // node_id
local_versions_.count(id) ? local_versions_.at(id) : 0 // local_db_version
};
}
return ElementVersionInfo{1, 0, replica_id_, 0};
}
void update_version_info(const ElementID& id, uint64_t version, uint64_t db_version, uint64_t local_version) {
element_versions_[id] = version;
db_versions_[id] = db_version;
local_versions_[id] = local_version;
}
private:
CrdtNodeId replica_id_; // Unique identifier for the replica
uint64_t counter_; // Monotonically increasing counter for generating unique IDs
std::set<ListElement<T>, ListElementComparator<T>> elements_; // Set of all elements (including tombstoned)
std::unordered_map<ElementID, ListElement<T>, ElementIDHash> element_index_; // Maps ElementID to ListElement
std::vector<const ListElement<T> *> visible_elements_; // Ordered list of visible elements
// Add version tracking
std::unordered_map<ElementID, uint64_t, ElementIDHash> element_versions_;
std::unordered_map<ElementID, uint64_t, ElementIDHash> db_versions_;
std::unordered_map<ElementID, uint64_t, ElementIDHash> local_versions_;
// Checks if an element exists by its ID
inline bool has_element(const ElementID &id) const { return element_index_.find(id) != element_index_.end(); }
// Finds an element by its ID using the index
typename std::set<ListElement<T>, ListElementComparator<T>>::iterator find_element(const ElementID &id) {
auto it_map = element_index_.find(id);
if (it_map != element_index_.end()) {
return elements_.find(it_map->second);
}
return elements_.end();
}
typename std::set<ListElement<T>, ListElementComparator<T>>::const_iterator find_element(const ElementID &id) const {
auto it_map = element_index_.find(id);
if (it_map != element_index_.end()) {
return elements_.find(it_map->second);
}
return elements_.end();
}
// Rebuilds the visible_elements_ vector after a merge
void rebuild_visible_elements() {
visible_elements_.clear();
for (const auto &elem : elements_) {
if (!elem.is_deleted()) {
visible_elements_.emplace_back(&element_index_.at(elem.id));
}
}
// Sort visible_elements_ according to the comparator
std::sort(visible_elements_.begin(), visible_elements_.end(),
[&](const ListElement<T> *a, const ListElement<T> *b) { return ListElementComparator<T>()(*a, *b); });
}
};
#endif // LIST_CRDT_HPP | 0 | 0.967921 | 1 | 0.967921 | game-dev | MEDIA | 0.307284 | game-dev | 0.952618 | 1 | 0.952618 |
alibaba/mdrill | 12,006 | trunk/adhoc-public/src/main/java/gnu/trove/decorator/TByteCharMapDecorator.java | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2002, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Robert D. Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.decorator;
import gnu.trove.map.TByteCharMap;
import gnu.trove.iterator.TByteCharIterator;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Wrapper class to make a TByteCharMap conform to the <tt>java.util.Map</tt> API.
* This class simply decorates an underlying TByteCharMap and translates the Object-based
* APIs into their Trove primitive analogs.
* <p/>
* Note that wrapping and unwrapping primitive values is extremely inefficient. If
* possible, users of this class should override the appropriate methods in this class
* and use a table of canonical values.
* <p/>
* Created: Mon Sep 23 22:07:40 PDT 2002
*
* @author Eric D. Friedman
* @author Robert D. Eden
* @author Jeff Randall
*/
public class TByteCharMapDecorator extends AbstractMap<Byte, Character>
implements Map<Byte, Character>, Externalizable, Cloneable {
static final long serialVersionUID = 1L;
/** the wrapped primitive map */
protected TByteCharMap _map;
/**
* FOR EXTERNALIZATION ONLY!!
*/
public TByteCharMapDecorator() {}
/**
* Creates a wrapper that decorates the specified primitive map.
*
* @param map the <tt>TByteCharMap</tt> to wrap.
*/
public TByteCharMapDecorator( TByteCharMap map ) {
super();
this._map = map;
}
/**
* Returns a reference to the map wrapped by this decorator.
*
* @return the wrapped <tt>TByteCharMap</tt> instance.
*/
public TByteCharMap getMap() {
return _map;
}
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or Character(0) if none was found.
*/
public Character put( Byte key, Character value ) {
byte k;
char v;
if ( key == null ) {
k = _map.getNoEntryKey();
} else {
k = unwrapKey( key );
}
if ( value == null ) {
v = _map.getNoEntryValue();
} else {
v = unwrapValue( value );
}
char retval = _map.put( k, v );
if ( retval == _map.getNoEntryValue() ) {
return null;
}
return wrapValue( retval );
}
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>Object</code> value
* @return the value of <tt>key</tt> or null if no such mapping exists.
*/
public Character get( Object key ) {
byte k;
if ( key != null ) {
if ( key instanceof Byte ) {
k = unwrapKey( key );
} else {
return null;
}
} else {
k = _map.getNoEntryKey();
}
char v = _map.get( k );
// There may be a false positive since primitive maps
// cannot return null, so we have to do an extra
// check here.
if ( v == _map.getNoEntryValue() ) {
return null;
} else {
return wrapValue( v );
}
}
/**
* Empties the map.
*/
public void clear() {
this._map.clear();
}
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>Object</code> value
* @return the removed value, or null if it was not found in the map
*/
public Character remove( Object key ) {
byte k;
if ( key != null ) {
if ( key instanceof Byte ) {
k = unwrapKey( key );
} else {
return null;
}
} else {
k = _map.getNoEntryKey();
}
char v = _map.remove( k );
// There may be a false positive since primitive maps
// cannot return null, so we have to do an extra
// check here.
if ( v == _map.getNoEntryValue() ) {
return null;
} else {
return wrapValue( v );
}
}
/**
* Returns a Set view on the entries of the map.
*
* @return a <code>Set</code> value
*/
public Set<Map.Entry<Byte,Character>> entrySet() {
return new AbstractSet<Map.Entry<Byte,Character>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TByteCharMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TByteCharMapDecorator.this.containsKey(k)
&& TByteCharMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Byte,Character>> iterator() {
return new Iterator<Map.Entry<Byte,Character>>() {
private final TByteCharIterator it = _map.iterator();
public Map.Entry<Byte,Character> next() {
it.advance();
byte ik = it.key();
final Byte key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
char iv = it.value();
final Character v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Byte,Character>() {
private Character val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Byte getKey() {
return key;
}
public Character getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Character setValue( Character value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Byte,Character> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Byte key = ( ( Map.Entry<Byte,Character> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Byte, Character>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TByteCharMapDecorator.this.clear();
}
};
}
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( Object val ) {
return val instanceof Character && _map.containsValue( unwrapValue( val ) );
}
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( Object key ) {
if ( key == null ) return _map.containsKey( _map.getNoEntryKey() );
return key instanceof Byte && _map.containsKey( unwrapKey( key ) );
}
/**
* Returns the number of entries in the map.
*
* @return the map's size.
*/
public int size() {
return this._map.size();
}
/**
* Indicates whether map has any entries.
*
* @return true if the map is empty
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Copies the key/value mappings in <tt>map</tt> into this map.
* Note that this will be a <b>deep</b> copy, as storage is by
* primitive value.
*
* @param map a <code>Map</code> value
*/
public void putAll( Map<? extends Byte, ? extends Character> map ) {
Iterator<? extends Entry<? extends Byte,? extends Character>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Byte,? extends Character> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
/**
* Wraps a key
*
* @param k key in the underlying map
* @return an Object representation of the key
*/
protected Byte wrapKey( byte k ) {
return Byte.valueOf( k );
}
/**
* Unwraps a key
*
* @param key wrapped key
* @return an unwrapped representation of the key
*/
protected byte unwrapKey( Object key ) {
return ( ( Byte ) key ).byteValue();
}
/**
* Wraps a value
*
* @param k value in the underlying map
* @return an Object representation of the value
*/
protected Character wrapValue( char k ) {
return Character.valueOf( k );
}
/**
* Unwraps a value
*
* @param value wrapped value
* @return an unwrapped representation of the value
*/
protected char unwrapValue( Object value ) {
return ( ( Character ) value ).charValue();
}
// Implements Externalizable
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// MAP
_map = ( TByteCharMap ) in.readObject();
}
// Implements Externalizable
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte(0);
// MAP
out.writeObject( _map );
}
} // TByteCharHashMapDecorator
| 0 | 0.936849 | 1 | 0.936849 | game-dev | MEDIA | 0.246756 | game-dev | 0.967397 | 1 | 0.967397 |
baileyholl/Ars-Nouveau | 3,701 | src/main/java/com/hollingsworth/arsnouveau/setup/reward/Rewards.java | package com.hollingsworth.arsnouveau.setup.reward;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.world.item.DyeColor;
import net.neoforged.fml.loading.FMLEnvironment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class Rewards {
public static List<ContributorStarby> starbuncles = new ArrayList<>();
public static List<UUID> CONTRIBUTORS = new ArrayList<>();
public static void init() {
try {
JsonObject object = JsonParser.parseString(readUrl(new URL("https://raw.githubusercontent.com/baileyholl/Ars-Nouveau/main/supporters.json"))).getAsJsonObject();
JsonArray supporters = object.getAsJsonArray("uuids");
for (JsonElement element : supporters) {
String uuid = element.getAsString();
try {
CONTRIBUTORS.add(UUID.fromString(uuid.trim()));
} catch (Exception e) {
e.printStackTrace();
}
}
JsonArray adoptions = object.getAsJsonArray("starbuncleAdoptions");
for (JsonElement element : adoptions) {
JsonObject jsonObject = element.getAsJsonObject();
String name = jsonObject.get("name").getAsString();
String adopter = jsonObject.get("adopter").getAsString();
String color = jsonObject.get("color").getAsString();
String bio = jsonObject.get("bio").getAsString();
starbuncles.add(new ContributorStarby(name, adopter, color, bio));
}
} catch (IOException var2) {
var2.printStackTrace();
if (!FMLEnvironment.production) {
throw new RuntimeException("Failed to load supporters.json");
}
}
}
public static String readUrl(URL url) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
StringBuilder buffer = new StringBuilder();
char[] chars = new char[1024];
int read;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
return buffer.toString();
}
}
public static class ContributorStarby {
public String name;
public String adopter;
public String color;
public String bio;
public ContributorStarby(String name, String adopter, String color, String bio) {
this.name = name;
this.adopter = adopter;
this.color = color;
this.bio = bio;
if (!FMLEnvironment.production) {
if (name == null) {
throw new RuntimeException("Name is null");
}
if (adopter == null) {
throw new RuntimeException("Adopter is null");
}
if (color == null) {
throw new RuntimeException("Color is null");
}
if (bio == null) {
throw new RuntimeException("Bio is null");
}
boolean foundColor = Arrays.stream(DyeColor.values()).anyMatch(dye -> dye.getName().equals(color));
if (!foundColor) {
throw new RuntimeException("Color is not a valid dye color");
}
}
}
}
}
| 0 | 0.811864 | 1 | 0.811864 | game-dev | MEDIA | 0.396575 | game-dev | 0.770079 | 1 | 0.770079 |
NeotokyoRebuild/neo | 4,500 | src/game/shared/replay_gamestats_shared.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//=============================================================================
#include "cbase.h"
#include "replay_gamestats_shared.h"
#include "steamworks_gamestats.h"
#if defined( CLIENT_DLL )
#include "../client/replay/genericclassbased_replay.h"
#include "replay/replayvideo.h"
#include "replay/vgui/replaybrowserrenderdialog.h"
#endif
#include "replay/rendermovieparams.h"
#include "replay/performance.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
CReplayGameStatsHelper::CReplayGameStatsHelper()
{
}
void CReplayGameStatsHelper::UploadError( KeyValues *pData, bool bIncludeTimeField )
{
if ( bIncludeTimeField )
{
// pData->SetInt( "Time", GetSteamWorksSGameStatsUploader().GetTimeSinceEpoch() );
}
GetSteamWorksSGameStatsUploader().AddStatsForUpload( pData );
}
CReplayGameStatsHelper &GetReplayGameStatsHelper()
{
static CReplayGameStatsHelper s_Instance;
return s_Instance;
}
#if defined( CLIENT_DLL )
void CReplayGameStatsHelper::SW_ReplayStats_WriteRenderDataStart( const RenderMovieParams_t& RenderParams, const CReplayRenderDialog *pDlg )
{
SW_ReplayStats_WriteRenderData( true, RenderParams, pDlg, NULL );
}
void CReplayGameStatsHelper::SW_ReplayStats_WriteRenderDataEnd( const RenderMovieParams_t& RenderParams, const char *pEndReason )
{
SW_ReplayStats_WriteRenderData( false, RenderParams, NULL, pEndReason );
}
void CReplayGameStatsHelper::SW_ReplayStats_WriteRenderData( bool bStarting, const RenderMovieParams_t& RenderParams,
const CReplayRenderDialog *pDlg, const char *pEndReason/*=NULL*/ )
{
#if !defined( NO_STEAM )
#if defined( REPLAY_ENABLED )
static uint32 s_iReplayRenderCounter = 0;
ReplayHandle_t hReplay = RenderParams.m_hReplay;
CGenericClassBasedReplay *pReplay = GetGenericClassBasedReplay( hReplay );
if ( !pReplay )
return;
KeyValues* pKVData = new KeyValues( "TF2ReplayRenders" );
// Base settings/DB key.
pKVData->SetInt( "RenderCounter", s_iReplayRenderCounter++ );
pKVData->SetInt( "ReplayHandle", hReplay );
pKVData->SetInt( "PeformanceIndex", RenderParams.m_iPerformance );
// Dialog-specific
if ( pDlg )
{
pKVData->SetInt( "ShowAdvancedChecked", pDlg->m_pShowAdvancedOptionsCheck->IsSelected() );
pKVData->SetString( "CodecID", ReplayVideo_GetCodec( pDlg->m_pCodecCombo->GetActiveItem() ).m_pName );
pKVData->SetInt( "RenderQualityPreset", pDlg->m_iQualityPreset );
}
// Render settings
CFmtStr fmtResolution( "%ix%i", RenderParams.m_Settings.m_nWidth, RenderParams.m_Settings.m_nHeight );
pKVData->SetInt( "QuitWhenDoneChecked", RenderParams.m_bQuitWhenFinished );
pKVData->SetString( "ResolutionID", fmtResolution.Access() );
pKVData->SetInt( "AAEnabled", RenderParams.m_Settings.m_bAAEnabled );
pKVData->SetInt( "MotionBlurEnabled", RenderParams.m_Settings.m_bMotionBlurEnabled );
pKVData->SetInt( "MotionBlurQuality", RenderParams.m_Settings.m_nMotionBlurQuality );
pKVData->SetInt( "RenderQuality", RenderParams.m_Settings.m_nEncodingQuality);
pKVData->SetInt( "ExportRawChecked", RenderParams.m_bExportRaw );
pKVData->SetInt( "FPSUPF", RenderParams.m_Settings.m_FPS.GetUnitsPerFrame() );
pKVData->SetInt( "FPSUPS", RenderParams.m_Settings.m_FPS.GetUnitsPerSecond() );
// Replay content.
pKVData->SetString( "MapID", pReplay->GetMapName() );
pKVData->SetString( "PlayerClassID", pReplay->GetPlayerClass() );
pKVData->SetInt( "ReplayLengthRealtime", pReplay->GetDeathTick() - pReplay->GetSpawnTick() );
CReplayPerformance *pPerformance = pReplay->GetPerformance( RenderParams.m_iPerformance );
if ( pPerformance )
{
int iPerformanceStartTick = pPerformance->HasInTick() ? pPerformance->GetTickIn() : pReplay->GetSpawnTick(),
iPeformanceEndTick = pPerformance->HasOutTick() ? pPerformance->GetTickOut() : pReplay->GetDeathTick();
pKVData->SetInt( "TakeLengthRealtime", iPeformanceEndTick - iPerformanceStartTick );
}
else
{
pKVData->SetInt( "TakeLengthRealtime", pReplay->GetDeathTick() - pReplay->GetSpawnTick() );
}
// Start or end time
pKVData->SetInt( bStarting ? "StartRenderTime" : "EndRenderTime", GetSteamWorksSGameStatsUploader().GetTimeSinceEpoch() );
// Write end reason
if ( !bStarting && pEndReason )
{
pKVData->SetString( "EndRenderReasonID", pEndReason );
}
GetSteamWorksSGameStatsUploader().AddStatsForUpload( pKVData );
#endif // REPLAY_ENABLED
#endif // !defined( NO_STEAM )
}
#endif // defined( CLIENT_DLL )
| 0 | 0.942811 | 1 | 0.942811 | game-dev | MEDIA | 0.741567 | game-dev | 0.974844 | 1 | 0.974844 |
ElunaLuaEngine/ElunaTrinityWotlk | 19,494 | src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* 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 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "OutdoorPvPZM.h"
#include "Creature.h"
#include "GossipDef.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "OutdoorPvPMgr.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "WorldStatePackets.h"
uint8 const OutdoorPvPZMBuffZonesNum = 5;
// the buff is cast in these zones
uint32 const OutdoorPvPZMBuffZones[OutdoorPvPZMBuffZonesNum] = { 3521, 3607, 3717, 3715, 3716 };
// linked when the central tower is controlled
uint32 const ZM_GRAVEYARD_ZONE = 3521;
// linked when the central tower is controlled
uint32 const ZM_GRAVEYARD_ID = 969;
// banners 182527, 182528, 182529, gotta check them ingame
go_type const ZM_Banner_A = { 182527, 530, { 253.54f, 7083.81f, 36.7728f, -0.017453f }, { 0.0f, 0.0f, 0.008727f, -0.999962f } };
go_type const ZM_Banner_H = { 182528, 530, { 253.54f, 7083.81f, 36.7728f, -0.017453f }, { 0.0f, 0.0f, 0.008727f, -0.999962f } };
go_type const ZM_Banner_N = { 182529, 530, { 253.54f, 7083.81f, 36.7728f, -0.017453f }, { 0.0f, 0.0f, 0.008727f, -0.999962f } };
// horde field scout spawn data
creature_type const ZM_HordeFieldScout = { 18564, 530, { 296.625f, 7818.4f, 42.6294f, 5.18363f } };
// alliance field scout spawn data
creature_type const ZM_AllianceFieldScout = { 18581, 530, { 374.395f, 6230.08f, 22.8351f, 0.593412f } };
struct zm_beacon
{
uint32 ui_tower_n;
uint32 ui_tower_h;
uint32 ui_tower_a;
uint32 map_tower_n;
uint32 map_tower_h;
uint32 map_tower_a;
uint32 event_enter;
uint32 event_leave;
};
zm_beacon const ZMBeaconInfo[ZM_NUM_BEACONS] =
{
{ 2560, 2559, 2558, 2652, 2651, 2650, 11807, 11806 },
{ 2557, 2556, 2555, 2646, 2645, 2644, 11805, 11804 }
};
uint32 const ZMBeaconCaptureA[ZM_NUM_BEACONS] =
{
TEXT_EAST_BEACON_TAKEN_ALLIANCE,
TEXT_WEST_BEACON_TAKEN_ALLIANCE
};
uint32 const ZMBeaconCaptureH[ZM_NUM_BEACONS] =
{
TEXT_EAST_BEACON_TAKEN_HORDE,
TEXT_WEST_BEACON_TAKEN_HORDE
};
go_type const ZMCapturePoints[ZM_NUM_BEACONS] =
{
{ 182523, 530, { 303.243f, 6841.36f, 40.1245f, -1.58825f }, { 0.0f, 0.0f, 0.71325f, -0.700909f } },
{ 182522, 530, { 336.466f, 7340.26f, 41.4984f, -1.58825f }, { 0.0f, 0.0f, 0.71325f, -0.700909f } }
};
OPvPCapturePointZM_Beacon::OPvPCapturePointZM_Beacon(OutdoorPvP* pvp, ZM_BeaconType type) : OPvPCapturePoint(pvp), m_TowerType(type), m_TowerState(ZM_TOWERSTATE_N)
{
SetCapturePointData(ZMCapturePoints[type].entry, ZMCapturePoints[type].map, ZMCapturePoints[type].pos, ZMCapturePoints[type].rot);
}
void OPvPCapturePointZM_Beacon::FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& packet)
{
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].ui_tower_n, (m_TowerState & ZM_TOWERSTATE_N) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].map_tower_n, (m_TowerState & ZM_TOWERSTATE_N) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].ui_tower_a, (m_TowerState & ZM_TOWERSTATE_A) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].map_tower_a, (m_TowerState & ZM_TOWERSTATE_A) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].ui_tower_h, (m_TowerState & ZM_TOWERSTATE_H) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZMBeaconInfo[m_TowerType].map_tower_h, (m_TowerState & ZM_TOWERSTATE_H) != 0 ? 1 : 0);
}
void OPvPCapturePointZM_Beacon::UpdateTowerState()
{
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].ui_tower_n), uint32((m_TowerState & ZM_TOWERSTATE_N) != 0));
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].map_tower_n), uint32((m_TowerState & ZM_TOWERSTATE_N) != 0));
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].ui_tower_a), uint32((m_TowerState & ZM_TOWERSTATE_A) != 0));
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].map_tower_a), uint32((m_TowerState & ZM_TOWERSTATE_A) != 0));
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].ui_tower_h), uint32((m_TowerState & ZM_TOWERSTATE_H) != 0));
m_PvP->SendUpdateWorldState(uint32(ZMBeaconInfo[m_TowerType].map_tower_h), uint32((m_TowerState & ZM_TOWERSTATE_H) != 0));
}
void OPvPCapturePointZM_Beacon::ChangeState()
{
// if changing from controlling alliance to horde
if (m_OldState == OBJECTIVESTATE_ALLIANCE)
{
if (uint32 alliance_towers = ((OutdoorPvPZM*)m_PvP)->GetAllianceTowersControlled())
((OutdoorPvPZM*)m_PvP)->SetAllianceTowersControlled(--alliance_towers);
}
// if changing from controlling horde to alliance
else if (m_OldState == OBJECTIVESTATE_HORDE)
{
if (uint32 horde_towers = ((OutdoorPvPZM*)m_PvP)->GetHordeTowersControlled())
((OutdoorPvPZM*)m_PvP)->SetHordeTowersControlled(--horde_towers);
}
switch (m_State)
{
case OBJECTIVESTATE_ALLIANCE:
{
m_TowerState = ZM_TOWERSTATE_A;
uint32 alliance_towers = ((OutdoorPvPZM*)m_PvP)->GetAllianceTowersControlled();
if (alliance_towers < ZM_NUM_BEACONS)
((OutdoorPvPZM*)m_PvP)->SetAllianceTowersControlled(++alliance_towers);
m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, ZMBeaconCaptureA[m_TowerType]);
break;
}
case OBJECTIVESTATE_HORDE:
{
m_TowerState = ZM_TOWERSTATE_H;
uint32 horde_towers = ((OutdoorPvPZM*)m_PvP)->GetHordeTowersControlled();
if (horde_towers < ZM_NUM_BEACONS)
((OutdoorPvPZM*)m_PvP)->SetHordeTowersControlled(++horde_towers);
m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, ZMBeaconCaptureH[m_TowerType]);
break;
}
case OBJECTIVESTATE_NEUTRAL:
case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE:
case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE:
case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE:
case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE:
m_TowerState = ZM_TOWERSTATE_N;
break;
}
UpdateTowerState();
}
bool OutdoorPvPZM::Update(uint32 diff)
{
bool changed = OutdoorPvP::Update(diff);
if (changed)
{
if (m_AllianceTowersControlled == ZM_NUM_BEACONS)
m_Graveyard->SetBeaconState(ALLIANCE);
else if (m_HordeTowersControlled == ZM_NUM_BEACONS)
m_Graveyard->SetBeaconState(HORDE);
else
m_Graveyard->SetBeaconState(0);
}
return changed;
}
void OutdoorPvPZM::HandlePlayerEnterZone(Player* player, uint32 zone)
{
if (player->GetTeam() == ALLIANCE)
{
if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_A)
player->CastSpell(player, ZM_CAPTURE_BUFF, true);
}
else
{
if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_H)
player->CastSpell(player, ZM_CAPTURE_BUFF, true);
}
OutdoorPvP::HandlePlayerEnterZone(player, zone);
}
void OutdoorPvPZM::HandlePlayerLeaveZone(Player* player, uint32 zone)
{
// remove buffs
player->RemoveAurasDueToSpell(ZM_CAPTURE_BUFF);
// remove flag
player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_A);
player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_H);
OutdoorPvP::HandlePlayerLeaveZone(player, zone);
}
OutdoorPvPZM::OutdoorPvPZM()
{
m_TypeId = OUTDOOR_PVP_ZM;
m_Graveyard = nullptr;
m_AllianceTowersControlled = 0;
m_HordeTowersControlled = 0;
}
bool OutdoorPvPZM::SetupOutdoorPvP()
{
m_AllianceTowersControlled = 0;
m_HordeTowersControlled = 0;
SetMapFromZone(OutdoorPvPZMBuffZones[0]);
// add the zones affected by the pvp buff
for (uint8 i = 0; i < OutdoorPvPZMBuffZonesNum; ++i)
RegisterZone(OutdoorPvPZMBuffZones[i]);
AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_WEST));
AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_EAST));
m_Graveyard = new OPvPCapturePointZM_Graveyard(this);
AddCapturePoint(m_Graveyard); // though the update function isn't used, the handleusego is!
return true;
}
void OutdoorPvPZM::HandleKillImpl(Player* player, Unit* killed)
{
if (killed->GetTypeId() != TYPEID_PLAYER)
return;
if (player->GetTeam() == ALLIANCE && killed->ToPlayer()->GetTeam() != ALLIANCE)
player->CastSpell(player, ZM_AlliancePlayerKillReward, true);
else if (player->GetTeam() == HORDE && killed->ToPlayer()->GetTeam() != HORDE)
player->CastSpell(player, ZM_HordePlayerKillReward, true);
}
bool OPvPCapturePointZM_Graveyard::Update(uint32 /*diff*/)
{
bool retval = m_State != m_OldState;
m_State = m_OldState;
return retval;
}
int32 OPvPCapturePointZM_Graveyard::HandleOpenGo(Player* player, GameObject* go)
{
int32 retval = OPvPCapturePoint::HandleOpenGo(player, go);
if (retval >= 0)
{
if (player->HasAura(ZM_BATTLE_STANDARD_A) && m_GraveyardState != ZM_GRAVEYARD_A)
{
m_GraveyardState = ZM_GRAVEYARD_A;
DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant
AddObject(0, ZM_Banner_A.entry, ZM_Banner_A.map, ZM_Banner_A.pos, ZM_Banner_A.rot);
sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE); // rem gy
sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE, false); // add gy
m_PvP->TeamApplyBuff(TEAM_ALLIANCE, ZM_CAPTURE_BUFF);
player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_A);
m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_ALLIANCE);
}
else if (player->HasAura(ZM_BATTLE_STANDARD_H) && m_GraveyardState != ZM_GRAVEYARD_H)
{
m_GraveyardState = ZM_GRAVEYARD_H;
DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant
AddObject(0, ZM_Banner_H.entry, ZM_Banner_H.map, ZM_Banner_H.pos, ZM_Banner_H.rot);
sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE); // rem gy
sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE, false); // add gy
m_PvP->TeamApplyBuff(TEAM_HORDE, ZM_CAPTURE_BUFF);
player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_H);
m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_HORDE);
}
UpdateTowerState();
}
return retval;
}
OPvPCapturePointZM_Graveyard::OPvPCapturePointZM_Graveyard(OutdoorPvP* pvp) : OPvPCapturePoint(pvp)
{
m_BothControllingFaction = 0;
m_GraveyardState = ZM_GRAVEYARD_N;
m_FlagCarrierGUID.Clear();
// add field scouts here
AddCreature(ZM_ALLIANCE_FIELD_SCOUT, ZM_AllianceFieldScout.entry, ZM_AllianceFieldScout.map, ZM_AllianceFieldScout.pos);
AddCreature(ZM_HORDE_FIELD_SCOUT, ZM_HordeFieldScout.entry, ZM_HordeFieldScout.map, ZM_HordeFieldScout.pos);
// add neutral banner
AddObject(0, ZM_Banner_N.entry, ZM_Banner_N.map, ZM_Banner_N.pos, ZM_Banner_N.rot);
}
void OPvPCapturePointZM_Graveyard::UpdateTowerState()
{
m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, uint32((m_GraveyardState & ZM_GRAVEYARD_N) != 0));
m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, uint32((m_GraveyardState & ZM_GRAVEYARD_H) != 0));
m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, uint32((m_GraveyardState & ZM_GRAVEYARD_A) != 0));
m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_READY, uint32(m_BothControllingFaction == ALLIANCE));
m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_NOT_READY, uint32(m_BothControllingFaction != ALLIANCE));
m_PvP->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_READY, uint32(m_BothControllingFaction == HORDE));
m_PvP->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_NOT_READY, uint32(m_BothControllingFaction != HORDE));
}
void OPvPCapturePointZM_Graveyard::FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& packet)
{
packet.Worldstates.emplace_back(ZM_MAP_GRAVEYARD_N, (m_GraveyardState & ZM_GRAVEYARD_N) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_GRAVEYARD_H, (m_GraveyardState & ZM_GRAVEYARD_H) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_GRAVEYARD_A, (m_GraveyardState & ZM_GRAVEYARD_A) != 0 ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_ALLIANCE_FLAG_READY, m_BothControllingFaction == ALLIANCE ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_ALLIANCE_FLAG_NOT_READY, m_BothControllingFaction != ALLIANCE ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_HORDE_FLAG_READY, m_BothControllingFaction == HORDE ? 1 : 0);
packet.Worldstates.emplace_back(ZM_MAP_HORDE_FLAG_NOT_READY, m_BothControllingFaction != HORDE ? 1 : 0);
}
void OPvPCapturePointZM_Graveyard::SetBeaconState(uint32 controlling_faction)
{
// nothing to do here
if (m_BothControllingFaction == controlling_faction)
return;
m_BothControllingFaction = controlling_faction;
switch (controlling_faction)
{
case ALLIANCE:
// if ally already controls the gy and taken back both beacons, return, nothing to do for us
if (m_GraveyardState & ZM_GRAVEYARD_A)
return;
// ally doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner
break;
case HORDE:
// if horde already controls the gy and taken back both beacons, return, nothing to do for us
if (m_GraveyardState & ZM_GRAVEYARD_H)
return;
// horde doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner
break;
default:
// if the graveyard is not neutral, then leave it that way
// if the graveyard is neutral, then we have to dispel the buff from the flag carrier
if (m_GraveyardState & ZM_GRAVEYARD_N)
{
// gy was neutral, thus neutral banner was spawned, it is possible that someone was taking the flag to the gy
if (!m_FlagCarrierGUID.IsEmpty())
{
// remove flag from carrier, reset flag carrier guid
Player* p = ObjectAccessor::FindPlayer(m_FlagCarrierGUID);
if (p)
{
p->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_A);
p->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_H);
}
m_FlagCarrierGUID.Clear();
}
}
break;
}
// send worldstateupdate
UpdateTowerState();
}
bool OPvPCapturePointZM_Graveyard::CanTalkTo(Player* player, Creature* c, GossipMenuItems const& /*gso*/)
{
std::map<uint32, uint32>::iterator itr = m_CreatureTypes.find(c->GetSpawnId());
if (itr != m_CreatureTypes.end())
{
if (itr->second == ZM_ALLIANCE_FIELD_SCOUT && player->GetTeam() == ALLIANCE && m_BothControllingFaction == ALLIANCE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_A)
return true;
else if (itr->second == ZM_HORDE_FIELD_SCOUT && player->GetTeam() == HORDE && m_BothControllingFaction == HORDE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_H)
return true;
}
return false;
}
bool OPvPCapturePointZM_Graveyard::HandleGossipOption(Player* player, Creature* creature, uint32 /*gossipid*/)
{
std::map<uint32, uint32>::iterator itr = m_CreatureTypes.find(creature->GetSpawnId());
if (itr != m_CreatureTypes.end())
{
// if the flag is already taken, then return
if (!m_FlagCarrierGUID.IsEmpty())
return true;
if (itr->second == ZM_ALLIANCE_FIELD_SCOUT)
{
creature->CastSpell(player, ZM_BATTLE_STANDARD_A, true);
m_FlagCarrierGUID = player->GetGUID();
}
else if (itr->second == ZM_HORDE_FIELD_SCOUT)
{
creature->CastSpell(player, ZM_BATTLE_STANDARD_H, true);
m_FlagCarrierGUID = player->GetGUID();
}
UpdateTowerState();
player->PlayerTalkClass->SendCloseGossip();
return true;
}
return false;
}
bool OPvPCapturePointZM_Graveyard::HandleDropFlag(Player* /*player*/, uint32 spellId)
{
switch (spellId)
{
case ZM_BATTLE_STANDARD_A:
m_FlagCarrierGUID.Clear();
return true;
case ZM_BATTLE_STANDARD_H:
m_FlagCarrierGUID.Clear();
return true;
}
return false;
}
uint32 OPvPCapturePointZM_Graveyard::GetGraveyardState() const
{
return m_GraveyardState;
}
uint32 OutdoorPvPZM::GetAllianceTowersControlled() const
{
return m_AllianceTowersControlled;
}
void OutdoorPvPZM::SetAllianceTowersControlled(uint32 count)
{
m_AllianceTowersControlled = count;
}
uint32 OutdoorPvPZM::GetHordeTowersControlled() const
{
return m_HordeTowersControlled;
}
void OutdoorPvPZM::SetHordeTowersControlled(uint32 count)
{
m_HordeTowersControlled = count;
}
void OutdoorPvPZM::FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& packet)
{
packet.Worldstates.emplace_back(ZM_WORLDSTATE_UNK_1, 1);
for (OPvPCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
itr->second->FillInitialWorldStates(packet);
}
void OutdoorPvPZM::SendRemoveWorldStates(Player* player)
{
player->SendUpdateWorldState(ZM_WORLDSTATE_UNK_1, 1);
player->SendUpdateWorldState(ZM_UI_TOWER_EAST_N, 0);
player->SendUpdateWorldState(ZM_UI_TOWER_EAST_H, 0);
player->SendUpdateWorldState(ZM_UI_TOWER_EAST_A, 0);
player->SendUpdateWorldState(ZM_UI_TOWER_WEST_N, 0);
player->SendUpdateWorldState(ZM_UI_TOWER_WEST_H, 0);
player->SendUpdateWorldState(ZM_UI_TOWER_WEST_A, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_EAST_N, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_EAST_H, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_EAST_A, 0);
player->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, 0);
player->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, 0);
player->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_WEST_N, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_WEST_H, 0);
player->SendUpdateWorldState(ZM_MAP_TOWER_WEST_A, 0);
player->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_READY, 0);
player->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_NOT_READY, 0);
player->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_NOT_READY, 0);
player->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_READY, 0);
}
class OutdoorPvP_zangarmarsh : public OutdoorPvPScript
{
public:
OutdoorPvP_zangarmarsh() : OutdoorPvPScript("outdoorpvp_zm") { }
OutdoorPvP* GetOutdoorPvP() const override
{
return new OutdoorPvPZM();
}
};
void AddSC_outdoorpvp_zm()
{
new OutdoorPvP_zangarmarsh();
}
| 0 | 0.958672 | 1 | 0.958672 | game-dev | MEDIA | 0.990351 | game-dev | 0.582845 | 1 | 0.582845 |
manisha-v/Unity3D | 2,218 | Part1 - 3D Movement/Codes/Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Editor/TMP_ResourcesLoader.cs | using UnityEditor;
using UnityEngine;
using System.Collections;
namespace TMPro.EditorUtilities
{
//[InitializeOnLoad]
class TMP_ResourcesLoader
{
/// <summary>
/// Function to pre-load the TMP Resources
/// </summary>
public static void LoadTextMeshProResources()
{
//TMP_Settings.LoadDefaultSettings();
//TMP_StyleSheet.LoadDefaultStyleSheet();
}
static TMP_ResourcesLoader()
{
//Debug.Log("Loading TMP Resources...");
// Get current targetted platform
//string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
//TMPro.TMP_Settings.LoadDefaultSettings();
//TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
}
//[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
//static void OnBeforeSceneLoaded()
//{
//Debug.Log("Before scene is loaded.");
// //TMPro.TMP_Settings.LoadDefaultSettings();
// //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
// //ShaderVariantCollection collection = new ShaderVariantCollection();
// //Shader s0 = Shader.Find("TextMeshPro/Mobile/Distance Field");
// //ShaderVariantCollection.ShaderVariant tmp_Variant = new ShaderVariantCollection.ShaderVariant(s0, UnityEngine.Rendering.PassType.Normal, string.Empty);
// //collection.Add(tmp_Variant);
// //collection.WarmUp();
//}
}
//static class TMP_ProjectSettings
//{
// [InitializeOnLoadMethod]
// static void SetProjectDefineSymbols()
// {
// string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
// //Check for and inject TMP_INSTALLED
// if (!currentBuildSettings.Contains("TMP_PRESENT"))
// {
// PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT");
// }
// }
//}
}
| 0 | 0.601373 | 1 | 0.601373 | game-dev | MEDIA | 0.739324 | game-dev | 0.766908 | 1 | 0.766908 |
esmini/esmini | 5,448 | EnvironmentSimulator/Modules/Controllers/Controller.hpp | /*
* esmini - Environment Simulator Minimalistic
* https://github.com/esmini/esmini
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright (c) partners of Simulation Scenarios
* https://sites.google.com/view/simulationscenarios
*/
#pragma once
#include <string>
#include "CommonMini.hpp"
#include "OSCProperties.hpp"
#include "Parameters.hpp"
#define CONTROLLER_BASE_TYPE_NAME "ControllerClass"
#define CONTROLLER_BASE_TYPE_ID -1
namespace scenarioengine
{
// Forward declarations
class ScenarioPlayer;
class ScenarioGateway;
class ScenarioEngine;
class Entities;
class Object;
// base class for controllers
class Controller
{
public:
enum Type
{
CONTROLLER_TYPE_DEFAULT,
CONTROLLER_TYPE_EXTERNAL,
CONTROLLER_TYPE_FOLLOW_GHOST,
CONTROLLER_TYPE_FOLLOW_ROUTE,
CONTROLLER_TYPE_INTERACTIVE,
CONTROLLER_TYPE_SLOPPY_DRIVER,
CONTROLLER_TYPE_SUMO,
CONTROLLER_TYPE_REL2ABS,
CONTROLLER_TYPE_ACC,
CONTROLLER_TYPE_NATURAL_DRIVER,
CONTROLLER_TYPE_ALKS,
CONTROLLER_TYPE_UDP_DRIVER,
CONTROLLER_TYPE_ECE_ALKS_REF_DRIVER,
CONTROLLER_ALKS_R157SM,
CONTROLLER_TYPE_LOOMING,
CONTROLLER_TYPE_OFFROAD_FOLLOWER,
CONTROLLER_TYPE_HID,
CONTROLLER_TYPE_FOLLOW_REFERENCE,
N_CONTROLLER_TYPES,
CONTROLLER_TYPE_UNDEFINED,
GHOST_RESERVED_TYPE = 100,
USER_CONTROLLER_TYPE_BASE = 1000,
};
typedef struct
{
std::string name;
std::string type;
OSCProperties* properties;
ScenarioGateway* gateway;
ScenarioEngine* scenario_engine;
Parameters* parameters;
} InitArgs;
Controller(InitArgs* args = nullptr);
virtual ~Controller() = default;
virtual const char* GetTypeName()
{
return CONTROLLER_BASE_TYPE_NAME;
}
virtual int GetType()
{
return CONTROLLER_BASE_TYPE_ID;
}
virtual void LinkObject(Object* object);
virtual void UnlinkObject();
virtual int Activate(const ControlActivationMode (&mode)[static_cast<unsigned int>(ControlDomains::COUNT)]);
virtual void Deactivate()
{
DeactivateDomains(static_cast<unsigned int>(ControlDomainMasks::DOMAIN_MASK_ALL));
};
virtual void DeactivateDomains(unsigned int domains);
// Executed by scenarioengine before first step
virtual void Init(){};
// Executed by player after player and viewer intialization
virtual void InitPostPlayer(){};
virtual void ReportKeyEvent(int key, bool down);
virtual void SetPlayer(ScenarioPlayer* player)
{
player_ = player;
};
// Base class Step function should be called from derived classes
virtual void Step(double timeStep);
bool Active() const
{
return (active_domains_ != static_cast<unsigned int>(ControlDomainMasks::DOMAIN_MASK_NONE));
};
std::string GetName() const
{
return name_;
}
void SetName(std::string name)
{
name_ = name;
}
unsigned int GetOperatingDomains() const
{
return operating_domains_;
}
unsigned int GetActiveDomains() const
{
return active_domains_;
}
ControlOperationMode GetMode() const
{
return mode_;
}
std::string Mode2Str(ControlOperationMode mode);
Object* GetRoadObject()
{
return object_;
}
bool IsActiveOnDomainsOnly(unsigned int domainMask) const;
bool IsActiveOnDomains(unsigned int domainMask) const;
bool IsNotActiveOnDomains(unsigned int domainMask) const;
bool IsActiveOnAnyOfDomains(unsigned int domainMask) const;
bool IsActive() const;
Object* GetLinkedObject()
{
return object_;
}
protected:
unsigned int operating_domains_; // bitmask representing domains controller is operating on
unsigned int active_domains_; // bitmask representing domains controller is currently active on
ControlOperationMode mode_; // add to scenario actions or replace
Object* object_; // The object to which the controller is attached and hence controls
std::string name_;
std::string type_name_;
Entities* entities_;
ScenarioGateway* gateway_;
ScenarioEngine* scenario_engine_;
ScenarioPlayer* player_;
bool align_to_road_heading_on_deactivation_ = false;
bool align_to_road_heading_on_activation_ = false;
void AlignToRoadHeading();
};
typedef Controller* (*ControllerInstantiateFunction)(void* args);
Controller* InstantiateController(void* args);
} // namespace scenarioengine | 0 | 0.934809 | 1 | 0.934809 | game-dev | MEDIA | 0.58234 | game-dev | 0.633055 | 1 | 0.633055 |
dreamanlan/CSharpGameFramework | 7,967 | App/ClientModule/PluginFramework/GmCommands/ClientGmStorySystem.cs | using System;
using System.Collections.Generic;
using DotnetStoryScript;
namespace ScriptableFramework.GmCommands
{
/// <summary>
/// The Gm plot system is a special plot system composed of adding GM commands on top of the game plot system. The commands and values added by the game plot system can be used in the Gm plot script (and vice versa)
/// </summary>
/// <remarks>
/// 1. The commands and values registered in the plot system are shared, that is, the Gm commands and values registered in the Gm plot system can also be used in normal plot scripts!
/// (This system should be removed from the client when publishing.)
/// 2. The plot script and the Gm plot script are not a system and have nothing to do with each other.
/// </remarks>
public sealed class ClientGmStorySystem
{
public void Init()
{
//register GM commands
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "enablecalculatorlog", "enablecalculatorlog command", new StoryCommandFactoryHelper<EnableCalculatorLogCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "resetdsl", "resetdsl command", new StoryCommandFactoryHelper<DoResetDslCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "scp", "scp command", new StoryCommandFactoryHelper<DoScpCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "gm", "gm command", new StoryCommandFactoryHelper<DoGmCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "setdebug", "setdebug command", new StoryCommandFactoryHelper<SetDebugCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "allocmemory", "allocmemory command", new StoryCommandFactoryHelper<AllocMemoryCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "freememory", "freememory command", new StoryCommandFactoryHelper<FreeMemoryCommand>());
StoryCommandManager.Instance.RegisterCommandFactory(StoryCommandGroupDefine.GM, "consumecpu", "consumecpu command", new StoryCommandFactoryHelper<ConsumeCpuCommand>());
//register value or functions
}
public int ActiveStoryCount
{
get
{
return m_StoryLogicInfos.Count;
}
}
public StrBoxedValueDict GlobalVariables
{
get { return m_GlobalVariables; }
}
public void ClearGlobalVariables()
{
m_GlobalVariables.Clear();
}
public void Reset()
{
int count = m_StoryLogicInfos.Count;
for (int index = count - 1; index >= 0; --index) {
StoryInstance info = m_StoryLogicInfos[index];
if (null != info) {
m_StoryLogicInfos.RemoveAt(index);
}
}
m_StoryLogicInfos.Clear();
}
public void LoadStory(string file)
{
m_StoryInstancePool.Clear();
m_ConfigManager.Clear();
m_ConfigManager.LoadStory(file, 0, string.Empty);
}
public void LoadStoryText(byte[] bytes)
{
m_StoryInstancePool.Clear();
m_ConfigManager.Clear();
m_ConfigManager.LoadStoryText(string.Empty, bytes, 0, string.Empty);
}
public StoryInstance GetStory(string storyId)
{
return GetStoryInstance(storyId);
}
public void StartStory(string storyId)
{
StoryInstance inst = NewStoryInstance(storyId);
if (null != inst) {
StopStory(storyId);
m_StoryLogicInfos.Add(inst);
inst.Context = null;
inst.GlobalVariables = m_GlobalVariables;
inst.Start();
LogSystem.Info("StartStory {0}", storyId);
}
}
public void StopStory(string storyId)
{
int count = m_StoryLogicInfos.Count;
for (int index = count - 1; index >= 0; --index) {
StoryInstance info = m_StoryLogicInfos[index];
if (info.StoryId == storyId) {
m_StoryLogicInfos.RemoveAt(index);
}
}
}
public void Tick()
{
long time = TimeUtility.GetLocalMilliseconds();
int ct = m_StoryLogicInfos.Count;
for (int ix = ct - 1; ix >= 0; --ix) {
StoryInstance info = m_StoryLogicInfos[ix];
info.Tick(time);
if (info.IsTerminated) {
m_StoryLogicInfos.RemoveAt(ix);
}
}
}
public void SendMessage(string msgId)
{
int ct = m_StoryLogicInfos.Count;
for (int ix = ct - 1; ix >= 0; --ix) {
StoryInstance info = m_StoryLogicInfos[ix];
info.SendMessage(msgId);
}
}
public void SendMessage(string msgId, BoxedValue arg1)
{
int ct = m_StoryLogicInfos.Count;
for (int ix = ct - 1; ix >= 0; --ix)
{
StoryInstance info = m_StoryLogicInfos[ix];
info.SendMessage(msgId, arg1);
}
}
public void SendMessage(string msgId, BoxedValue arg1, BoxedValue arg2)
{
int ct = m_StoryLogicInfos.Count;
for (int ix = ct - 1; ix >= 0; --ix)
{
StoryInstance info = m_StoryLogicInfos[ix];
info.SendMessage(msgId, arg1, arg2);
}
}
public void SendMessage(string msgId, BoxedValue arg1, BoxedValue arg2, BoxedValue arg3)
{
int ct = m_StoryLogicInfos.Count;
for (int ix = ct - 1; ix >= 0; --ix)
{
StoryInstance info = m_StoryLogicInfos[ix];
info.SendMessage(msgId, arg1, arg2, arg3);
}
}
private StoryInstance NewStoryInstance(string storyId)
{
StoryInstance instance = GetStoryInstance(storyId);
if (null == instance) {
instance = m_ConfigManager.NewStoryInstance(storyId, 0);
if (instance == null) {
ScriptableFramework.LogSystem.Error("Can't load story config, story:{0} !", storyId);
return null;
}
AddStoryInstance(storyId, instance);
return instance;
} else {
return instance;
}
}
private void AddStoryInstance(string storyId, StoryInstance info)
{
if (!m_StoryInstancePool.ContainsKey(storyId)) {
m_StoryInstancePool.Add(storyId, info);
} else {
m_StoryInstancePool[storyId] = info;
}
}
private StoryInstance GetStoryInstance(string storyId)
{
StoryInstance info;
m_StoryInstancePool.TryGetValue(storyId, out info);
return info;
}
private ClientGmStorySystem() { }
private StrBoxedValueDict m_GlobalVariables = new StrBoxedValueDict();
private List<StoryInstance> m_StoryLogicInfos = new List<StoryInstance>();
private Dictionary<string, StoryInstance> m_StoryInstancePool = new Dictionary<string, StoryInstance>();
private StoryConfigManager m_ConfigManager = StoryConfigManager.NewInstance();
public static ClientGmStorySystem Instance
{
get
{
return s_Instance;
}
}
private static ClientGmStorySystem s_Instance = new ClientGmStorySystem();
}
}
| 0 | 0.8734 | 1 | 0.8734 | game-dev | MEDIA | 0.831871 | game-dev | 0.892642 | 1 | 0.892642 |
AvaloniaUI/Avalonia | 4,577 | src/Avalonia.Base/Rendering/Composition/Server/ServerCompositionContainerVisual.cs | using System;
using System.Numerics;
using Avalonia.Media;
using Avalonia.Platform;
namespace Avalonia.Rendering.Composition.Server
{
/// <summary>
/// Server-side counterpart of <see cref="CompositionContainerVisual"/>.
/// Mostly propagates update and render calls, but is also responsible
/// for updating adorners in deferred manner
/// </summary>
internal partial class ServerCompositionContainerVisual : ServerCompositionVisual
{
public ServerCompositionVisualCollection Children { get; private set; } = null!;
private LtrbRect? _transformedContentBounds;
private IImmutableEffect? _oldEffect;
protected override void RenderCore(ServerVisualRenderContext context, LtrbRect currentTransformedClip)
{
base.RenderCore(context, currentTransformedClip);
if (context.RenderChildren)
{
foreach (var ch in Children)
{
ch.Render(context, currentTransformedClip);
}
}
}
public override UpdateResult Update(ServerCompositionTarget root, Matrix parentCombinedTransform)
{
var (combinedBounds, oldInvalidated, newInvalidated) = base.Update(root, parentCombinedTransform);
foreach (var child in Children)
{
if (child.AdornedVisual != null)
root.EnqueueAdornerUpdate(child);
else
{
var res = child.Update(root, GlobalTransformMatrix);
oldInvalidated |= res.InvalidatedOld;
newInvalidated |= res.InvalidatedNew;
combinedBounds = LtrbRect.FullUnion(combinedBounds, res.Bounds);
}
}
// If effect is changed, we need to clean both old and new bounds
var effectChanged = !Effect.EffectEquals(_oldEffect);
if (effectChanged)
oldInvalidated = newInvalidated = true;
// Expand invalidated bounds to the whole content area since we don't actually know what is being sampled
// We also ignore clip for now since we don't have means to reset it?
if (_oldEffect != null && oldInvalidated && _transformedContentBounds.HasValue)
AddEffectPaddedDirtyRect(_oldEffect, _transformedContentBounds.Value);
if (Effect != null && newInvalidated && combinedBounds.HasValue)
AddEffectPaddedDirtyRect(Effect, combinedBounds.Value);
_oldEffect = Effect;
_transformedContentBounds = combinedBounds;
IsDirtyComposition = false;
return new(_transformedContentBounds, oldInvalidated, newInvalidated);
}
void AddEffectPaddedDirtyRect(IImmutableEffect effect, LtrbRect transformedBounds)
{
var padding = effect.GetEffectOutputPadding();
if (padding == default)
{
AddDirtyRect(transformedBounds);
return;
}
// We are in a weird position here: bounds are in global coordinates while padding gets applied in local ones
// Since we have optimizations to AVOID recomputing transformed bounds and since visuals with effects are relatively rare
// we instead apply the transformation matrix to rescale the bounds
// If we only have translation and scale, just scale the padding
if (CombinedTransformMatrix is
{
M12: 0, M13: 0,
M21: 0, M23: 0,
M31: 0, M32: 0
})
padding = new Thickness(padding.Left * CombinedTransformMatrix.M11,
padding.Top * CombinedTransformMatrix.M22,
padding.Right * CombinedTransformMatrix.M11,
padding.Bottom * CombinedTransformMatrix.M22);
else
{
// Conservatively use the transformed rect size
var transformedPaddingRect = new Rect().Inflate(padding).TransformToAABB(CombinedTransformMatrix);
padding = new(Math.Max(transformedPaddingRect.Width, transformedPaddingRect.Height));
}
AddDirtyRect(transformedBounds.Inflate(padding));
}
partial void Initialize()
{
Children = new ServerCompositionVisualCollection(Compositor);
}
}
}
| 0 | 0.957957 | 1 | 0.957957 | game-dev | MEDIA | 0.537105 | game-dev,graphics-rendering | 0.973141 | 1 | 0.973141 |
ManlyMarco/KoikatuGameplayMods | 2,277 | src/StudioCameraObjectTweaks/StudioCameraObjectTweaksPlugin.cs | using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Studio;
using UnityEngine;
namespace StudioCameraObjectTweaks
{
[BepInPlugin(GUID, "Studio Camera Tweaks", Version)]
[BepInProcess("CharaStudio")]
[BepInProcess("StudioNEOV2")]
public class StudioCameraObjectTweaksPlugin : BaseUnityPlugin
{
public const string GUID = "StudioCameraTweaks";
public const string Version = "1.0";
private static ConfigEntry<bool> _spawnAtMaincam;
private static ConfigEntry<bool> _turnOffByDefault;
private static OCICamera _lastCamera;
private void Awake()
{
_spawnAtMaincam = Config.Bind("Camera Object", "Spawn at current camera position", true,
"Should clicking the Camera button in Workspace window spawn the new camera at the current viewport camera position?\n" +
"The deafault is to spawn the new camera object at either origin point or current cursor position.");
_turnOffByDefault = Config.Bind("Camera Object", "Hide newly created camera objects", true,
"Automatically disable newly spawned camera objects in the workspace.\n" +
"This will cause their gizmo to not appear, but they will still function normally.\n" +
"Useful when spawning at current camera position to not obscure the view.");
Harmony.CreateAndPatchAll(typeof(StudioCameraObjectTweaksPlugin));
}
[HarmonyPostfix]
[HarmonyPatch(typeof(AddObjectCamera), nameof(AddObjectCamera.Add))]
public static void AddCameraHook1(OCICamera __result)
{
_lastCamera = __result;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(WorkspaceCtrl), "OnClickCamera")]
public static void AddCameraHook2()
{
if (_spawnAtMaincam.Value)
{
var changeAmount = _lastCamera.objectInfo.changeAmount;
var camera = Camera.main.transform;
changeAmount.pos = camera.position;
changeAmount.rot = camera.rotation.eulerAngles;
if (_turnOffByDefault.Value)
_lastCamera.treeNodeObject.SetVisible(false);
}
}
}
}
| 0 | 0.551943 | 1 | 0.551943 | game-dev | MEDIA | 0.603767 | game-dev | 0.797121 | 1 | 0.797121 |
renancaraujo/watchsteroids | 7,293 | lib/game/game/asteroid.dart | import 'dart:math';
import 'dart:ui';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:watchsteroids/game/game.dart';
enum AsteroidSpawnArea {
northWest(-470, -470),
north(-100, -470),
northEast(270, -470),
west(-470, -100),
southEast(270, 270),
south(-100, 270),
southWest(-470, 270),
east(270, -100);
const AsteroidSpawnArea(this.originX, this.originY);
final double originX;
final double originY;
AsteroidSpawnArea get opposite {
switch (this) {
case AsteroidSpawnArea.northWest:
return AsteroidSpawnArea.southEast;
case AsteroidSpawnArea.north:
return AsteroidSpawnArea.south;
case AsteroidSpawnArea.northEast:
return AsteroidSpawnArea.southWest;
case AsteroidSpawnArea.west:
return AsteroidSpawnArea.east;
case AsteroidSpawnArea.southEast:
return AsteroidSpawnArea.northWest;
case AsteroidSpawnArea.south:
return AsteroidSpawnArea.north;
case AsteroidSpawnArea.southWest:
return AsteroidSpawnArea.northEast;
case AsteroidSpawnArea.east:
return AsteroidSpawnArea.west;
}
}
AsteroidSpawnArea get curvedOpposite {
switch (this) {
case AsteroidSpawnArea.northWest:
return random.nextBool()
? AsteroidSpawnArea.southWest
: AsteroidSpawnArea.east;
case AsteroidSpawnArea.north:
return random.nextBool()
? AsteroidSpawnArea.southWest
: AsteroidSpawnArea.southEast;
case AsteroidSpawnArea.northEast:
return random.nextBool()
? AsteroidSpawnArea.northWest
: AsteroidSpawnArea.south;
case AsteroidSpawnArea.west:
return random.nextBool()
? AsteroidSpawnArea.northEast
: AsteroidSpawnArea.north;
case AsteroidSpawnArea.southEast:
return random.nextBool()
? AsteroidSpawnArea.west
: AsteroidSpawnArea.north;
case AsteroidSpawnArea.south:
return random.nextBool()
? AsteroidSpawnArea.northWest
: AsteroidSpawnArea.northEast;
case AsteroidSpawnArea.southWest:
return random.nextBool()
? AsteroidSpawnArea.north
: AsteroidSpawnArea.east;
case AsteroidSpawnArea.east:
return random.nextBool()
? AsteroidSpawnArea.northWest
: AsteroidSpawnArea.southWest;
}
}
Vector2 get origin => Vector2(originX, originY);
}
class AsteroidSpawner extends Component
with
HasGameRef<WatchsteroidsGame>,
FlameBlocListenable<GameCubit, GameState> {
AsteroidSpawner() {
timer = initialTimer;
}
static const interval = 3.0;
late Timer timer;
Timer get initialTimer => Timer(
0,
onTick: onTick,
autoStart: false,
);
void onTick() {
final nextPeriod = random.nextDouble() * 0.3 + interval;
timer = Timer(
nextPeriod,
onTick: onTick,
);
final path = generateAsteroidPath();
gameRef.flameMultiBlocProvider.add(Asteroid(path));
// gameRef.add(ProtoRenderPath(path));
}
Path generateAsteroidPath() {
final path = Path();
final random = Random();
final spawnArea = AsteroidSpawnArea
.values[random.nextInt(AsteroidSpawnArea.values.length)];
final curved = random.nextBool();
AsteroidSpawnArea destinationArea;
if (curved) {
destinationArea = spawnArea.curvedOpposite;
} else {
destinationArea = spawnArea.opposite;
}
final originPoint = Vector2.random(random)..multiply(Vector2(200, 200));
final destinationPoint = Vector2.random(random)
..multiply(Vector2(200, 200));
final origin = spawnArea.origin + originPoint;
final destination = destinationArea.origin + destinationPoint;
path.moveTo(origin.x, origin.y);
if (curved) {
path.conicTo(0, 0, destination.x, destination.y, 2);
} else {
path.lineTo(destination.x, destination.y);
}
return path;
}
@override
void update(double dt) {
if (!bloc.isPlaying) {
return;
}
timer.update(dt);
}
@override
void onNewState(GameState state) {
switch (state) {
case GameState.playing:
timer = initialTimer;
timer.start();
case GameState.initial:
case GameState.gameOver:
timer.stop();
}
}
}
class Asteroid extends PositionComponent
with
HasGameRef<WatchsteroidsGame>,
FlameBlocListenable<GameCubit, GameState> {
Asteroid(this.path)
: super(
position: Vector2(0, 0),
priority: 90,
anchor: Anchor.center,
);
final Path path;
late int heath = (random.nextDouble() < 0.75) ? 2 : 3;
void takeHit(Set<Vector2> intersectionPoints, double angle) {
heath--;
if (heath <= 0) {
removeFromParent();
gameRef.flameMultiBlocProvider.add(
AsteroidExplosion(position: absolutePositionOfAnchor(Anchor.center)),
);
gameRef.scoreCubit.point();
} else {
for (final intersectionPoint in intersectionPoints) {
gameRef.flameMultiBlocProvider.add(
AsteroidHit(
position: intersectionPoint,
),
);
}
}
}
RotateEffect? rotateEffect;
MoveAlongPathEffect? moveAlongPathEffect;
@override
Future<void> onLoad() async {
await add(AsteroidSprite());
await add(
rotateEffect = RotateEffect.by(
pi * 2,
InfiniteEffectController(
LinearEffectController(random.nextDouble() * 5 + 4),
),
),
);
await add(
moveAlongPathEffect = MoveAlongPathEffect(
path,
LinearEffectController(random.nextDouble() * 5 + 14),
onComplete: removeFromParent,
),
);
}
@override
void onNewState(GameState state) {
switch (state) {
case GameState.initial:
case GameState.playing:
removeFromParent();
case GameState.gameOver:
rotateEffect?.pause();
moveAlongPathEffect?.pause();
}
}
}
class AsteroidSprite extends SpriteComponent
with HasGameRef<WatchsteroidsGame>, ParentIsA<Asteroid> {
AsteroidSprite({super.position}) : super(anchor: Anchor.center);
@override
Paint paint = Paint()..blendMode = BlendMode.softLight;
@override
Future<void> onLoad() async {
sprite = await gameRef.loadSprite(
'protoasteroid2.png',
srcSize: Vector2(57, 68),
);
size = Vector2(57, 68);
position = Vector2.zero();
await add(
PolygonHitbox(
[
Vector2(26.5, 0),
Vector2(38.5, 20.5),
Vector2(55.9, 27),
Vector2(38.1, 57.4),
Vector2(13.7, 67.9),
Vector2(0, 31.9),
Vector2(10.3, 12.3),
],
isSolid: true,
),
);
}
}
class ProtoRenderPath extends Component {
ProtoRenderPath(this.path);
final Path path;
static final paint = Paint()
..color = const Color(0xFF00FF00)
..style = PaintingStyle.stroke
..strokeWidth = 1;
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawPath(path, paint);
}
}
| 0 | 0.960427 | 1 | 0.960427 | game-dev | MEDIA | 0.986733 | game-dev | 0.99408 | 1 | 0.99408 |
bates64/papermario-dx | 39,213 | src/world/area_jan/jan_03/npc.c | #include "jan_03.h"
#include "sprite/player.h"
#include "world/common/npc/Toad_Stationary.inc.c"
#include "world/common/npc/Yoshi.inc.c"
#include "world/common/npc/Yoshi_Patrol.inc.c"
#include "world/common/npc/YoshiKid.inc.c"
#include "world/common/npc/YoshiKid_Patrol.inc.c"
#include "world/common/npc/Raven.inc.c"
#include "world/common/npc/Sushie.inc.c"
#include "world/common/npc/Kolorado.inc.c"
#include "world/common/complete/ToadHouseBlanketAnim.inc.c"
#include "world/common/atomic/ToadHouse.inc.c"
#include "world/common/atomic/ToadHouse.data.inc.c"
#include "world/common/complete/KeyItemChoice.inc.c"
#include "world/common/complete/ConsumableItemChoice.inc.c"
#define CHUCK_QUIZMO_NPC_ID NPC_ChuckQuizmo
#include "world/common/complete/Quizmo.inc.c"
#include "world/common/complete/LetterDelivery.inc.c"
s32 N(RedYoshiKidLetters)[] = {
ITEM_LETTER_CHAIN_YOSHI_KID,
ITEM_NONE
};
EvtScript N(EVS_LetterPrompt_RedYoshiKid) = {
Call(N(LetterDelivery_Init),
NPC_YoshiKid_02, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle,
ITEM_LETTER_CHAIN_YOSHI_KID, ITEM_LETTER_CHAIN_DANE_T_2,
MSG_CH5_0079, MSG_CH5_007A, MSG_CH5_007B, MSG_CH5_007C,
Ref(N(RedYoshiKidLetters)))
ExecWait(N(EVS_DoLetterDelivery))
Return
End
};
s32 N(KoloradoLetters)[] = {
ITEM_LETTER_TO_KOLORADO,
ITEM_NONE
};
EvtScript N(EVS_LetterPrompt_Kolorado) = {
Call(N(LetterDelivery_Init),
NPC_Kolorado, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle,
ITEM_LETTER_TO_KOLORADO, ITEM_NONE,
MSG_CH5_001D, MSG_CH5_001E, MSG_CH5_001F, MSG_CH5_0020,
Ref(N(KoloradoLetters)))
ExecWait(N(EVS_DoLetterDelivery))
Return
End
};
EvtScript N(EVS_LetterReward_Kolorado) = {
IfEq(LVarC, DELIVERY_ACCEPTED)
EVT_GIVE_STAR_PIECE()
EndIf
Return
End
};
s32 N(FoodItemList)[] = {
ITEM_FRIED_SHROOM,
ITEM_SPICY_SOUP,
ITEM_NUTTY_CAKE,
ITEM_KOOPA_TEA,
ITEM_SPAGHETTI,
ITEM_BIG_COOKIE,
ITEM_CAKE,
ITEM_FRIED_EGG,
ITEM_BOILED_EGG,
ITEM_FROZEN_FRIES,
ITEM_POTATO_SALAD,
ITEM_HOT_SHROOM,
ITEM_BLAND_MEAL,
ITEM_HONEY_SHROOM,
ITEM_MAPLE_SHROOM,
ITEM_JELLY_SHROOM,
ITEM_SHROOM_CAKE,
ITEM_SHROOM_STEAK,
ITEM_HONEY_SUPER,
ITEM_MAPLE_SUPER,
ITEM_JELLY_SUPER,
ITEM_YUMMY_MEAL,
ITEM_HONEY_ULTRA,
ITEM_MAPLE_ULTRA,
ITEM_JELLY_ULTRA,
ITEM_SWEET_SHROOM,
ITEM_ELECTRO_POP,
ITEM_FIRE_POP,
ITEM_SPECIAL_SHAKE,
ITEM_COCO_POP,
ITEM_LIME_CANDY,
ITEM_LEMON_CANDY,
ITEM_HONEY_CANDY,
ITEM_JELLY_POP,
ITEM_APPLE_PIE,
ITEM_KOOPASTA,
ITEM_KOOKY_COOKIE,
ITEM_YOSHI_COOKIE,
ITEM_NONE
};
API_CALLABLE(N(CountFoodItems)) {
Bytecode* args = script->ptrReadPos;
PlayerData* playerData = &gPlayerData;
s32 outVar = *args++;
s32 foodCount = 0;
s32* it;
s32 i;
for (i = 0; i < ARRAY_COUNT(playerData->invItems); i++) {
it = N(FoodItemList);
while (*it != 0) {
if (playerData->invItems[i] == *it++) {
foodCount++;
}
}
}
evt_set_variable(script, outVar, foodCount);
return ApiStatus_DONE2;
}
EvtScript N(EVS_GetRescuedYoshiCount) = {
Set(LVar0, 0)
Add(LVar0, GF_JAN05_SavedYoshi)
Add(LVar0, GF_JAN07_SavedYoshi)
Add(LVar0, GF_JAN08_SavedYoshi)
Add(LVar0, GF_JAN10_SavedYoshi)
Add(LVar0, GF_JAN11_SavedYoshi)
Return
End
};
EvtScript N(EVS_ToadHouse_SetDialogue) = {
Set(LVar0, MSG_CH5_0094)
Set(LVar8, MSG_CH5_0095)
Set(LVar1, MSG_CH5_0096)
Set(LVar2, MSG_CH5_0097)
Set(LVar3, MSG_CH5_0098)
Return
End
};
EvtScript N(EVS_ToadHouse_GetInBed) = {
Exec(N(EVS_PlayRestingSong))
Call(SetPlayerSpeed, Float(3.5))
Call(PlayerMoveTo, 322, -178, 0)
Thread
Wait(15)
Call(N(ToadHouse_CamSetFOV), 0, 40)
Call(SetCamType, CAM_DEFAULT, CAM_CONTROL_FIXED_POS_AND_ORIENTATION, FALSE)
Call(SetCamPitch, CAM_DEFAULT, 54, -27)
Call(SetCamDistance, CAM_DEFAULT, 135)
Call(SetCamPosA, CAM_DEFAULT, 406, -130)
Call(SetCamPosB, CAM_DEFAULT, 361, -190)
Call(SetCamPosC, CAM_DEFAULT, 0, -1)
Call(SetCamSpeed, CAM_DEFAULT, Float(90.0))
Call(PanToTarget, CAM_DEFAULT, 0, TRUE)
EndThread
Call(SetPlayerSpeed, Float(3.0))
Call(PlayerMoveTo, 361, -194, 0)
Call(PlayerMoveTo, 370, -257, 0)
Call(InterpPlayerYaw, 229, 1)
Call(HidePlayerShadow, TRUE)
Call(SetPlayerAnimation, ANIM_Mario1_Idle)
Call(SetPlayerImgFXFlags, IMGFX_FLAG_800)
Call(UpdatePlayerImgFX, ANIM_Mario1_Idle, IMGFX_SET_ANIM, IMGFX_ANIM_GET_IN_BED, 1, 1, 0)
Thread
Wait(60)
Call(SetPlayerAnimation, ANIM_MarioW2_SleepStanding)
EndThread
Wait(20)
Thread
Wait(81)
Call(N(ToadHouse_CamSetFOV), 0, 25)
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Call(UseSettingsFrom, CAM_DEFAULT, LVar0, LVar1, LVar2)
Wait(1)
Call(PanToTarget, CAM_DEFAULT, 0, FALSE)
EndThread
Return
End
};
EvtScript N(EVS_ToadHouse_ReturnFromRest) = {
Call(HidePlayerShadow, FALSE)
Call(UpdatePlayerImgFX, ANIM_Mario1_Idle, IMGFX_CLEAR, 0, 0, 0, 0)
Call(SetPlayerPos, 345, 0, -186)
Call(SetPlayerSpeed, Float(3.0))
Call(PlayerMoveTo, 291, -100, 0)
Exec(N(EVS_SetupMusic))
Return
End
};
EvtScript N(EVS_NpcInit_Toad) = {
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_ToadHouseKeeper)))
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_01) = {
ExecWait(EVS_ShopOwnerDialog)
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_01) = {
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_01)))
Return
End
};
EvtScript N(EVS_NpcInteract_VillageLeader) = {
ExecWait(N(EVS_GetRescuedYoshiCount))
Switch(LVar0)
CaseLt(1)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Shout, ANIM_VillageLeader_IdleSad, 0, MSG_CH5_0099)
Set(GF_JAN03_AgreedToRescueChildren, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Shout, ANIM_VillageLeader_IdleSad, 0, MSG_CH5_009A)
EndIf
CaseLt(3)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Shout, ANIM_VillageLeader_IdleSad, 0, MSG_CH5_009B)
CaseLt(4)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Shout, ANIM_VillageLeader_IdleSad, 0, MSG_CH5_009C)
CaseLt(5)
Call(SpeakToPlayer, NPC_SELF, ANIM_VillageLeader_Shout, ANIM_VillageLeader_IdleSad, 0, MSG_CH5_009D)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_VillageLeader) = {
Loop(0)
Call(NpcMoveTo, NPC_SELF, -300, -70, 50)
Call(NpcMoveTo, NPC_SELF, -350, -70, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_VillageLeader) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(RemoveNpc, NPC_SELF)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SetNpcAnimation, NPC_SELF, ANIM_VillageLeader_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_VillageLeader)))
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_VillageLeader)))
CaseDefault
Call(RemoveNpc, NPC_SELF)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_02) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_005A)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
ExecWait(N(EVS_GetRescuedYoshiCount))
IfEq(LVar0, 0)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_CryTalk, ANIM_Yoshi_Green_Cry, 0, MSG_CH5_005B)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_CryTalk, ANIM_Yoshi_Green_Cry, 0, MSG_CH5_005C)
EndIf
Else
IfEq(GF_JAN11_SavedYoshi, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_CryTalk, ANIM_Yoshi_Green_Cry, 0, MSG_CH5_005D)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_005E)
EndIf
EndIf
CaseLe(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_005F)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_0060)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_0061)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Green_Talk, ANIM_Yoshi_Green_Idle, 0, MSG_CH5_0062)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_Yoshi_02) = {
Loop(0)
Call(NpcMoveTo, NPC_SELF, -430, -220, 50)
Call(NpcMoveTo, NPC_SELF, -340, -220, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_02) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN11_SavedYoshi, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_Yoshi_Green_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Yoshi_02)))
Else
Call(BindNpcIdle, NPC_SELF, 0)
EndIf
EndSwitch
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_02)))
Return
End
};
EvtScript N(EVS_NpcInteract_Yoshi_03) = {
IfGe(GB_StoryProgress, STORY_CH5_STAR_SPRIT_DEPARTED)
Call(N(CountFoodItems), LVar0)
IfNe(LVar0, 0)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_006C)
EVT_CHOOSE_CONSUMABLE_FROM(N(FoodItemList), 4)
IfLe(LVar0, 0)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_006E)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_006D)
EVT_GIVE_REWARD(ITEM_MELON)
EndIf
Return
EndIf
EndIf
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_0063)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
ExecWait(N(EVS_GetRescuedYoshiCount))
IfEq(LVar0, 0)
IfEq(GF_JAN03_AgreedToRescueChildren, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_CryTalk, ANIM_Yoshi_Yellow_Cry, 0, MSG_CH5_0064)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_CryTalk, ANIM_Yoshi_Yellow_Cry, 0, MSG_CH5_0065)
EndIf
Else
IfEq(GF_JAN07_SavedYoshi, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_CryTalk, ANIM_Yoshi_Yellow_Cry, 0, MSG_CH5_0066)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_0067)
EndIf
EndIf
CaseLe(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_0068)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_0069)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_006A)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Yoshi_Yellow_Talk, ANIM_Yoshi_Yellow_Idle, 0, MSG_CH5_006B)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcIdle_Yoshi_03) = {
Loop(0)
#if VERSION_JP
Call(NpcMoveTo, NPC_SELF, -100, -80, 50)
#else
Call(NpcMoveTo, NPC_SELF, -105, -20, 50)
#endif
Call(NpcMoveTo, NPC_SELF, -190, -80, 50)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Yoshi_03) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
IfEq(GF_JAN07_SavedYoshi, FALSE)
Call(SetNpcAnimation, NPC_SELF, ANIM_Yoshi_Yellow_Panic)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Yoshi_03)))
Else
Call(BindNpcIdle, NPC_SELF, 0)
EndIf
EndSwitch
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Yoshi_03)))
Return
End
};
EvtScript N(EVS_NpcIdle_YoshiKid_01) = {
Return
End
};
EvtScript N(EVS_NpcIdle_YoshiKid_04) = {
Return
End
};
EvtScript N(EVS_NpcInteract_YoshiKid_01) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Green_Talk, ANIM_YoshiKid_Green_Idle, 0, MSG_CH5_006F)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Green_Talk, ANIM_YoshiKid_Green_Idle, 0, MSG_CH5_0070)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Green_Talk, ANIM_YoshiKid_Green_Idle, 0, MSG_CH5_0071)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Green_Talk, ANIM_YoshiKid_Green_Idle, 0, MSG_CH5_0072)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Green_Talk, ANIM_YoshiKid_Green_Idle, 0, MSG_CH5_0073)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInteract_YoshiKid_02) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle, 0, MSG_CH5_0074)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle, 0, MSG_CH5_0075)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle, 0, MSG_CH5_0076)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle, 0, MSG_CH5_0077)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Red_Talk, ANIM_YoshiKid_Red_Idle, 0, MSG_CH5_0078)
EndSwitch
ExecWait(N(EVS_LetterPrompt_RedYoshiKid))
IfNe(LVarC, 0)
Return
EndIf
Return
End
};
EvtScript N(EVS_NpcInteract_YoshiKid_03) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Blue_Talk, ANIM_YoshiKid_Blue_Idle, 0, MSG_CH5_007D)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Blue_Talk, ANIM_YoshiKid_Blue_Idle, 0, MSG_CH5_007E)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Blue_Talk, ANIM_YoshiKid_Blue_Idle, 0, MSG_CH5_007F)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Blue_Talk, ANIM_YoshiKid_Blue_Idle, 0, MSG_CH5_0080)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Blue_Talk, ANIM_YoshiKid_Blue_Idle, 0, MSG_CH5_0081)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInteract_YoshiKid_04) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Yellow_Talk, ANIM_YoshiKid_Yellow_Idle, 0, MSG_CH5_0082)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Yellow_Talk, ANIM_YoshiKid_Yellow_Idle, 0, MSG_CH5_0083)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Yellow_Talk, ANIM_YoshiKid_Yellow_Idle, 0, MSG_CH5_0084)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Yellow_Talk, ANIM_YoshiKid_Yellow_Idle, 0, MSG_CH5_0085)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Yellow_Talk, ANIM_YoshiKid_Yellow_Idle, 0, MSG_CH5_0086)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInteract_YoshiKid_05) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Purple_Talk, ANIM_YoshiKid_Purple_Idle, 0, MSG_CH5_0087)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Purple_Talk, ANIM_YoshiKid_Purple_Idle, 0, MSG_CH5_0088)
CaseLt(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Purple_Talk, ANIM_YoshiKid_Purple_Idle, 0, MSG_CH5_0089)
CaseLt(STORY_CH6_FLOWER_GATE_OPEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Purple_Talk, ANIM_YoshiKid_Purple_Idle, 0, MSG_CH5_008A)
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_YoshiKid_Purple_Talk, ANIM_YoshiKid_Purple_Idle, 0, MSG_CH5_008B)
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_YoshiKid_01) = {
IfGe(GB_StoryProgress, STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN11_SavedYoshi, FALSE)
Call(RemoveNpc, NPC_SELF)
Return
Else
IfEq(GB_StoryProgress, STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SetNpcPos, NPC_SELF, -490, 0, -90)
Else
Call(SetNpcPos, NPC_SELF, -450, 0, -190)
EndIf
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_YoshiKid_01)))
EndIf
EndIf
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_YoshiKid_01)))
Return
End
};
EvtScript N(EVS_NpcInit_YoshiKid_02) = {
IfGe(GB_StoryProgress, STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN08_SavedYoshi, FALSE)
Call(RemoveNpc, NPC_SELF)
Return
EndIf
EndIf
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_YoshiKid_02)))
Return
End
};
EvtScript N(EVS_NpcInit_YoshiKid_03) = {
IfGe(GB_StoryProgress, STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN10_SavedYoshi, FALSE)
Call(RemoveNpc, NPC_SELF)
Return
EndIf
EndIf
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_YoshiKid_03)))
Return
End
};
EvtScript N(EVS_NpcInit_YoshiKid_04) = {
IfGe(GB_StoryProgress, STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN07_SavedYoshi, FALSE)
Call(RemoveNpc, NPC_SELF)
Return
Else
#if VERSION_JP
Call(SetNpcPos, NPC_SELF, -120, 0, -110)
#else
Call(SetNpcPos, NPC_SELF, -135, 0, -70)
#endif
Call(InterpNpcYaw, NPC_SELF, 270, 0)
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_YoshiKid_04)))
EndIf
EndIf
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_YoshiKid_04)))
Return
End
};
EvtScript N(EVS_NpcInit_YoshiKid_05) = {
IfGe(GB_StoryProgress, STORY_CH5_YOSHI_CHILDREN_ARE_MISSING)
IfEq(GF_JAN05_SavedYoshi, FALSE)
Call(RemoveNpc, NPC_SELF)
Return
EndIf
EndIf
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_YoshiKid_05)))
Return
End
};
EvtScript N(EVS_NpcInteract_Raven) = {
Call(GetSelfNpcID, LVar0)
Switch(LVar0)
CaseEq(NPC_Raven_01)
IfLt(GB_StoryProgress, STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_008C)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_008D)
EndIf
CaseEq(NPC_Raven_03)
IfLt(GB_StoryProgress, STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_008E)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_008F)
EndIf
CaseEq(NPC_Raven_04)
IfLt(GB_StoryProgress, STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_0090)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_0091)
EndIf
CaseEq(NPC_Raven_05)
IfLt(GB_StoryProgress, STORY_CH5_RAPHAEL_LEFT_NEST)
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_0092)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Raven_Talk, ANIM_Raven_Idle, 0, MSG_CH5_0093)
EndIf
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_Raven) = {
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Raven)))
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_RAPHAEL_LEFT_NEST)
CaseRange(STORY_CH5_ZIP_LINE_READY, STORY_CH5_OPENED_ESCAPE_ROUTE)
Call(GetSelfNpcID, LVar0)
IfEq(LVar0, 14)
Call(RemoveNpc, NPC_SELF)
EndIf
CaseGe(STORY_CH5_BEGAN_PEACH_MISSION)
CaseDefault
Call(RemoveNpc, NPC_SELF)
EndSwitch
Return
End
};
s32 N(VolcanoVaseList)[] = {
ITEM_VOLCANO_VASE,
-1
};
EvtScript N(EVS_NpcInteract_Kolorado) = {
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_ALL_YOSHI_CHILDREN_RESCUED)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0012)
ExecWait(N(EVS_LetterPrompt_Kolorado))
ExecWait(N(EVS_LetterReward_Kolorado))
CaseLt(STORY_CH5_GOT_JADE_RAVEN)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0013)
ExecWait(N(EVS_LetterPrompt_Kolorado))
ExecWait(N(EVS_LetterReward_Kolorado))
CaseLt(STORY_CH5_ZIP_LINE_READY)
IfEq(AF_JAN_06, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0014)
Set(AF_JAN_06, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0015)
EndIf
ExecWait(N(EVS_LetterPrompt_Kolorado))
ExecWait(N(EVS_LetterReward_Kolorado))
CaseEq(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(FindItem, ITEM_VOLCANO_VASE, LVar0)
IfEq(LVar0, -1)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0016)
ExecWait(N(EVS_LetterPrompt_Kolorado))
ExecWait(N(EVS_LetterReward_Kolorado))
Else
Call(AdjustCam, CAM_DEFAULT, Float(5.0), 0, 325, Float(20.0), Float(-7.5))
Set(LVar0, Ref(N(VolcanoVaseList)))
Set(LVar1, 15)
ExecWait(N(EVS_ChooseKeyItem))
Switch(LVar0)
CaseEq(-1)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0017)
ExecWait(N(EVS_LetterPrompt_Kolorado))
ExecWait(N(EVS_LetterReward_Kolorado))
CaseDefault
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0018)
Call(SetPlayerAnimation, ANIM_Mario1_NodYes)
Wait(20)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_0019)
Wait(10)
Call(SetNpcAnimation, NPC_SELF, ANIM_Kolorado_IdleSad)
Wait(15)
Call(SetNpcAnimation, NPC_SELF, ANIM_Kolorado_Idle)
Call(PlaySoundAtNpc, NPC_SELF, SOUND_EMOTE_IDEA, SOUND_SPACE_DEFAULT)
Call(ShowEmote, NPC_SELF, EMOTE_EXCLAMATION, 0, 20, EMOTER_NPC, 0, 0, 0, 0)
Wait(25)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_001A)
EVT_GIVE_REWARD(ITEM_MAGICAL_SEED4)
Set(GF_JAN03_Gift_MagicalSeed4, TRUE)
Wait(20)
Call(SetNpcFlagBits, NPC_SELF, NPC_FLAG_IGNORE_PLAYER_COLLISION, TRUE)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_001B)
Wait(10)
Call(SpeakToPlayer, NPC_SELF, ANIM_Kolorado_Talk, ANIM_Kolorado_Idle, 0, MSG_CH5_001C)
Call(SetNpcAnimation, NPC_SELF, ANIM_Kolorado_Walk)
Call(SetNpcSpeed, NPC_SELF, Float(4.0))
Call(NpcMoveTo, NPC_SELF, -465, -185, 0)
Call(NpcMoveTo, NPC_SELF, -540, -70, 0)
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
Set(GB_StoryProgress, STORY_CH5_TRADED_VASE_FOR_SEED)
EndSwitch
Call(ResetCam, CAM_DEFAULT, Float(5.0))
EndIf
EndSwitch
Return
End
};
EvtScript N(EVS_NpcInit_Kolorado) = {
Set(LVar0, 0)
Switch(GB_StoryProgress)
CaseLt(STORY_CH5_ZIP_LINE_READY)
Set(LVar0, 1)
CaseEq(STORY_CH5_STAR_SPRIT_DEPARTED)
Call(SetNpcPos, NPC_SELF, -433, 0, -205)
Call(SetEnemyFlagBits, NPC_SELF, ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER, FALSE)
Set(LVar0, 1)
EndSwitch
IfEq(LVar0, 1)
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Kolorado)))
Else
Call(SetNpcPos, NPC_SELF, NPC_DISPOSE_LOCATION)
EndIf
Return
End
};
EvtScript N(EVS_NpcInteract_Sushie) = {
IfEq(AF_JAN_07, FALSE)
Call(SpeakToPlayer, NPC_SELF, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 0, MSG_CH5_0058)
Set(AF_JAN_07, TRUE)
Else
Call(SpeakToPlayer, NPC_SELF, ANIM_WorldSushie_Talk, ANIM_WorldSushie_Idle, 0, MSG_CH5_0059)
EndIf
Return
End
};
EvtScript N(EVS_NpcIdle_Sushie) = {
Call(GetNpcPos, NPC_SELF, LVar0, LVar1, LVar2)
Call(SetNpcJumpscale, NPC_SELF, 1)
Loop(0)
Call(SetNpcAnimation, NPC_SELF, ANIM_WorldSushie_Talk)
Wait(30)
Call(SetNpcAnimation, NPC_SELF, ANIM_WorldSushie_Run)
Wait(15)
EndLoop
Return
End
};
EvtScript N(EVS_NpcInit_Sushie) = {
Call(BindNpcIdle, NPC_SELF, Ref(N(EVS_NpcIdle_Sushie)))
Call(BindNpcInteract, NPC_SELF, Ref(N(EVS_NpcInteract_Sushie)))
Return
End
};
AnimID N(ExtraAnims_VillageLeader)[] = {
ANIM_VillageLeader_Idle,
ANIM_VillageLeader_IdleSad,
ANIM_VillageLeader_Walk,
ANIM_VillageLeader_Panic,
ANIM_VillageLeader_Run,
ANIM_VillageLeader_Talk,
ANIM_VillageLeader_Shout,
ANIM_VillageLeader_Celebrate,
ANIM_VillageLeader_CrossArms,
ANIM_LIST_END
};
NpcData N(NpcData_VillageLeader) = {
.id = NPC_VillageLeader,
.pos = { -300.0f, 0.0f, -70.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_VillageLeader),
.settings = &N(NpcSettings_Yoshi),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_LEADER_ANIMS,
.extraAnimations = N(ExtraAnims_VillageLeader),
.tattle = MSG_NpcTattle_VillageLeader,
};
AnimID N(ExtraAnims_Sushie)[] = {
ANIM_WorldSushie_Idle,
ANIM_WorldSushie_Run,
ANIM_WorldSushie_Talk,
ANIM_LIST_END
};
NpcData N(NpcData_Sushie) = {
.id = NPC_Sushie,
.pos = { -425.0f, 0.0f, -350.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Sushie),
.settings = &N(NpcSettings_Sushie),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = SUSHIE_ANIMS,
.extraAnimations = N(ExtraAnims_Sushie),
.tattle = MSG_NpcTattle_Sushie,
};
AnimID N(ExtraAnims_Kolorado)[] = {
ANIM_Kolorado_Idle,
ANIM_Kolorado_IdleSad,
ANIM_Kolorado_Walk,
ANIM_Kolorado_Talk,
ANIM_LIST_END
};
NpcData N(NpcData_Kolorado) = {
.id = NPC_Kolorado,
.pos = { -475.0f, 0.0f, -75.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Kolorado),
.settings = &N(NpcSettings_Kolorado),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = KOLORADO_ANIMS,
.extraAnimations = N(ExtraAnims_Kolorado),
.tattle = MSG_NpcTattle_Kolorado,
};
NpcData N(NpcData_Toad)[] = {
{
.id = NPC_Toad,
.pos = { 275.0f, 0.0f, -70.0f },
.yaw = 0,
.init = &N(EVS_NpcInit_Toad),
.settings = &N(NpcSettings_Toad_Stationary),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = TOAD_RED_ANIMS,
.tattle = MSG_NpcTattle_JAN_ToadHouseToad,
},
{
.id = NPC_Yoshi_01,
.pos = { 125.0f, 30.0f, -425.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_Yoshi_01),
.settings = &N(NpcSettings_Yoshi),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_BLUE_ANIMS,
.tattle = MSG_NpcTattle_JAN_ShopOwner,
},
{
.id = NPC_Yoshi_02,
.pos = { -350.0f, 0.0f, -220.0f },
.yaw = 90,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 2,
.points = {
{ -375, 0, -220 },
{ -325, 0, -220 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_Yoshi_02),
.settings = &N(NpcSettings_Yoshi_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_GREEN_ANIMS,
.tattle = MSG_NpcTattle_GenericYoshi,
},
{
.id = NPC_Yoshi_03,
.pos = { -100.0f, 0.0f, -80.0f },
.yaw = 270,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 2,
.points = {
{ -100, 0, -20 },
{ -210, 0, -80 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_Yoshi_03),
.settings = &N(NpcSettings_Yoshi_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_YELLOW_ANIMS,
.tattle = MSG_NpcTattle_FoodLovingYoshi,
},
{
.id = NPC_YoshiKid_01,
.pos = { -450.0f, 0.0f, -160.0f },
.yaw = 90,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 5,
.points = {
{ -450, 0, -160 },
{ -378, 0, -81 },
{ -590, 0, -100 },
{ -464, 0, -46 },
{ -495, 0, -147 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_YoshiKid_01),
.settings = &N(NpcSettings_YoshiKid_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_KID_GREEN_ANIMS,
.tattle = MSG_NpcTattle_GreenYoshiKid,
},
{
.id = NPC_YoshiKid_02,
.pos = { -340.0f, 0.0f, -385.0f },
.yaw = 90,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 3,
.points = {
{ -340, 0, -385 },
{ -290, 0, -310 },
{ -360, 0, -310 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_YoshiKid_02),
.settings = &N(NpcSettings_YoshiKid_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_KID_RED_ANIMS,
.tattle = MSG_NpcTattle_RedYoshiKid,
},
{
.id = NPC_YoshiKid_03,
.pos = { -260.0f, 0.0f, -220.0f },
.yaw = 270,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 3,
.points = {
{ -260, 0, -220 },
{ -270, 0, -220 },
{ -260, 0, -230 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_YoshiKid_03),
.settings = &N(NpcSettings_YoshiKid_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_KID_BLUE_ANIMS,
.tattle = MSG_NpcTattle_BlueYoshiKid,
},
{
.id = NPC_YoshiKid_04,
.pos = { -460.0f, 0.0f, 150.0f },
.yaw = 90,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 3,
.points = {
{ -460, 0, 150 },
{ -450, 0, 150 },
{ -460, 0, 160 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_YoshiKid_04),
.settings = &N(NpcSettings_YoshiKid_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_KID_YELLOW_ANIMS,
.tattle = MSG_NpcTattle_YellowYoshiKid,
},
{
.id = NPC_YoshiKid_05,
.pos = { -320.0f, 0.0f, 80.0f },
.yaw = 270,
.territory = {
.patrol = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.numPoints = 3,
.points = {
{ -320, 0, 80 },
{ -330, 0, 80 },
{ -320, 0, 90 },
},
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 0 },
}
},
.init = &N(EVS_NpcInit_YoshiKid_05),
.settings = &N(NpcSettings_YoshiKid_Patrol),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = YOSHI_KID_PURPLE_ANIMS,
.tattle = MSG_NpcTattle_PurpleYoshiKid,
},
};
AnimID N(ExtraAnims_Raven)[] = {
ANIM_Raven_Still,
ANIM_Raven_Idle,
ANIM_Raven_Talk,
ANIM_LIST_END
};
NpcData N(NpcData_Ravens)[] = {
{
.id = NPC_Raven_01,
.pos = { -650.0f, 374.0f, -150.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Raven),
.settings = &N(NpcSettings_Raven),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = RAVEN_ANIMS,
.extraAnimations = N(ExtraAnims_Raven),
.tattle = MSG_NpcTattle_RavenA,
},
{
.id = NPC_Raven_02,
.pos = { -645.0f, 457.0f, -255.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Raven),
.settings = &N(NpcSettings_Raven),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = RAVEN_ANIMS,
#if VERSION_JP
.tattle = MSG_NpcTattle_0121,
#endif
},
{
.id = NPC_Raven_03,
.pos = { -570.0f, 374.0f, -300.0f },
.yaw = 90,
.init = &N(EVS_NpcInit_Raven),
.settings = &N(NpcSettings_Raven),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = RAVEN_ANIMS,
.tattle = MSG_NpcTattle_RavenC,
},
{
.id = NPC_Raven_04,
.pos = { -500.0f, 374.0f, -285.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_Raven),
.settings = &N(NpcSettings_Raven),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = RAVEN_ANIMS,
.tattle = MSG_NpcTattle_RavenD,
},
{
.id = NPC_Raven_05,
.pos = { -450.0f, 374.0f, -175.0f },
.yaw = 270,
.init = &N(EVS_NpcInit_Raven),
.settings = &N(NpcSettings_Raven),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST | ENEMY_FLAG_DO_NOT_AUTO_FACE_PLAYER,
.drops = NO_DROPS,
.animations = RAVEN_ANIMS,
.tattle = MSG_NpcTattle_RavenE,
},
};
NpcData N(NpcData_ChuckQuizmo) = {
.id = NPC_ChuckQuizmo,
.pos = { 300.0f, 0.0f, 400.0f },
.yaw = 90,
.initVarCount = 1,
.initVar = { .bytes = { 0, QUIZ_AREA_JAN, QUIZ_COUNT_JAN, QUIZ_MAP_JAN_03 }},
.settings = &N(NpcSettings_ChuckQuizmo),
.flags = COMMON_PASSIVE_FLAGS | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = NO_DROPS,
.animations = QUIZMO_ANIMS,
.tattle = MSG_NpcTattle_ChuckQuizmo,
};
NpcGroupList N(CrisisNPCs) = {
NPC_GROUP(N(NpcData_VillageLeader)),
NPC_GROUP(N(NpcData_Sushie)),
NPC_GROUP(N(NpcData_Ravens)),
NPC_GROUP(N(NpcData_Toad)),
{}
};
NpcGroupList N(ChapterNPCs) = {
NPC_GROUP(N(NpcData_VillageLeader)),
NPC_GROUP(N(NpcData_Kolorado)),
NPC_GROUP(N(NpcData_Ravens)),
NPC_GROUP(N(NpcData_Toad)),
{}
};
NpcGroupList N(DefaultNPCs) = {
NPC_GROUP(N(NpcData_VillageLeader)),
NPC_GROUP(N(NpcData_Ravens)),
NPC_GROUP(N(NpcData_Toad)),
{}
};
NpcGroupList N(AfterNPCs) = {
NPC_GROUP(N(NpcData_ChuckQuizmo)),
NPC_GROUP(N(NpcData_Ravens)),
NPC_GROUP(N(NpcData_Toad)),
{}
};
| 0 | 0.945428 | 1 | 0.945428 | game-dev | MEDIA | 0.983715 | game-dev | 0.903648 | 1 | 0.903648 |
Reisyukaku/SVScripts | 3,281 | references/main/lua_split/C2F1067C9535CA530.lua | L55_1 = _ENV
L56_1 = "C2F1067C9535CA530"
L57_1 = _hx_e
L57_1 = L57_1()
L55_1[L56_1] = L57_1
_ENV["C2F1067C9535CA530"]["new"] = function(A0_2)
local L1_2, L2_2, L3_2, L4_2
L1_2 = lua_helper_new
L2_2 = C2F1067C9535CA530
L2_2 = L2_2.prototype
L3_2 = 3
L4_2 = 10
L1_2 = L1_2(L2_2, L3_2, L4_2)
L2_2 = C2F1067C9535CA530
L2_2 = L2_2.super
L3_2 = L1_2
L4_2 = A0_2
L2_2(L3_2, L4_2)
return L1_2
end
_ENV["C2F1067C9535CA530"]["super"] = function(A0_2, A1_2)
local L2_2, L3_2, L4_2
A0_2[3] = nil
A0_2[2] = nil
L2_2 = CDC3F92928A2194E6
L2_2 = L2_2.super
L3_2 = A0_2
L4_2 = A1_2
L2_2(L3_2, L4_2)
end
L68_1 = "C2F1067C9535CA530"
L69_1 = _ENV["C2F1067C9535CA530"]
L25_1[L68_1] = L69_1
L68_1 = _ENV["C2F1067C9535CA530"]
L69_1 = "__name__"
L70_1 = "C2F1067C9535CA530"
L68_1[L69_1] = L70_1
L68_1 = _ENV["C2F1067C9535CA530"]
L69_1 = "prototype"
L70_1 = _hx_e
L70_1 = L70_1()
L68_1[L69_1] = L70_1
_ENV["C2F1067C9535CA530"]["prototype"]["F7C68FEDB79AB6396"] = function(A0_2, A1_2)
local L2_2, L3_2, L4_2, L5_2, L6_2
L2_2 = c69ACCC6F
L2_2 = L2_2.f3F98EEAD
L3_2 = A0_2[1]
L2_2 = L2_2(L3_2)
A0_2[2] = L2_2
L2_2 = cECF00344
L2_2 = L2_2.fEECE6995
L3_2 = A0_2[1]
L2_2 = L2_2(L3_2)
A0_2[3] = L2_2
function L2_2()
local L0_3, L1_3
L0_3 = nil
L1_3 = c93450143
L1_3 = L1_3.f4F92E4A5
L1_3 = L1_3()
if 50 == L1_3 then
L0_3 = 0
else
L0_3 = 1
end
return L0_3
end
L2_2 = L2_2()
L3_2 = A0_2[3]
L4_2 = L3_2
L3_2 = L3_2.fEAD9FB7D
L5_2 = "L_keep_00/ptn_version"
L6_2 = L2_2
L3_2(L4_2, L5_2, L6_2)
L3_2 = A0_2[3]
L4_2 = L3_2
L3_2 = L3_2.fB4E9D030
L5_2 = "L_keep_00/keep"
L3_2(L4_2, L5_2)
L4_2 = A0_2
L3_2 = A0_2.F1BB2C5F716B25F79
L5_2 = 0
L3_2(L4_2, L5_2)
end
_ENV["C2F1067C9535CA530"]["prototype"]["FE94F3E13286232CF"] = function(A0_2, A1_2)
local L2_2, L3_2, L4_2
L2_2 = A0_2[3]
L3_2 = L2_2
L2_2 = L2_2.fF8C77C75
L4_2 = "L_keep_00/keep"
L2_2 = L2_2(L3_2, L4_2)
if L2_2 then
L2_2 = A0_2[3]
L3_2 = L2_2
L2_2 = L2_2.fB4E9D030
L4_2 = "L_keep_00/keep"
L2_2(L3_2, L4_2)
end
end
_ENV["C2F1067C9535CA530"]["prototype"]["F20A40E2F8B95D5F6"] = function(A0_2, A1_2)
end
_ENV["C2F1067C9535CA530"]["prototype"]["F1C2AA00ADAC52EC5"] = function(A0_2)
local L1_2
end
_ENV["C2F1067C9535CA530"]["prototype"]["F1BB2C5F716B25F79"] = function(A0_2, A1_2)
local L2_2, L3_2, L4_2, L5_2, L6_2, L7_2, L8_2
L2_2 = ""
if 0 == A1_2 then
L2_2 = "pokepicnic_cooking_19_01"
elseif 1 == A1_2 then
L2_2 = "pokepicnic_cooking_19_02"
end
L3_2 = c8C3BF576
L3_2 = L3_2.f316077B2
L4_2 = A0_2[1]
L5_2 = "L_header_title_00/T_title_00"
L6_2 = c8C3BF576
L6_2 = L6_2.fC8CEF9EF
L7_2 = "pokepicnic_cooking"
L8_2 = L2_2
L6_2, L7_2, L8_2 = L6_2(L7_2, L8_2)
L3_2(L4_2, L5_2, L6_2, L7_2, L8_2)
end
_ENV["C2F1067C9535CA530"]["prototype"]["F0B860A1409D97905"] = function(A0_2)
local L1_2, L2_2, L3_2
L1_2 = A0_2[3]
L2_2 = L1_2
L1_2 = L1_2.fB4E9D030
L3_2 = "f_out"
L1_2(L2_2, L3_2)
end
L68_1 = _ENV["C2F1067C9535CA530"]["prototype"]
L69_1 = _ENV["C2F1067C9535CA530"]
L68_1.__class__ = L69_1
L68_1 = _ENV["C2F1067C9535CA530"]
L69_1 = "__super__"
L69_1 = _ENV["C2F1067C9535CA530"]["prototype"]
L70_1 = {}
L71_1 = "__index"
| 0 | 0.56292 | 1 | 0.56292 | game-dev | MEDIA | 0.297549 | game-dev | 0.62312 | 1 | 0.62312 |
Minestom/VanillaReimplementation | 1,834 | instance-meta/src/main/java/net/minestom/vanilla/instancemeta/InstanceMetaFeature.java | package net.minestom.vanilla.instancemeta;
import net.kyori.adventure.key.Key;
import net.minestom.server.event.instance.InstanceTickEvent;
import net.minestom.server.instance.Instance;
import net.minestom.vanilla.VanillaReimplementation;
import net.minestom.vanilla.instancemeta.tickets.TicketManager;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
public class InstanceMetaFeature implements VanillaReimplementation.Feature {
@Override
public void hook(@NotNull HookContext context) {
new Logic().hook(context.vri());
}
@Override
public @NotNull Key key() {
return Key.key("vri:instancemeta");
}
private static class Logic {
private final @NotNull Map<Instance, TicketManager> instance2TicketManager =
Collections.synchronizedMap(new WeakHashMap<>());
private Logic() {
}
private void hook(@NotNull VanillaReimplementation vri) {
vri.process().eventHandler().addListener(InstanceTickEvent.class, event -> tickInstance(event.getInstance()));
}
// Process all future tickets
private void tickInstance(@NotNull Instance instance) {
TicketManager ticketManager = instance2TicketManager.computeIfAbsent(instance, ignored -> new TicketManager());
List<TicketManager.Ticket> waitingForceLoads = instance.getTag(TicketManager.WAITING_TICKETS_TAG);
if (waitingForceLoads == null) {
return;
}
for (TicketManager.Ticket waitingForceLoad : waitingForceLoads) {
ticketManager.addTicket(waitingForceLoad);
}
instance.setTag(TicketManager.WAITING_TICKETS_TAG, List.of());
}
}
}
| 0 | 0.805057 | 1 | 0.805057 | game-dev | MEDIA | 0.36162 | game-dev | 0.894659 | 1 | 0.894659 |
AresClient/ares | 9,013 | ares-fabric-1.16/src/main/java/dev/tigr/ares/fabric/impl/modules/combat/AutoTrap.java | package dev.tigr.ares.fabric.impl.modules.combat;
import dev.tigr.ares.core.feature.module.Category;
import dev.tigr.ares.core.feature.module.Module;
import dev.tigr.ares.core.setting.Setting;
import dev.tigr.ares.core.setting.settings.BooleanSetting;
import dev.tigr.ares.core.setting.settings.EnumSetting;
import dev.tigr.ares.core.setting.settings.numerical.DoubleSetting;
import dev.tigr.ares.core.setting.settings.numerical.IntegerSetting;
import dev.tigr.ares.core.util.Priorities;
import dev.tigr.ares.core.util.Timer;
import dev.tigr.ares.fabric.utils.InventoryUtils;
import dev.tigr.ares.fabric.utils.entity.PlayerUtils;
import dev.tigr.ares.fabric.utils.entity.SelfUtils;
import net.minecraft.block.Blocks;
import net.minecraft.block.ShapeContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
/**
* @author Tigermouthbear
*/
@Module.Info(name = "AutoTrap", description = "Automatically trap people in holes", category = Category.COMBAT)
public class AutoTrap extends Module {
private final Setting<Mode> mode = register(new EnumSetting<>("Mode", Mode.FULL));
private final Setting<Boolean> rotate = register(new BooleanSetting("Rotate", true));
private final Setting<Boolean> packetPlace = register(new BooleanSetting("Packet Place", true));
private final Setting<Double> range = register(new DoubleSetting("Range", 5, 0, 8));
private final Setting<Integer> delay = register(new IntegerSetting("Delay", 2, 0, 10));
private final Setting<Integer> blocksPerTick = register(new IntegerSetting("Blocks Per Tick", 8, 0, 20)).setVisibility(() -> delay.getValue() == 0);
private final Timer delayTimer = new Timer();
int key = Priorities.Rotation.AUTO_TRAP;
int blocksPlaced = 0;
@Override
public void onDisable() {
if(rotate.getValue()) ROTATIONS.setCompletedAction(key, true);
}
@Override
public void onTick() {
//Flag rotations off if there are no placements needing completion
boolean flagCurrent = true;
for(PlayerEntity player: SelfUtils.getPlayersInRadius(range.getValue()))
if(isPlayerValidTarget(player))
for(BlockPos pos: getPos(player))
if(isPosInRange(pos)
&& MC.world.getBlockState(pos).getMaterial().isReplaceable()
&& MC.world.canPlace(Blocks.OBSIDIAN.getDefaultState(), pos, ShapeContext.absent()))
flagCurrent = false;
if(ROTATIONS.isKeyCurrent(key) && flagCurrent) ROTATIONS.setCompletedAction(key, true);
int oldSlot = MC.player.inventory.selectedSlot;
if(delayTimer.passedTicks(delay.getValue())) {
for(PlayerEntity player: SelfUtils.getPlayersInRadius(range.getValue())) {
if(isPlayerValidTarget(player)) {
int newSlot = InventoryUtils.findBlockInHotbar(Blocks.OBSIDIAN);
if(delay.getValue() == 0) {
if(newSlot == -1) return;
else HOTBAR_TRACKER.setSlot(newSlot, packetPlace.getValue(), oldSlot);
}
for(BlockPos pos: getPos(player)) {
if(MC.world.getBlockState(pos).getMaterial().isReplaceable() && isPosInRange(pos)) {
if(MC.world.getOtherEntities(null, new Box(pos)).isEmpty()) {
//place block
if(delay.getValue() != 0) {
if(newSlot == -1) return;
else HOTBAR_TRACKER.setSlot(newSlot, packetPlace.getValue(), oldSlot);
}
SelfUtils.placeBlockMainHand(packetPlace.getValue(), -1, rotate.getValue(), key, key, delay.getValue() == 0, false, pos);
if(delay.getValue() != 0) HOTBAR_TRACKER.reset();
delayTimer.reset();
if(delay.getValue() == 0) {
blocksPlaced++;
if(blocksPlaced < blocksPerTick.getValue()) continue;
else {
HOTBAR_TRACKER.reset();
blocksPlaced = 0;
return;
}
}
return;
}
}
}
}
}
}
HOTBAR_TRACKER.reset();
}
private boolean isPosInRange(BlockPos pos) {
return MC.player.squaredDistanceTo(Vec3d.ofCenter(pos)) <= range.getValue() * range.getValue();
}
private boolean isPlayerValidTarget(PlayerEntity player) {
return (MC.player.squaredDistanceTo(player) <= range.getValue() * range.getValue()) && PlayerUtils.isValidTarget(player, range.getValue());
}
private BlockPos[] getPos(Entity player) {
BlockPos playerPos = new BlockPos(player.getPos());
BlockPos[] blocks;
if(mode.getValue() == Mode.FULL) {
blocks = new BlockPos[]{
playerPos.add(1, -1, 0),
playerPos.add(1, 0, 0),
playerPos.add(1, 1, 0),
playerPos.add(-1, -1, 0),
playerPos.add(-1, 0, 0),
playerPos.add(-1, 1, 0),
playerPos.add(0, -1, 1),
playerPos.add(0, 0, 1),
playerPos.add(0, 1, 1),
playerPos.add(0, -1, -1),
playerPos.add(0, 0, -1),
playerPos.add(0, 1, -1),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 0)
};
} else if(mode.getValue() == Mode.CRYSTALAIR) {
blocks = new BlockPos[]{
playerPos.add(0, 1, 1),
playerPos.add(0, 1, -1),
playerPos.add(1, 1, 0),
playerPos.add(-1, 1, 0),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 0)
};
} else if(mode.getValue() == Mode.CRYSTALTOP) {
blocks = new BlockPos[]{
playerPos.add(1, -1, 0),
playerPos.add(1, 0, 0),
playerPos.add(1, 1, 0),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 0),
playerPos.add(-1, 2, 0),
playerPos.add(0, 2, 1),
playerPos.add(0, 2, -1),
playerPos.add(-1, 1, 0),
playerPos.add(0, 1, 1),
playerPos.add(0, 1, -1),
};
} else if(mode.getValue() == Mode.TOPONLY) {
blocks = new BlockPos[]{
playerPos.add(1, -1, 0),
playerPos.add(1, 0, 0),
playerPos.add(1, 1, 0),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 0)
};
} else if(mode.getValue() == Mode.TOPAIR) {
blocks = new BlockPos[]{
playerPos.add(0, 2, 0)
};
} else if(mode.getValue() == Mode.TOP3x3) {
blocks = new BlockPos[]{
playerPos.add(0, 2, 0),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 1),
playerPos.add(-1, 2, 0),
playerPos.add(0, 2, -1),
playerPos.add(1, 2, 1),
playerPos.add(1, 2, -1),
playerPos.add(-1, 2, -1),
playerPos.add(-1, 2, 1)
};
} else {
blocks = new BlockPos[]{
playerPos.add(1, -1, 1),
playerPos.add(1, 0, 1),
playerPos.add(1, 1, 1),
playerPos.add(1, -1, -1),
playerPos.add(1, 0, -1),
playerPos.add(1, 1, -1),
playerPos.add(-1, -1, 1),
playerPos.add(-1, 0, 1),
playerPos.add(-1, 1, 1),
playerPos.add(-1, -1, -1),
playerPos.add(-1, 0, -1),
playerPos.add(-1, 1, -1),
playerPos.add(0, 1, 1),
playerPos.add(0, 1, -1),
playerPos.add(1, 1, 0),
playerPos.add(-1, 1, 0),
playerPos.add(1, 2, 0),
playerPos.add(0, 2, 0)
};
}
return blocks;
}
enum Mode { FULL, CRYSTALAIR, CRYSTALTOP, CRYSTALFULL, TOPONLY, TOPAIR, TOP3x3 }
}
| 0 | 0.843952 | 1 | 0.843952 | game-dev | MEDIA | 0.965916 | game-dev | 0.967614 | 1 | 0.967614 |
TeamTwilight/twilightforest-fabric | 4,427 | src/main/java/twilightforest/events/MiscEvents.java | package twilightforest.events;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal;
import net.minecraft.world.entity.ai.goal.target.NonTameRandomTargetGoal;
import net.minecraft.world.item.ItemStack;
import twilightforest.compat.trinkets.TrinketsCompat;
import twilightforest.entity.passive.Bighorn;
import twilightforest.entity.passive.DwarfRabbit;
import twilightforest.entity.passive.Squirrel;
import twilightforest.entity.passive.TinyBird;
import twilightforest.init.TFBlocks;
import twilightforest.init.TFEntities;
import twilightforest.network.CreateMovingCicadaSoundPacket;
import twilightforest.network.TFPacketHandler;
import javax.annotation.Nonnull;
public class MiscEvents {
public static void init() {
ServerEntityEvents.ENTITY_LOAD.register(MiscEvents::addPrey);
ServerEntityEvents.EQUIPMENT_CHANGE.register(MiscEvents::armorChanged);
}
public static void addPrey(Entity entity, ServerLevel world) {
if (entity instanceof Mob mob) {
EntityType<?> type = mob.getType();
if (type == EntityType.CAT) {
mob.targetSelector.addGoal(1, new NonTameRandomTargetGoal<>((TamableAnimal) mob, DwarfRabbit.class, false, null));
mob.targetSelector.addGoal(1, new NonTameRandomTargetGoal<>((TamableAnimal) mob, Squirrel.class, false, null));
mob.targetSelector.addGoal(1, new NonTameRandomTargetGoal<>((TamableAnimal) mob, TinyBird.class, false, null));
} else if (type == EntityType.OCELOT) {
mob.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(mob, DwarfRabbit.class, false));
mob.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(mob, Squirrel.class, false));
mob.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(mob, TinyBird.class, false));
} else if (type == EntityType.FOX) {
mob.targetSelector.addGoal(6, new NearestAttackableTargetGoal<>(mob, DwarfRabbit.class, false));
mob.targetSelector.addGoal(6, new NearestAttackableTargetGoal<>(mob, Squirrel.class, false));
} else if (type == EntityType.WOLF) {
mob.targetSelector.addGoal(7, new NonTameRandomTargetGoal<>((TamableAnimal) mob, DwarfRabbit.class, false, null));
mob.targetSelector.addGoal(7, new NonTameRandomTargetGoal<>((TamableAnimal) mob, Squirrel.class, false, null));
mob.targetSelector.addGoal(7, new NonTameRandomTargetGoal<>((TamableAnimal) mob, Bighorn.class, false, null));
}
}
}
public static void armorChanged(LivingEntity living, EquipmentSlot slot, @Nonnull ItemStack from, @Nonnull ItemStack to) {
// from what I can see, vanilla doesnt have a hook for this in the item class. So this will have to do.
// we only have to check equipping, when its unequipped the sound instance handles the rest
//if we have a cicada in our curios slot, dont try to run this
if (FabricLoader.getInstance().isModLoaded("trinkets")) {
if (TrinketsCompat.isCicadaEquipped(living)) {
return;
}
}
if (living != null && !living.level().isClientSide() && slot == EquipmentSlot.HEAD && to.is(TFBlocks.CICADA.get().asItem())) {
TFPacketHandler.CHANNEL.sendToClientsTrackingAndSelf(new CreateMovingCicadaSoundPacket(living.getId()), living);
}
}
@SubscribeEvent
public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {
Player player = event.getEntity();
ItemStack stack = player.getItemInHand(event.getHand());
if (stack.getItem() instanceof SpawnEggItem spawnEggItem && spawnEggItem.getType(stack.getTag()) == TFEntities.DEATH_TOME.get()) {
BlockPos pos = event.getPos();
BlockState state = event.getLevel().getBlockState(pos);
if (state.getBlock() instanceof LecternBlock && !state.getValue(BlockStateProperties.HAS_BOOK)) {
event.setCanceled(true);
event.getLevel().playSound(null, pos, SoundEvents.BOOK_PUT, SoundSource.BLOCKS, 1.0F, 1.0F);
if (event.getLevel() instanceof ServerLevel serverLevel) {
DeathTome tome = TFEntities.DEATH_TOME.get().spawn(serverLevel, stack, player, pos.below(), MobSpawnType.SPAWN_EGG, true, false);
if (tome != null) {
if (!player.getAbilities().instabuild) stack.shrink(1);
serverLevel.gameEvent(player, GameEvent.ENTITY_PLACE, pos);
tome.setOnLectern(true);
}
}
}
}
}
}
| 0 | 0.888246 | 1 | 0.888246 | game-dev | MEDIA | 0.99739 | game-dev | 0.939026 | 1 | 0.939026 |
Shadows-of-Fire/Apotheosis | 5,037 | src/main/java/dev/shadowsoffire/apotheosis/loot/LootRarity.java | package dev.shadowsoffire.apotheosis.loot;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.UnaryOperator;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.include.com.google.common.base.Preconditions;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import dev.shadowsoffire.apotheosis.tiers.GenContext;
import dev.shadowsoffire.apotheosis.tiers.TieredWeights;
import dev.shadowsoffire.apotheosis.tiers.TieredWeights.Weighted;
import dev.shadowsoffire.placebo.codec.CodecProvider;
import dev.shadowsoffire.placebo.reload.DynamicHolder;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
public record LootRarity(TextColor color, Holder<Item> material, TieredWeights weights, List<LootRule> rules, int sortIndex, RarityRenderData renderData) implements CodecProvider<LootRarity>, Weighted {
public static final Codec<LootRarity> LOAD_CODEC = RecordCodecBuilder.create(inst -> inst.group(
TextColor.CODEC.fieldOf("color").forGetter(LootRarity::color),
ItemStack.ITEM_NON_AIR_CODEC.fieldOf("material").forGetter(LootRarity::material),
TieredWeights.CODEC.fieldOf("weights").forGetter(Weighted::weights),
LootRule.CODEC.listOf().fieldOf("rules").forGetter(LootRarity::rules),
Codec.intRange(0, 2000).optionalFieldOf("sort_index", 1000).forGetter(LootRarity::sortIndex),
RarityRenderData.CODEC.optionalFieldOf("render_data", RarityRenderData.DEFAULT).forGetter(LootRarity::renderData))
.apply(inst, LootRarity::new));
/**
* Direct resolution codec. Only for use in other datapack objects which load after the {@link RarityRegistry}.
*/
public static final Codec<LootRarity> CODEC = Codec.lazyInitialized(() -> RarityRegistry.INSTANCE.holderCodec().xmap(DynamicHolder::get, RarityRegistry.INSTANCE::holder));
public Item getMaterial() {
return this.material.value();
}
public List<LootRule> getRules(LootCategory category) {
RarityOverride overrides = RarityOverrideRegistry.INSTANCE.getOverride(category);
if (overrides != null && overrides.hasRules(this)) {
return overrides.getRules(this);
}
return this.rules;
}
public MutableComponent toComponent() {
return Component.translatable("rarity." + RarityRegistry.INSTANCE.getKey(this)).withStyle(Style.EMPTY.withColor(this.color));
}
@Override
public String toString() {
return "LootRarity{" + RarityRegistry.INSTANCE.getKey(this) + "}";
}
@Override
public Codec<LootRarity> getCodec() {
return LOAD_CODEC;
}
@Nullable
public static LootRarity random(GenContext ctx) {
return RarityRegistry.INSTANCE.getRandomItem(ctx);
}
public static LootRarity random(GenContext ctx, Set<LootRarity> pool) {
return RarityRegistry.INSTANCE.getRandomItem(ctx, pool);
}
public static LootRarity randomFromHolders(GenContext ctx, Set<DynamicHolder<LootRarity>> pool) {
return RarityRegistry.INSTANCE.getRandomItemFromHolders(ctx, pool);
}
public static <T> Codec<Map<LootRarity, T>> mapCodec(Codec<T> codec) {
return Codec.unboundedMap(LootRarity.CODEC, codec);
}
public static Builder builder(TextColor color, Holder<Item> material) {
return new Builder(color, material);
}
public static class Builder {
private final TextColor color;
private final Holder<Item> material;
private TieredWeights weights;
private final List<LootRule> rules = new ArrayList<>();
private int index = 1000;
private RarityRenderData renderData = RarityRenderData.DEFAULT;
public Builder(TextColor color, Holder<Item> material) {
this.color = color;
this.material = material;
}
public Builder weights(TieredWeights.Builder builder) {
this.weights = builder.build();
return this;
}
public Builder rule(LootRule rule) {
this.rules.add(rule);
return this;
}
public Builder sortIndex(int index) {
this.index = index;
return this;
}
public Builder renderData(UnaryOperator<RarityRenderData.Builder> config) {
this.renderData = config.apply(new RarityRenderData.Builder()).build();
return this;
}
public LootRarity build() {
Preconditions.checkNotNull(this.weights);
Preconditions.checkArgument(this.rules.size() > 0);
return new LootRarity(this.color, this.material, this.weights, this.rules, this.index, this.renderData);
}
}
}
| 0 | 0.729357 | 1 | 0.729357 | game-dev | MEDIA | 0.991071 | game-dev | 0.968063 | 1 | 0.968063 |
fuyouawa/MMORPG | 2,369 | MMORPG/Assets/Scripts/Game/Entity/Item/ItemController.cs | using MMORPG.Game;
using QFramework;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.GlobalIllumination;
using LightType = UnityEngine.LightType;
public class ItemController : MonoBehaviour, IController
{
public EntityView EntityView;
private static Dictionary<string, GameObject> _essenceDict;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
if (_essenceDict == null)
{
_essenceDict = new();
_essenceDict["普通"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemWhiteEssence");
_essenceDict["非凡"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemGreenEssence");
_essenceDict["稀有"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemBlueEssence");
_essenceDict["史诗"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemPurpleEssence");
_essenceDict["传说"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemOrangeEssence");
_essenceDict["传说"] = Resources.Load<GameObject>("Prefabs/Effect/Essence/ItemRedEssence");
}
var pos = transform.position;
pos.y = 20;
transform.position = CalculateGroundPosition(pos, LayerMask.NameToLayer("Terrain"));
// 找到物品品质
var dataManagerSystem = this.GetSystem<IDataManagerSystem>();
var itemDefine = dataManagerSystem.GetUnitItemDefine(EntityView.UnitDefine.ID);
var essence = Instantiate(_essenceDict[itemDefine.Quality], transform);
essence.transform.localScale = new Vector3(2, 2, 2);
//Light pointLight = gameObject.AddComponent<Light>();
//pointLight.type = LightType.Point;
//pointLight.color = Color.white;
//pointLight.intensity = 1f;
//pointLight.range = 3f;
//pointLight.enabled = true;
}
// Update is called once per frame
void Update()
{
}
public Vector3 CalculateGroundPosition(Vector3 position, int layer)
{
int layerMask = 1 << layer;
if (Physics.Raycast(position, Vector3.down, out var hit, Mathf.Infinity, layerMask))
{
return hit.point;
}
return position;
}
public IArchitecture GetArchitecture()
{
return GameApp.Interface;
}
}
| 0 | 0.682802 | 1 | 0.682802 | game-dev | MEDIA | 0.959381 | game-dev | 0.7965 | 1 | 0.7965 |
DeanRoddey/CIDLib | 148,996 | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_NetClasses.cpp | //
// FILE NAME: CIDMacroEng_NetClasses.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/17/2005
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements a set of derivatives of the class info and class
// value classes, which implement the macro level HTTP and URL classes.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDMacroEng_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TMEngDataSrcVal,TMEngClassVal)
RTTIDecls(TMEngDataSrcInfo,TMEngClassInfo)
RTTIDecls(TMEngHTTPClientVal,TMEngClassVal)
RTTIDecls(TMEngHTTPClientInfo,TMEngClassInfo)
RTTIDecls(TMEngURLVal,TMEngClassVal)
RTTIDecls(TMEngURLInfo,TMEngClassInfo)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace
{
namespace CIDMacroEng_NetClasses
{
// -----------------------------------------------------------------------
// The names for the types that we support here. Each derivative has to
// be able to return strings that contain its name and full name.
// -----------------------------------------------------------------------
const TString strDataSrc(L"DataSrc");
const TString strDataSrcClassPath(L"MEng.System.Runtime.DataSrc");
const TString strHTTPClient(L"HTTPClient");
const TString strHTTPClientClassPath(L"MEng.System.Runtime.HTTPClient");
const TString strURL(L"URL");
const TString strURLClassPath(L"MEng.System.Runtime.URL");
const TString strURLProtosClassPath(L"MEng.System.Runtime.URL.URLProtos");
}
}
// ---------------------------------------------------------------------------
// CLASS: TMEngDataSrcVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngDataSrcVal: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngDataSrcVal::TMEngDataSrcVal( const TString& strName
, const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst) :
TMEngClassVal(strName, c2Id, eConst)
, m_pcdsSrc(nullptr)
{
}
TMEngDataSrcVal::~TMEngDataSrcVal()
{
try
{
delete m_pcdsSrc;
}
catch(...)
{
}
m_pcdsSrc = nullptr;
}
// ---------------------------------------------------------------------------
// TMEngDataSrcVal: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngDataSrcVal::bDbgFormat( TTextOutStream& strmTarget
, const TMEngClassInfo& meciThis
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices eRadix
, const TCIDMacroEngine& meOwner) const
{
if (eFormat == tCIDMacroEng::EDbgFmts::Long)
{
return kCIDLib::True;
}
return kCIDLib::False;
}
// ---------------------------------------------------------------------------
// TMEngDataSrcVal: Public, non-virtual methods
// ---------------------------------------------------------------------------
// Return true if we hae a source and it's connected
tCIDLib::TBoolean TMEngDataSrcVal::bConnected() const
{
return (m_pcdsSrc && m_pcdsSrc->bIsConnected());
}
// Return true if our data source object is already set up
tCIDLib::TBoolean TMEngDataSrcVal::bReady() const
{
return (m_pcdsSrc != nullptr);
}
TCIDDataSrc& TMEngDataSrcVal::cdsValue()
{
CIDAssert(m_pcdsSrc != nullptr, L"Net data source is not set yet");
return *m_pcdsSrc;
}
const TCIDDataSrc& TMEngDataSrcVal::cdsValue() const
{
CIDAssert(m_pcdsSrc != nullptr, L"Net data source is not set yet");
return *m_pcdsSrc;
}
// If we have a source object, clean it up
tCIDLib::TVoid TMEngDataSrcVal::Close()
{
if (m_pcdsSrc)
{
// Terminate it first, to giveit a chance for a clean shutdown
try
{
m_pcdsSrc->Terminate(TTime::enctNowPlusSecs(5), kCIDLib::True);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
catch(...)
{
}
try
{
delete m_pcdsSrc;
}
catch(...)
{
}
m_pcdsSrc = nullptr;
}
}
tCIDLib::TVoid
TMEngDataSrcVal::SetSockTCP(const TIPEndPoint& ipepTar, const tCIDLib::TBoolean bSecure)
{
//
// If we have current stuff, clean it up. If it was already terminated this will
// just do nothing. We set the close parameter, though it doesn't really matter
// since we are going to delete this source anyway. At the CML level, we don't want
// to trust users to manage the connection state correctly. So we just create
// and destroy them.
//
if (m_pcdsSrc)
{
try
{
m_pcdsSrc->Terminate(TTime::enctNowPlusSecs(5), kCIDLib::True);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
catch(...)
{
}
}
try
{
delete m_pcdsSrc;
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
catch(...)
{
}
// Now clear the pointer until we manage to set a new one
m_pcdsSrc = nullptr;
TCIDDataSrc* pcdsNew = nullptr;
try
{
// Create ourselves a new source
if (bSecure)
{
//
// Create the socket in this case and directly and pass it to the
// secure channel data source, who will adopt it.
//
tCIDLib::TStrList colALPN;
pcdsNew = new TCIDSChanClDataSrc
(
L"CML Secure Channel Client"
, new TClientStreamSocket(tCIDSock::ESockProtos::TCP, ipepTar)
, tCIDLib::EAdoptOpts::Adopt
, TString::strEmpty()
, colALPN
, tCIDSChan::EConnOpts::None
, ipepTar.strHostName()
);
}
else
{
pcdsNew = new TCIDSockStreamDataSrc(ipepTar);
}
// Try to initialize it
pcdsNew->Initialize(TTime::enctNowPlusSecs(5));
// It worked, so store it
m_pcdsSrc = pcdsNew;
}
catch(TError& errToCatch)
{
// It failed so dclean it up and rethrow
try
{
delete pcdsNew;
}
catch(...)
{
}
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
}
// ---------------------------------------------------------------------------
// CLASS: TMEngDataSrcInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Public, static methods
// ---------------------------------------------------------------------------
const TString& TMEngDataSrcInfo::strPath()
{
return CIDMacroEng_NetClasses::strDataSrcClassPath;
}
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngDataSrcInfo::TMEngDataSrcInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
CIDMacroEng_NetClasses::strDataSrc
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2MethId_DataIsReady(kCIDMacroEng::c2BadId)
, m_c2MethId_Close(kCIDMacroEng::c2BadId)
, m_c2MethId_DefCtor(kCIDMacroEng::c2BadId)
, m_c2MethId_GetIsConnected(kCIDMacroEng::c2BadId)
, m_c2MethId_GetLine(kCIDMacroEng::c2BadId)
, m_c2MethId_ReadBytes(kCIDMacroEng::c2BadId)
, m_c2MethId_TCPSetup(kCIDMacroEng::c2BadId)
, m_c4ErrId_Already(kCIDLib::c4MaxCard)
, m_c4ErrId_Close(kCIDLib::c4MaxCard)
, m_c4ErrId_NotReady(kCIDLib::c4MaxCard)
, m_c4ErrId_Read(kCIDLib::c4MaxCard)
, m_c4ErrId_Setup(kCIDLib::c4MaxCard)
, m_c2TypeId_IPEndPoint(kCIDMacroEng::c2BadId)
, m_c2TypeId_TextXCoder(kCIDMacroEng::c2BadId)
, m_pmeciErrors(nullptr)
, m_pmeciLineRes(nullptr)
, m_pmeciSockProtos(nullptr)
{
// Force the import of non-intrinsic classes we reference
bAddClassImport(TMEngStreamSocketInfo::strPath());
bAddClassImport(TMEngTextXCoderInfo::strPath());
}
TMEngDataSrcInfo::~TMEngDataSrcInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngDataSrcInfo::Init(TCIDMacroEngine& meOwner)
{
//
// An enum to represent the exceptions that this class throws. Note
// that we just use the text in the C++ exception in some cases, so there
// is no text for the enum value for those.
//
{
m_pmeciErrors = new TMEngEnumInfo
(
meOwner, L"DataSrcErrors", strClassPath(), L"MEng.Enum", 5
);
m_c4ErrId_Already = m_pmeciErrors->c4AddEnumItem(L"Already", TString::strEmpty());
m_c4ErrId_Close = m_pmeciErrors->c4AddEnumItem(L"Close", TString::strEmpty());
m_c4ErrId_NotReady = m_pmeciErrors->c4AddEnumItem(L"NotReady", L"The net data source is not ready for use");
m_c4ErrId_Read = m_pmeciErrors->c4AddEnumItem(L"Read", TString::strEmpty());
m_c4ErrId_Setup = m_pmeciErrors->c4AddEnumItem(L"Setup", TString::strEmpty());
m_pmeciErrors->BaseClassInit(meOwner);
meOwner.c2AddClass(m_pmeciErrors);
bAddNestedType(m_pmeciErrors->strClassPath());
}
// An enum wrapper for the C++ line result enum.
{
m_pmeciLineRes = new TMEngEnumInfo
(
meOwner, L"LineReadRes", strClassPath(), L"MEng.Enum", 4
);
m_pmeciLineRes->c4AddEnumItem(L"GotLine", L"Got a line", tCIDLib::ELineRes::GotLine);
m_pmeciLineRes->c4AddEnumItem(L"EmptyLine", L"Got empty line" , tCIDLib::ELineRes::EmptyLine);
m_pmeciLineRes->c4AddEnumItem(L"Timeout", L"Timed out", tCIDLib::ELineRes::Timeout);
m_pmeciLineRes->c4AddEnumItem(L"Partial", L"Got partial Line", tCIDLib::ELineRes::Partial);
m_pmeciLineRes->BaseClassInit(meOwner);
meOwner.c2AddClass(m_pmeciLineRes);
bAddNestedType(m_pmeciLineRes->strClassPath());
}
//
// Look up some classes that we need to use.
//
m_c2TypeId_IPEndPoint = meOwner.c2FindClassId(TMEngIPEPInfo::strPath());
m_c2TypeId_TextXCoder = meOwner.c2FindClassId(TMEngTextXCoderInfo::strPath());
m_pmeciSockProtos = meOwner.pmeciFindAs<TMEngEnumInfo>
(
TMEngSocketInfo::strSockProtosPath(), kCIDLib::True
);
// The only constructor, which takes a title string
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.Runtime.DataSrc"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Close this object. It can later be reused
{
TMEngMethodInfo methiNew
(
L"Close"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
m_c2MethId_Close = c2AddMethodInfo(methiNew);
}
// Return true if data is available to be read
{
TMEngMethodInfo methiNew
(
L"DataIsReady"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"WaitMS", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_DataIsReady = c2AddMethodInfo(methiNew);
}
// Return true if the data source is conencted
{
TMEngMethodInfo methiNew
(
L"GetIsConnected"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetIsConnected = c2AddMethodInfo(methiNew);
}
// Get a line, or try to, returning the status
{
TMEngMethodInfo methiNew
(
L"GetLine"
, m_pmeciLineRes->c2Id()
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"WaitMS", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"TextCvt", m_c2TypeId_TextXCoder);
m_c2MethId_GetLine = c2AddMethodInfo(methiNew);
}
// Read up to the indicated number of bytes
{
TMEngMethodInfo methiNew
(
L"ReadBytes"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInParm(L"MaxBytes", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"WaitMS", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_ReadBytes = c2AddMethodInfo(methiNew);
}
// Set up this object
{
TMEngMethodInfo methiNew
(
L"TCPSetup"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"EndPoint", m_c2TypeId_IPEndPoint);
methiNew.c2AddInParm(L"Secure", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_TCPSetup = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngDataSrcInfo::pmecvMakeStorage( const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngDataSrcVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// These objects have to be set up before they can be used. The HTTP client class
// accesses the value object's C++ data source object, but he does it at the C++
// level. So he doesn't call a method of ours which could throw an exception if
// the value wasn't ready. So we provide this method for him to do that check.
//
tCIDLib::TVoid
TMEngDataSrcInfo::CheckIsReady( TCIDMacroEngine& meOwner
, const TMEngDataSrcVal& mecvCheck) const
{
if (!mecvCheck.bReady())
ThrowAnErr(meOwner, m_c4ErrId_NotReady);
}
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngDataSrcInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
TMEngDataSrcVal& mecvActual = static_cast<TMEngDataSrcVal&>(mecvInstance);
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_Close)
{
// Clean up the source object inside our value object
try
{
mecvActual.Close();
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
ThrowAnErr(meOwner, m_c4ErrId_Close, errToCatch);
}
}
else if (c2MethId == m_c2MethId_DataIsReady)
{
//
// The objects isn't set up, then obviously not. Else, let's get the wait
// time and make the call.
//
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
if (!mecvActual.bReady())
{
mecvRet.bValue(kCIDLib::False);
}
else
{
try
{
mecvRet.bValue
(
mecvActual.cdsValue().bDataAvailMS(meOwner.c4StackValAt(c4FirstInd))
);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
ThrowAnErr(meOwner, m_c4ErrId_Read, errToCatch);
}
}
}
else if (c2MethId == m_c2MethId_DefCtor)
{
}
else if (c2MethId == m_c2MethId_GetIsConnected)
{
// Just a return value
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue(mecvActual.bConnected());
}
else if (c2MethId == m_c2MethId_GetLine)
{
try
{
// Get the text converter object, for which there is not a convenience call
tCIDLib::ELineRes eRes = mecvActual.cdsValue().eGetLine
(
meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd).strValue()
, TTime::enctNowPlusMSs(meOwner.c4StackValAt(c4FirstInd + 1))
, meOwner.mecvStackAtAs<TMEngTextXCoderVal>(c4FirstInd + 2).tcvtValue()
);
//
// Convert the line result to the CML enum. They use the same values
// so we can just set the C++ value as the ordinal.
//
meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd - 1).c4Ordinal
(
tCIDLib::c4EnumOrd(eRes)
);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
ThrowAnErr(meOwner, m_c4ErrId_Read, errToCatch);
}
}
else if (c2MethId == m_c2MethId_ReadBytes)
{
try
{
const tCIDLib::TEncodedTime enctEnd = TTime::enctNowPlusMSs
(
meOwner.c4StackValAt(c4FirstInd + 2)
);
TMEngMemBufVal& mecvToFill = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd);
const tCIDLib::TCard4 c4Ret = mecvActual.cdsValue().c4ReadBytes
(
mecvToFill.mbufValue()
, meOwner.c4StackValAt(c4FirstInd + 1)
, enctEnd
, kCIDLib::False
);
// Give back the count of bytes read
meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1).c4Value(c4Ret);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
ThrowAnErr(meOwner, m_c4ErrId_Read, errToCatch);
}
}
else if (c2MethId == m_c2MethId_TCPSetup)
{
if (mecvActual.bReady())
ThrowAnErr(meOwner, m_c4ErrId_Already);
try
{
mecvActual.SetSockTCP
(
meOwner.mecvStackAtAs<TMEngIPEPVal>(c4FirstInd).ipepValue()
, meOwner.bStackValAt(c4FirstInd + 1)
);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
ThrowAnErr(meOwner, m_c4ErrId_Setup, errToCatch);
}
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TMEngDataSrcInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TMEngDataSrcInfo::ThrowAnErr( TCIDMacroEngine& meOwner
, const tCIDLib::TCard4 c4ToThrow
, TError& errCaught) const
{
// If verbose log mode, we'll log the C++ level exception
if (!errCaught.bLogged() && facCIDMacroEng().bLogWarnings())
{
errCaught.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errCaught);
}
// Set the exception info on the engine
meOwner.SetException
(
m_pmeciErrors->c2Id()
, strPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, errCaught.strErrText()
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
tCIDLib::TVoid
TMEngDataSrcInfo::ThrowAnErr(TCIDMacroEngine& meOwner, const tCIDLib::TCard4 c4ToThrow) const
{
// Set the exception info on the engine
meOwner.SetException
(
m_pmeciErrors->c2Id()
, strPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, m_pmeciErrors->strTextValue(c4ToThrow)
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
// ---------------------------------------------------------------------------
// CLASS: TMEngHTTPClientVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngHTTPClientVal: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngHTTPClientVal::TMEngHTTPClientVal( const TString& strName
, const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst) :
TMEngClassVal(strName, c2Id, eConst)
, m_phttpcValue(new THTTPClient)
{
}
TMEngHTTPClientVal::~TMEngHTTPClientVal()
{
delete m_phttpcValue;
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientVal: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngHTTPClientVal::bDbgFormat( TTextOutStream& strmTarget
, const TMEngClassInfo& meciThis
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices eRadix
, const TCIDMacroEngine& meOwner) const
{
CIDAssert(m_phttpcValue != nullptr, L"The HTTP client value object is not set");
if (eFormat == tCIDMacroEng::EDbgFmts::Long)
{
strmTarget << L"Proxy Server: ";
if (m_phttpcValue->strProxy().bIsEmpty())
{
strmTarget << L"[None]";
}
else
{
strmTarget << m_phttpcValue->strProxy()
<< L':' << m_phttpcValue->ippnProxy();
}
return kCIDLib::True;
}
return kCIDLib::False;
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientVal: Public, non-virtual methods
// ---------------------------------------------------------------------------
THTTPClient& TMEngHTTPClientVal::httpcValue()
{
return *m_phttpcValue;
}
tCIDLib::TVoid TMEngHTTPClientVal::Reset()
{
m_phttpcValue->Reset();
}
// ---------------------------------------------------------------------------
// CLASS: TMEngHTTPClientInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngHTTPClientInfo: Public, static methods
// ---------------------------------------------------------------------------
const TString& TMEngHTTPClientInfo::strPath()
{
return CIDMacroEng_NetClasses::strHTTPClientClassPath;
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngHTTPClientInfo::TMEngHTTPClientInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
CIDMacroEng_NetClasses::strHTTPClient
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2MethId_CreateBasicAuthStr(kCIDMacroEng::c2BadId)
, m_c2MethId_DefCtor(kCIDMacroEng::c2BadId)
, m_c2MethId_DoSSLGET(kCIDMacroEng::c2BadId)
, m_c2MethId_DoSSLPOST(kCIDMacroEng::c2BadId)
, m_c2MethId_EscapeBodyText(kCIDMacroEng::c2BadId)
, m_c2MethId_ExpandBodyText(kCIDMacroEng::c2BadId)
, m_c2MethId_FindHdrLine(kCIDMacroEng::c2BadId)
, m_c2MethId_FindTextEncoding(kCIDMacroEng::c2BadId)
, m_c2MethId_GetClientMsg(kCIDMacroEng::c2BadId)
, m_c2MethId_GetSrvReply(kCIDMacroEng::c2BadId)
, m_c2MethId_ParseAuthReq(kCIDMacroEng::c2BadId)
, m_c2MethId_ParseMPartMIME(kCIDMacroEng::c2BadId)
, m_c2MethId_ParseQParms(kCIDMacroEng::c2BadId)
, m_c2MethId_ParseTextEncoding(kCIDMacroEng::c2BadId)
, m_c2MethId_SendGET(kCIDMacroEng::c2BadId)
, m_c2MethId_SendHEAD(kCIDMacroEng::c2BadId)
, m_c2MethId_SendPOST(kCIDMacroEng::c2BadId)
, m_c2MethId_SendPOST2(kCIDMacroEng::c2BadId)
, m_c2MethId_SendPUT(kCIDMacroEng::c2BadId)
, m_c2MethId_SendRUGET(kCIDMacroEng::c2BadId)
, m_c2MethId_SendRUHEAD(kCIDMacroEng::c2BadId)
, m_c2MethId_SendRUPOST(kCIDMacroEng::c2BadId)
, m_c2MethId_SendRUPOST2(kCIDMacroEng::c2BadId)
, m_c2MethId_SendRUPUT(kCIDMacroEng::c2BadId)
, m_c2MethId_SetAddrType(kCIDMacroEng::c2BadId)
, m_c2MethId_SetAuthInfo(kCIDMacroEng::c2BadId)
, m_c2MethId_SetAutoAuth(kCIDMacroEng::c2BadId)
, m_c2MethId_SetProxy(kCIDMacroEng::c2BadId)
, m_c2MethId_Reset(kCIDMacroEng::c2BadId)
, m_c2TypeId_KVPair(kCIDMacroEng::c2BadId)
, m_c2TypeId_CardList(kCIDMacroEng::c2BadId)
, m_c2TypeId_BufList(kCIDMacroEng::c2BadId)
, m_c2TypeId_ItemList(kCIDMacroEng::c2BadId)
, m_c2TypeId_StrList(kCIDMacroEng::c2BadId)
, m_c4ErrId_Get(kCIDLib::c4MaxCard)
, m_c4ErrId_Escape(kCIDLib::c4MaxCard)
, m_c4ErrId_Expand(kCIDLib::c4MaxCard)
, m_c4ErrId_Parse(kCIDLib::c4MaxCard)
, m_c4ErrId_Post(kCIDLib::c4MaxCard)
, m_c4ErrId_RecvMsg(kCIDLib::c4MaxCard)
, m_c4ErrId_SetProxy(kCIDLib::c4MaxCard)
, m_pmeciAuthTypes(nullptr)
, m_pmeciErrors(nullptr)
, m_pmeciIPAddrTypes(nullptr)
, m_pmeciNetSrc(nullptr)
, m_pmeciReadRes(nullptr)
{
// Force the import of non-intrinsic classes we reference
bAddClassImport(TMEngVectorInfo::strPath());
bAddClassImport(TMEngIPEPInfo::strPath());
bAddClassImport(CIDMacroEng_NetClasses::strURLClassPath);
bAddClassImport(TMEngKVPairInfo::strPath());
bAddClassImport(TMEngStreamSocketInfo::strPath());
bAddClassImport(CIDMacroEng_NetClasses::strDataSrcClassPath);
}
TMEngHTTPClientInfo::~TMEngHTTPClientInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngHTTPClientInfo::Init(TCIDMacroEngine& meOwner)
{
//
// An enum to represent the exceptions that this class throws. Note
// that we just use the text in the C++ exception in some cases, so there
// is no text for the enum value for those.
//
{
m_pmeciErrors = new TMEngEnumInfo
(
meOwner, L"HTTPClientErrors", strClassPath(), L"MEng.Enum", 7
);
m_c4ErrId_Get = m_pmeciErrors->c4AddEnumItem(L"GetError", TString::strEmpty());
m_c4ErrId_Escape = m_pmeciErrors->c4AddEnumItem(L"EscapeError", TString::strEmpty());
m_c4ErrId_Expand = m_pmeciErrors->c4AddEnumItem(L"ExpandError", TString::strEmpty());
m_c4ErrId_Parse = m_pmeciErrors->c4AddEnumItem(L"ParseError", TString::strEmpty());
m_c4ErrId_Post = m_pmeciErrors->c4AddEnumItem(L"PostError", TString::strEmpty());
m_c4ErrId_RecvMsg = m_pmeciErrors->c4AddEnumItem(L"ReceiveMsg", TString::strEmpty());
m_c4ErrId_SetProxy = m_pmeciErrors->c4AddEnumItem(L"SetProxy", TString::strEmpty());
m_pmeciErrors->BaseClassInit(meOwner);
meOwner.c2AddClass(m_pmeciErrors);
bAddNestedType(m_pmeciErrors->strClassPath());
}
//
// An enum to represent the HTTP authentication types
//
{
m_pmeciAuthTypes = new TMEngEnumInfo
(
meOwner, L"HTTPAuthTypes", strClassPath(), L"MEng.Enum", 2
);
m_pmeciAuthTypes->c4AddEnumItem(L"Basic", L"Basic Authentication", tCIDNet::EHTTPAuthTypes::Basic);
m_pmeciAuthTypes->c4AddEnumItem(L"Digest", L"Digest Authentication", tCIDNet::EHTTPAuthTypes::Digest);
m_pmeciAuthTypes->BaseClassInit(meOwner);
meOwner.c2AddClass(m_pmeciAuthTypes);
bAddNestedType(m_pmeciAuthTypes->strClassPath());
}
//
// An enum to represent the read result from GetClientMsg().
//
{
m_pmeciReadRes = new TMEngEnumInfo
(
meOwner, L"HTTPReadRes", strClassPath(), L"MEng.Enum", 11
);
m_pmeciReadRes->c4AddEnumItem(L"Success", L"Successful read", tCIDNet::ENetPReadRes::Success);
m_pmeciReadRes->c4AddEnumItem(L"BadFirstLn", TString::strEmpty(), tCIDNet::ENetPReadRes::BadFirstLine);
m_pmeciReadRes->c4AddEnumItem(L"BadHdrLn", TString::strEmpty(), tCIDNet::ENetPReadRes::BadHdrLine);
m_pmeciReadRes->c4AddEnumItem(L"BadLineCont", TString::strEmpty(), tCIDNet::ENetPReadRes::BadLineCont);
m_pmeciReadRes->c4AddEnumItem(L"BadProtoVer", TString::strEmpty(), tCIDNet::ENetPReadRes::BadProtoVer);
m_pmeciReadRes->c4AddEnumItem(L"BufTooSmall", TString::strEmpty(), tCIDNet::ENetPReadRes::BufTooSmall);
m_pmeciReadRes->c4AddEnumItem(L"ContLen", TString::strEmpty(), tCIDNet::ENetPReadRes::ContLen);
m_pmeciReadRes->c4AddEnumItem(L"InvalidMsg", TString::strEmpty(), tCIDNet::ENetPReadRes::InvalidMsg);
m_pmeciReadRes->c4AddEnumItem(L"PartialMsg", TString::strEmpty(), tCIDNet::ENetPReadRes::PartialMsg);
m_pmeciReadRes->c4AddEnumItem(L"Timeout", TString::strEmpty(), tCIDNet::ENetPReadRes::Timeout);
m_pmeciReadRes->BaseClassInit(meOwner);
meOwner.c2AddClass(m_pmeciReadRes);
bAddNestedType(m_pmeciReadRes->strClassPath());
}
// Add some constants for common HTTP return codes
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_OK"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_OK", tCIDMacroEng::EConstTypes::Const, 200)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_MovedPerm"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_MovedPerm", tCIDMacroEng::EConstTypes::Const, 301)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_MovedTemp"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_MovedTemp", tCIDMacroEng::EConstTypes::Const, 302)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_SeeOther"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_SeeOther", tCIDMacroEng::EConstTypes::Const, 303)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_NotChanged"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_NotChanged", tCIDMacroEng::EConstTypes::Const, 304)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_TempRedir"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_TempRedir", tCIDMacroEng::EConstTypes::Const, 307)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_PermRedir"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_PermRedir", tCIDMacroEng::EConstTypes::Const, 308)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_BadRequest"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_BadRequest", tCIDMacroEng::EConstTypes::Const, 400)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_AuthRequired"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_AuthRequired", tCIDMacroEng::EConstTypes::Const, 401)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_NotFound"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_NotFound", tCIDMacroEng::EConstTypes::Const, 404)
)
);
AddLiteral
(
new TMEngLiteralVal
(
L"kHTTPCode_ServerErr"
, tCIDMacroEng::EIntrinsics::Card4
, new TMEngCard4Val(L"kHTTPCode_ServerErr", tCIDMacroEng::EConstTypes::Const, 500)
)
);
//
// Look up some classes that we need to use. We need the URL class just
// for methods declarations below. We need the type of if the KVPair class
// for later. And we need the IP address types class, which is nested within
// the IP end point class. This one we get the class info object for since
// we need to do translations during runtime.
//
const tCIDLib::TCard2 c2URLId
(
meOwner.meciFind(CIDMacroEng_NetClasses::strURLClassPath).c2Id()
);
m_c2TypeId_KVPair = meOwner.c2FindClassId(TMEngKVPairInfo::strPath());
m_pmeciIPAddrTypes = meOwner.pmeciFindAs<TMEngEnumInfo>
(
TMEngIPEPInfo::strIPAddrTypesPath(), kCIDLib::True
);
m_pmeciNetSrc = meOwner.pmeciFindAs<TMEngDataSrcInfo>
(
CIDMacroEng_NetClasses::strDataSrcClassPath, kCIDLib::True
);
//
// We need vectors of a number of things.
//
{
TMEngVectorInfo* pmeciNew = new TMEngVectorInfo
(
meOwner
, L"BufList"
, strClassPath()
, TMEngVectorInfo::strPath()
, tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::MemBuf)
);
TJanitor<TMEngVectorInfo> janNewClass(pmeciNew);
pmeciNew->BaseClassInit(meOwner);
bAddNestedType(pmeciNew->strClassPath());
m_c2TypeId_BufList = meOwner.c2AddClass(janNewClass.pobjOrphan());
}
{
TMEngVectorInfo* pmeciNew = new TMEngVectorInfo
(
meOwner
, L"CardList"
, strClassPath()
, TMEngVectorInfo::strPath()
, tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card4)
);
TJanitor<TMEngVectorInfo> janNewClass(pmeciNew);
pmeciNew->BaseClassInit(meOwner);
bAddNestedType(pmeciNew->strClassPath());
m_c2TypeId_CardList = meOwner.c2AddClass(janNewClass.pobjOrphan());
}
{
TMEngVectorInfo* pmeciNew = new TMEngVectorInfo
(
meOwner
, L"LinesList"
, strClassPath()
, TMEngVectorInfo::strPath()
, m_c2TypeId_KVPair
);
TJanitor<TMEngVectorInfo> janNewClass(pmeciNew);
pmeciNew->BaseClassInit(meOwner);
bAddNestedType(pmeciNew->strClassPath());
m_c2TypeId_ItemList = meOwner.c2AddClass(janNewClass.pobjOrphan());
}
{
TMEngVectorInfo* pmeciNew = new TMEngVectorInfo
(
meOwner
, L"StrList"
, strClassPath()
, TMEngVectorInfo::strPath()
, tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::String)
);
TJanitor<TMEngVectorInfo> janNewClass(pmeciNew);
pmeciNew->BaseClassInit(meOwner);
bAddNestedType(pmeciNew->strClassPath());
m_c2TypeId_StrList = meOwner.c2AddClass(janNewClass.pobjOrphan());
}
// Create a basic authentication value, given a name and password
{
TMEngMethodInfo methiNew
(
L"CreateBasicAuthStr"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"UserName", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Password", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_CreateBasicAuthStr = c2AddMethodInfo(methiNew);
}
// Default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.Runtime.HTTPClient"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
//
// Do an SSL based GET or POST. They are really the same except for the
// the parameter directions.
//
{
TMEngMethodInfo methiNew
(
L"DoSSLGET"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
m_c2MethId_DoSSLGET = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"DoSSLPOST"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
m_c2MethId_DoSSLPOST = c2AddMethodInfo(methiNew);
}
// Escape HTML body text from a string to a stream
{
TMEngMethodInfo methiNew
(
L"EscapeBodyText"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"TarStream", tCIDMacroEng::EIntrinsics::TextOutStream);
m_c2MethId_EscapeBodyText = c2AddMethodInfo(methiNew);
}
// Expand HTML body text from a string to a stream
{
TMEngMethodInfo methiNew
(
L"ExpandBodyText"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"TarStream", tCIDMacroEng::EIntrinsics::TextOutStream);
m_c2MethId_ExpandBodyText = c2AddMethodInfo(methiNew);
}
// Look up a particular value in a header lines list
{
TMEngMethodInfo methiNew
(
L"FindHdrLine"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"HdrList", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"ToFind", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ValToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_FindHdrLine = c2AddMethodInfo(methiNew);
}
// Look at header lines and content body to try to determine encoding
{
TMEngMethodInfo methiNew
(
L"FindTextEncoding"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"HdrList", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddOutParm(L"Encoding", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_FindTextEncoding = c2AddMethodInfo(methiNew);
}
//
// When reusing the socket and expecting the server to send ongoing unsolicted
// replies, this can be used to parse them out. And the other way, to read in
// ongoing client type msgs.
//
{
TMEngMethodInfo methiNew
(
L"GetClientMsg"
, m_pmeciReadRes->c2Id()
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddOutParm(L"ReqType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"HdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"URLText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ProtoVer", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_GetClientMsg = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"GetSrvReply"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"NoContent", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_GetSrvReply = c2AddMethodInfo(methiNew);
}
// Break out the authenticate request header line from the server
{
TMEngMethodInfo methiNew
(
L"ParseAuthReq"
, m_pmeciAuthTypes->c2Id()
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Realm", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Nonce", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Opaque", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Domain", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Algorithm", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_ParseAuthReq = c2AddMethodInfo(methiNew);
}
// Parse a multi-part MIME content body
{
TMEngMethodInfo methiNew
(
L"ParseMultiPartMIME"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcBuf", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInParm(L"SrcBytes", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"PartBufs", m_c2TypeId_BufList);
methiNew.c2AddOutParm(L"Sizes", m_c2TypeId_CardList);
methiNew.c2AddOutParm(L"ContTypes", m_c2TypeId_StrList);
methiNew.c2AddOutParm(L"ContDispositions", m_c2TypeId_StrList);
methiNew.c2AddOutParm(L"ContTransEncodings", m_c2TypeId_StrList);
m_c2MethId_ParseMPartMIME = c2AddMethodInfo(methiNew);
}
// Break out a string of URL encoded query parameters
{
TMEngMethodInfo methiNew
(
L"ParseQueryParms"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ToFill", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"Expand", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_ParseQParms = c2AddMethodInfo(methiNew);
}
// Parse the ContType return and see if it's text and if so what encoding
{
TMEngMethodInfo methiNew
(
L"ParseTextEncoding"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"SrcText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_ParseTextEncoding = c2AddMethodInfo(methiNew);
}
// Send a GET request
{
TMEngMethodInfo methiNew
(
L"SendGET"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
m_c2MethId_SendGET = c2AddMethodInfo(methiNew);
}
// Sends out a HEAD, which never returns a body
{
TMEngMethodInfo methiNew
(
L"SendHEAD"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
m_c2MethId_SendHEAD = c2AddMethodInfo(methiNew);
}
//
// Send a POST request, providing the body content as a set of k/v pairs,
// which we format out appropriately.
//
{
TMEngMethodInfo methiNew
(
L"SendPOST"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PostVals", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
m_c2MethId_SendPOST = c2AddMethodInfo(methiNew);
}
// Same as above, but with pre-created body content instead of a k/v pair list
{
TMEngMethodInfo methiNew
(
L"SendPOST2"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
m_c2MethId_SendPOST2 = c2AddMethodInfo(methiNew);
}
// Send a PUT
{
TMEngMethodInfo methiNew
(
L"SendPUT"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
m_c2MethId_SendPUT = c2AddMethodInfo(methiNew);
}
// Send a GET request, with a reusable socket
{
TMEngMethodInfo methiNew
(
L"SendRUGET"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
m_c2MethId_SendRUGET = c2AddMethodInfo(methiNew);
}
// Sends out a HEAD, with a reusable socket
{
TMEngMethodInfo methiNew
(
L"SendRUHEAD"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
m_c2MethId_SendRUHEAD = c2AddMethodInfo(methiNew);
}
//
// Send a POST request, providing the body content as a set of k/v pairs,
// which we format out appropriately.
//
{
TMEngMethodInfo methiNew
(
L"SendRUPOST"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PostVals", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
m_c2MethId_SendRUPOST = c2AddMethodInfo(methiNew);
}
// Same as above, but with pre-created body content instead of a k/v pair list
{
TMEngMethodInfo methiNew
(
L"SendRUPOST2"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"DataSrc", m_pmeciNetSrc->c2Id());
m_c2MethId_SendRUPOST2 = c2AddMethodInfo(methiNew);
}
// Send a PUT
{
TMEngMethodInfo methiNew
(
L"SendRUPUT"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"URL", c2URLId);
methiNew.c2AddInParm(L"WaitFor", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Agent", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Accept", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"RepText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"OutHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInOutParm(L"ContType", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInOutParm(L"Content", tCIDMacroEng::EIntrinsics::MemBuf);
methiNew.c2AddInOutParm(L"ContLen", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"OutBody", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"InHdrLines", m_c2TypeId_ItemList);
methiNew.c2AddInParm(L"DataSrv", m_pmeciNetSrc->c2Id());
m_c2MethId_SendRUPUT = c2AddMethodInfo(methiNew);
}
// Set the desired address family type
{
TMEngMethodInfo methiNew
(
L"SetAddrType"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"Type", m_pmeciIPAddrTypes->c2Id());
m_c2MethId_SetAddrType = c2AddMethodInfo(methiNew);
}
// Set the auto-authorization flag
{
TMEngMethodInfo methiNew
(
L"SetAutoAuth"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"ToSet", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_SetAutoAuth = c2AddMethodInfo(methiNew);
}
// Set the auto-authorization info
{
TMEngMethodInfo methiNew
(
L"SetAuthInfo"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"UserName", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Password", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_SetAuthInfo = c2AddMethodInfo(methiNew);
}
// Set the proxy addr/port to use
{
TMEngMethodInfo methiNew
(
L"SetProxy"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"SrvAddr", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PortNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_SetProxy = c2AddMethodInfo(methiNew);
}
// Reset the object to get rid of any partial input or state
{
TMEngMethodInfo methiNew
(
L"Reset"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
m_c2MethId_Reset = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngHTTPClientInfo::pmecvMakeStorage( const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngHTTPClientVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngHTTPClientInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
TMEngHTTPClientVal& mecvActual = static_cast<TMEngHTTPClientVal&>(mecvInstance);
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_CreateBasicAuthStr)
{
// The HTTP client has a static helper to do this, just pass in the parms
THTTPClient::MakeBasicAuthStr
(
meOwner.strStackValAt(c4FirstInd)
, meOwner.strStackValAt(c4FirstInd + 1)
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2).strValue()
);
}
else if (c2MethId == m_c2MethId_DefCtor)
{
// Reset the value object
mecvActual.Reset();
}
else if ((c2MethId == m_c2MethId_DoSSLGET)
|| (c2MethId == m_c2MethId_DoSSLPOST))
{
try
{
const TMEngURLVal& mecvURL = meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd);
const TString& strAgent = meOwner.strStackValAt(c4FirstInd + 1);
const TString& strAccept = meOwner.strStackValAt(c4FirstInd + 2);
// The In and/or out parms
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 3);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 4);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 5);
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 6)
);
//
// Load up any incoming header lines. Use +1 for the max, in case of
// zero count.
//
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
tCIDLib::TKVPList colInHdrLines(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colInHdrLines.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
// If a POST, we have an outgoing length
tCIDLib::TCard4 c4SendLen = 0;
if (c2MethId == m_c2MethId_DoSSLPOST)
c4SendLen = mecvContLen.c4Value();
tCIDLib::TCard4 c4ResCode = 0;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4ContLen = THTTPClient::c4DoSSLPageOp
(
(c2MethId == m_c2MethId_DoSSLGET) ? tCIDNet::ESSLOps::GET
: tCIDNet::ESSLOps::POST
, mecvURL.urlValue()
, strAgent
, strAccept
, mecvContType.strValue()
, c4ResCode
, mecvCont.mbufValue()
, colInHdrLines
, colOutHdrLines
, c4SendLen
);
// Give back the content length. The data is already in the buffer
mecvContLen.c4Value(c4ContLen);
// Give back any output header lines
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 7);
mecvOutHdrLines.RemoveAll();
c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
// Give back the result code as the return
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4ResCode);
}
catch(TError& errToCatch)
{
ThrowAnErr
(
meOwner
, (c2MethId == m_c2MethId_DoSSLGET) ? m_c4ErrId_Get : m_c4ErrId_Post
, errToCatch
);
}
}
else if ((c2MethId == m_c2MethId_EscapeBodyText)
|| (c2MethId == m_c2MethId_ExpandBodyText))
{
//
// These both take an input string and output text stream, they just
// call different underyling C++ methods (with also take those same
// parameters.
//
const TString& strSrc = meOwner.strStackValAt(c4FirstInd);
TMEngTextOutStreamVal& mecvStrm
(
meOwner.mecvStackAtAs<TMEngTextOutStreamVal>(c4FirstInd + 1)
);
try
{
if (c2MethId == m_c2MethId_EscapeBodyText)
THTTPClient::EscapeBodyText(strSrc, mecvStrm.strmTarget(meOwner));
else
THTTPClient::ExpandBodyText(strSrc, mecvStrm.strmTarget(meOwner));
}
catch(TError& errToCatch)
{
ThrowAnErr
(
meOwner
, (c2MethId == m_c2MethId_EscapeBodyText) ? m_c4ErrId_Escape
: m_c4ErrId_Expand
, errToCatch
);
}
}
else if (c2MethId == m_c2MethId_FindHdrLine)
{
//
// Get the vector and search it. There's actually a helper in the
// C++ object, but this is so simple it's not worth the overhead
// of copying to a C++ collection just to find an element.
//
TMEngVectorVal& mecvInLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
const TString& strToFind = meOwner.strStackValAt(c4FirstInd + 1);
tCIDLib::TCard4 c4Index = 0;
for (; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& kvalCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
if (kvalCur.strKey() == strToFind)
{
TMEngStringVal& mecvVal = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2);
mecvVal.strValue(kvalCur.strValue());
break;
}
}
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue(c4Index < c4Count);
}
else if (c2MethId == m_c2MethId_FindTextEncoding)
{
try
{
// Load up any incoming header lines to a C++ vector
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd)
);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
// Use +1 for max in case of zero count
tCIDLib::TKVPList colHdrLines(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colHdrLines.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
// The output string to fill if successful
TMEngStringVal& mecvToFill = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 3);
// Now make the call and set up the return value
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue
(
TNetCoreParser::bFindTextEncoding
(
colHdrLines
, meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 1).mbufValue()
, meOwner.c4StackValAt(c4FirstInd + 2)
, mecvToFill.strValue()
)
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Parse, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetClientMsg)
{
try
{
TMEngDataSrcVal& mecvSrc = meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
TMEngStringVal& mecvReqText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 3);
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4);
TMEngStringVal& mecvURL = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 5);
TMEngCard4Val& mecvProtoVer = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 6);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 7);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 8);
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4ContLen = 0;
tCIDLib::TCard4 c4ProtoVer = 0;
const tCIDNet::ENetPReadRes eRes = mecvActual.httpcValue().eGetClientMsg
(
mecvSrc.cdsValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, mecvReqText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvURL.strValue()
, c4ProtoVer
, mecvCont.mbufValue()
, c4ContLen
, kCIDLib::False
);
mecvContLen.c4Value(c4ContLen);
mecvProtoVer.c4Value(c4ProtoVer);
TMEngEnumVal& mecvRet = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd - 1);
mecvRet.c4Ordinal(m_pmeciReadRes->c4FromMapValue(eRes));
// If it worked
if (eRes == tCIDNet::ENetPReadRes::Success)
{
// Get the outgoing header lines to CML format
mecvOutHdrLines.RemoveAll();
const tCIDLib::TCard4 c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_RecvMsg, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetSrvReply)
{
try
{
TMEngDataSrcVal& mecvSrc = meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
const tCIDLib::TBoolean bNoContent = meOwner.bStackValAt(c4FirstInd + 2);
// Output parms
TMEngStringVal& mecvRepText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 3);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 4);
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 5);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 6);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 7);
tCIDNet::EHTTPCodes eCodeType;
TString strRepType;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4ContLen;
tCIDLib::TCard4 c4Ret = mecvActual.httpcValue().c4GetSrvReply
(
mecvSrc.cdsValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, bNoContent
, strRepType
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvCont.mbufValue()
, c4ContLen
);
mecvContLen.c4Value(c4ContLen);
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
//
// We need to get the header lines out of our local vector and
// into the CML level vector.
//
mecvOutHdrLines.RemoveAll();
const tCIDLib::TCard4 c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_RecvMsg, errToCatch);
}
}
else if (c2MethId == m_c2MethId_ParseMPartMIME)
{
// We need to do the call and get the stuff into locals first
try
{
TVector<THeapBuf> colParts;
tCIDLib::TCardList fcolSizes;
tCIDLib::TStrList colTypes;
tCIDLib::TStrList colDispos;
tCIDLib::TStrList colEncodings;
TMEngMemBufVal& mecvSrcBuf = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd);
facCIDNet().ParseMultiPartMIME
(
mecvSrcBuf.mbufValue()
, meOwner.c4StackValAt(c4FirstInd + 1)
, meOwner.strStackValAt(c4FirstInd + 2)
, colParts
, fcolSizes
, colTypes
, colDispos
, colEncodings
);
//
// Now we have to load up our CML level vectors from the local
// data.
//
TMEngVectorVal& mecvParts = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 3);
TMEngVectorVal& mecvSizes = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 4);
TMEngVectorVal& mecvTypes = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 5);
TMEngVectorVal& mecvDispos = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 6);
TMEngVectorVal& mecvEncodings = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 7);
tCIDLib::TCard4 c4Count;
// Do the parts
c4Count = colParts.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
TMEngMemBufVal* pmecvNew = new TMEngMemBufVal
(
TString::strEmpty()
, tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::MemBuf)
, tCIDMacroEng::EConstTypes::NonConst
);
pmecvNew->mbufValue() = colParts[c4Index];
mecvParts.AddObject(pmecvNew);
}
// Do the sizes
c4Count = fcolSizes.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
mecvSizes.AddObject
(
new TMEngCard4Val
(
TString::strEmpty()
, tCIDMacroEng::EConstTypes::NonConst
, fcolSizes[c4Index]
)
);
}
// Do the content types
c4Count = colTypes.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
mecvTypes.AddObject
(
new TMEngStringVal
(
TString::strEmpty()
, tCIDMacroEng::EConstTypes::NonConst
, colTypes[c4Index]
)
);
}
// Do the content dispositions
c4Count = colDispos.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
mecvDispos.AddObject
(
new TMEngStringVal
(
TString::strEmpty()
, tCIDMacroEng::EConstTypes::NonConst
, colDispos[c4Index]
)
);
}
// Do the encodings
c4Count = colEncodings.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
mecvEncodings.AddObject
(
new TMEngStringVal
(
TString::strEmpty()
, tCIDMacroEng::EConstTypes::NonConst
, colEncodings[c4Index]
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Parse, errToCatch);
}
}
else if (c2MethId == m_c2MethId_ParseQParms)
{
try
{
// We have to use a temp local C++ collection first
tCIDLib::TKVPList colItems;
tCIDLib::TCard4 c4Ret = TURL::c4ParseQueryParms
(
meOwner.strStackValAt(c4FirstInd)
, colItems
, meOwner.bStackValAt(c4FirstInd + 2)
, TURL::EExpTypes::Query
);
// Now copy over to the CML level collection
TMEngVectorVal& mecvItems = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 1);
mecvItems.RemoveAll();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Ret; c4Index++)
{
const TKeyValuePair& kvalCur = colItems[c4Index];
mecvItems.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
// Give back the count return value
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Parse, errToCatch);
}
}
else if (c2MethId == m_c2MethId_ParseAuthReq)
{
try
{
tCIDNet::EHTTPAuthTypes eType;
THTTPClient::ParseAuthReq
(
meOwner.strStackValAt(c4FirstInd)
, eType
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 1).strValue()
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2).strValue()
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 3).strValue()
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4).strValue()
, meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 5).strValue()
);
// Store the authorization type
TMEngEnumVal& mecvRet = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd - 1);
mecvRet.c4Ordinal(m_pmeciAuthTypes->c4FromMapValue(eType));
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Parse, errToCatch);
}
}
else if (c2MethId == m_c2MethId_ParseTextEncoding)
{
try
{
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
TMEngStringVal& mecvToFill = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 1);
mecvRet.bValue
(
mecvActual.httpcValue().bParseTextEncoding
(
meOwner.strStackValAt(c4FirstInd), mecvToFill.strValue()
)
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Parse, errToCatch);
}
}
else if (c2MethId == m_c2MethId_Reset)
{
mecvActual.httpcValue().Reset();
}
else if ((c2MethId == m_c2MethId_SendGET)
|| (c2MethId == m_c2MethId_SendRUGET)
|| (c2MethId == m_c2MethId_SendPUT)
|| (c2MethId == m_c2MethId_SendRUPUT))
{
// These two are the same but for the method called
try
{
// Input parms
const TMEngURLVal& mecvURL = meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
const TString& strAgent = meOwner.strStackValAt(c4FirstInd + 2);
const TString& strAccept = meOwner.strStackValAt(c4FirstInd + 3);
// Output parms
TMEngStringVal& mecvRepText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 5);
// These are in/out, though possibly only used for out
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 6);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 7);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 8);
// And this tells us if we have outgoing content
const tCIDLib::TBoolean bOutBody = meOwner.bStackValAt(c4FirstInd + 9);
// Load up any incoming header lines
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 10)
);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
// Use +1 for max in case of zero count
tCIDLib::TKVPList colInHdrLines(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colInHdrLines.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
// If outgoing body content, then set the content length
tCIDLib::TCard4 c4ContLen = 0;
if (bOutBody)
c4ContLen = mecvContLen.c4Value();
//
// If there's an incoming data src , get a pointer to it, else pass in
// zero and it will create one for us.
//
TCIDDataSrc* pcdsToUse = 0;
if ((c2MethId == m_c2MethId_SendRUGET) || (c2MethId == m_c2MethId_SendRUPUT))
{
TMEngDataSrcVal& mecvSrc
(
meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd + 11)
);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
pcdsToUse = &mecvSrc.cdsValue();
}
tCIDNet::EHTTPCodes eCodeType = tCIDNet::EHTTPCodes::Unknown;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4Ret = 0;
if ((c2MethId == m_c2MethId_SendGET) || (c2MethId == m_c2MethId_SendRUGET))
{
c4Ret = mecvActual.httpcValue().c4SendGet
(
pcdsToUse
, mecvURL.urlValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, strAgent
, strAccept
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvCont.mbufValue()
, c4ContLen
, bOutBody
, colInHdrLines
);
}
else
{
c4Ret = mecvActual.httpcValue().c4SendPut
(
pcdsToUse
, mecvURL.urlValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, strAgent
, strAccept
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvCont.mbufValue()
, c4ContLen
, bOutBody
, colInHdrLines
);
}
mecvContLen.c4Value(c4ContLen);
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
//
// We need to get the header lines out of our local vector and
// into the CML level vector.
//
mecvOutHdrLines.RemoveAll();
c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Get, errToCatch);
}
}
else if ((c2MethId == m_c2MethId_SendHEAD)
|| (c2MethId == m_c2MethId_SendRUHEAD))
{
try
{
// Input parms
const TMEngURLVal& mecvURL = meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
const TString& strAgent = meOwner.strStackValAt(c4FirstInd + 2);
const TString& strAccept = meOwner.strStackValAt(c4FirstInd + 3);
// Output parms
TMEngStringVal& mecvRepText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 5);
// These are in/out, though possibly only used for out
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 6);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 7);
// Load up any incoming header lines
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 8)
);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
// Use +1 for max in case of zero count
tCIDLib::TKVPList colInHdrLines(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colInHdrLines.objAdd(TKeyValuePair(mecvCur.strKey(), mecvCur.strValue()));
}
//
// If there's an incoming socket, get a pointer to it, else pass in
// zero and it will create one for us.
//
TCIDDataSrc* pcdsToUse = nullptr;
if (c2MethId == m_c2MethId_SendRUHEAD)
{
TMEngDataSrcVal& mecvSrc
(
meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd + 11)
);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
pcdsToUse = &mecvSrc.cdsValue();
}
tCIDNet::EHTTPCodes eCodeType;
tCIDLib::TCard4 c4ContLen;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4Ret = mecvActual.httpcValue().c4SendHead
(
pcdsToUse
, mecvURL.urlValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, strAgent
, strAccept
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, c4ContLen
, colInHdrLines
);
mecvContLen.c4Value(c4ContLen);
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
//
// We need to get the header lines out of our local vector and
// into the CML level vector.
//
mecvOutHdrLines.RemoveAll();
c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Get, errToCatch);
}
}
else if ((c2MethId == m_c2MethId_SendPOST)
|| (c2MethId == m_c2MethId_SendRUPOST))
{
try
{
// Input parms
const TMEngURLVal& mecvURL = meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
const TString& strAgent = meOwner.strStackValAt(c4FirstInd + 2);
const TString& strAccept = meOwner.strStackValAt(c4FirstInd + 3);
//
// Get the incoming k/v pairs that represent the post values out of
// the CML level vector and into a local one.
//
tCIDLib::TKVPList colPostVals;
TMEngVectorVal& mecvVals = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 4);
const tCIDLib::TCard4 c4ValCount = mecvVals.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ValCount; c4Index++)
{
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvVals.mecvAt(meOwner, c4Index)
)
);
colPostVals.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 10)
);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
// Use + 1 for max in case of zero count
tCIDLib::TKVPList colInHdrLines(c4Count + 1);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colInHdrLines.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
// Output parms
TMEngStringVal& mecvRepText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 5);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 6);
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 7);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 8);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 9);
//
// If there's an incoming socket, get a pointer to it, else pass in
// zero and it will create one for us.
//
TCIDDataSrc* pcdsToUse = nullptr;
if (c2MethId == m_c2MethId_SendRUPOST)
{
TMEngDataSrcVal& mecvSrc
(
meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd + 11)
);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
pcdsToUse = &mecvSrc.cdsValue();
}
tCIDNet::EHTTPCodes eCodeType = tCIDNet::EHTTPCodes::Unknown;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4ContLen = 0;
tCIDLib::TCard4 c4Ret = mecvActual.httpcValue().c4SendPost
(
pcdsToUse
, mecvURL.urlValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, strAgent
, strAccept
, colPostVals
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvCont.mbufValue()
, c4ContLen
, colInHdrLines
);
mecvContLen.c4Value(c4ContLen);
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
//
// We need to get the header lines out of our local vector and
// into the CML level vector.
//
mecvOutHdrLines.RemoveAll();
c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Post, errToCatch);
}
}
else if ((c2MethId == m_c2MethId_SendPOST2)
|| (c2MethId == m_c2MethId_SendRUPOST2))
{
try
{
// Input parms
const TMEngURLVal& mecvURL = meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd);
const tCIDLib::TCard4 c4WaitFor = meOwner.c4StackValAt(c4FirstInd + 1);
const TString& strAgent = meOwner.strStackValAt(c4FirstInd + 2);
const TString& strAccept = meOwner.strStackValAt(c4FirstInd + 3);
// Output parms
TMEngStringVal& mecvRepText = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4);
TMEngVectorVal& mecvOutHdrLines = meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 5);
// These are in/out, though possibly only used for out
TMEngStringVal& mecvContType = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 6);
TMEngMemBufVal& mecvCont = meOwner.mecvStackAtAs<TMEngMemBufVal>(c4FirstInd + 7);
TMEngCard4Val& mecvContLen = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd + 8);
// And this tells us if we have outgoing content
const tCIDLib::TBoolean bOutBody = meOwner.bStackValAt(c4FirstInd + 9);
// And the outgong header lines
const TMEngVectorVal& mecvInLines
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 10)
);
tCIDLib::TCard4 c4Count = mecvInLines.c4ElemCount();
// Use +1 for max in case of zero count
tCIDLib::TKVPList colInHdrLines(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvInLines.mecvAt(meOwner, c4Index)
)
);
colInHdrLines.objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
//
// Get a copy of the incoming content length to pass in. If the
// bOutBody flag is false, it will be ignored so it doesn't matter
// if there's really no outgoing, but be a good boy and only pass
// non-zero if we need to.
//
// For the content buffer and the content type string, we are
// passing the passed values directly, so they already are going
// in with whatever value they had on the way in.
//
tCIDLib::TCard4 c4ContLen = 0;
if (bOutBody)
c4ContLen = mecvContLen.c4Value();
//
// If there's an incoming socket, get a pointer to it, else pass in
// zero and it will create one for us.
//
TCIDDataSrc* pcdsToUse = nullptr;
if (c2MethId == m_c2MethId_SendRUPOST2)
{
TMEngDataSrcVal& mecvSrc
(
meOwner.mecvStackAtAs<TMEngDataSrcVal>(c4FirstInd + 11)
);
m_pmeciNetSrc->CheckIsReady(meOwner, mecvSrc);
pcdsToUse = &mecvSrc.cdsValue();
}
tCIDNet::EHTTPCodes eCodeType;
tCIDLib::TKVPList colOutHdrLines;
tCIDLib::TCard4 c4Ret = mecvActual.httpcValue().c4SendPost
(
pcdsToUse
, mecvURL.urlValue()
, TTime::enctNowPlusMSs(c4WaitFor)
, strAgent
, strAccept
, eCodeType
, mecvRepText.strValue()
, colOutHdrLines
, mecvContType.strValue()
, mecvCont.mbufValue()
, c4ContLen
, bOutBody
, colInHdrLines
);
mecvContLen.c4Value(c4ContLen);
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(c4Ret);
//
// We need to get the header lines out of our local vector and
// into the CML level vector.
//
mecvOutHdrLines.RemoveAll();
c4Count = colOutHdrLines.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TKeyValuePair& kvalCur = colOutHdrLines[c4Index];
mecvOutHdrLines.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Post, errToCatch);
}
}
else if (c2MethId == m_c2MethId_SetAddrType)
{
// Translate the value
const TMEngEnumVal& mecvType = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd);
tCIDSock::EAddrTypes eType = tCIDSock::EAddrTypes
(
m_pmeciIPAddrTypes->c4MapValue(mecvType)
);
mecvActual.httpcValue().eAddrType(eType);
}
else if (c2MethId == m_c2MethId_SetAutoAuth)
{
mecvActual.httpcValue().bAutoAuth(meOwner.bStackValAt(c4FirstInd));
}
else if (c2MethId == m_c2MethId_SetAuthInfo)
{
mecvActual.httpcValue().SetAuthInfo
(
meOwner.strStackValAt(c4FirstInd)
, meOwner.strStackValAt(c4FirstInd + 1)
);
}
else if (c2MethId == m_c2MethId_SetProxy)
{
try
{
mecvActual.httpcValue().SetProxy
(
meOwner.strStackValAt(c4FirstInd)
, meOwner.c4StackValAt(c4FirstInd + 1)
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_SetProxy, errToCatch);
}
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TMEngHTTPClientInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TMEngHTTPClientInfo::ThrowAnErr( TCIDMacroEngine& meOwner
, const tCIDLib::TCard4 c4ToThrow
, TError& errCaught)
{
// If verbose log mode, we'll log the C++ level exception
if (!errCaught.bLogged() && facCIDMacroEng().bLogWarnings())
{
errCaught.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errCaught);
}
// Set the exception info on the engine
TString strText(errCaught.strErrText(), 128UL);
if (errCaught.bHasAuxText())
{
strText.Append(L". ");
strText.Append(errCaught.strAuxText());
}
meOwner.SetException
(
m_pmeciErrors->c2Id()
, strClassPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, strText
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
// ---------------------------------------------------------------------------
// CLASS: TMEngURLVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngURLVal: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngURLVal::TMEngURLVal(const TString& strName
, const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst) :
TMEngClassVal(strName, c2Id, eConst)
, m_purlValue(new TURL)
{
}
TMEngURLVal::TMEngURLVal(const TString& strName
, const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst
, const TURL& urlInit) :
TMEngClassVal(strName, c2Id, eConst)
, m_purlValue(new TURL(urlInit))
{
}
TMEngURLVal::~TMEngURLVal()
{
delete m_purlValue;
}
// ---------------------------------------------------------------------------
// TMEngURLVal: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngURLVal::bDbgFormat( TTextOutStream& strmTar
, const TMEngClassInfo& meciThis
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices eRadix
, const TCIDMacroEngine& meOwner) const
{
if (eFormat == tCIDMacroEng::EDbgFmts::Short)
{
strmTar << *m_purlValue;
}
else if (eFormat == tCIDMacroEng::EDbgFmts::Long)
{
TString strProto;
TString strUser;
TString strPassword;
TString strHost;
tCIDLib::TIPPortNum ippnHost;
TString strPath;
TString strParams;
TString strFragment;
TString strQuery;
m_purlValue->QueryEncodedForm
(
strProto
, strUser
, strPassword
, strHost
, ippnHost
, strPath
, strParams
, strFragment
, strQuery
);
strmTar << L"Proto: " << strProto << kCIDLib::NewLn
<< L"User: " << strUser << kCIDLib::NewLn
<< L"Password: " << strPassword << kCIDLib::NewLn
<< L"Host: " << strHost << kCIDLib::NewLn
<< L"Port: " << ippnHost << kCIDLib::NewLn
<< L"Path: " << strPath << kCIDLib::NewLn
<< L"Params: " << strParams << kCIDLib::NewLn
<< L"Fragment: " << strFragment << kCIDLib::NewLn
<< L"Query: " << strQuery<< kCIDLib::NewLn;
}
return kCIDLib::True;
}
tCIDLib::TVoid
TMEngURLVal::CopyFrom( const TMEngClassVal& mecvToCopy
, TCIDMacroEngine& meOwner)
{
if (meOwner.bValidation())
meOwner.CheckSameClasses(*this, mecvToCopy);
*m_purlValue = *static_cast<const TMEngURLVal&>(mecvToCopy).m_purlValue;
}
// ---------------------------------------------------------------------------
// TMEngURLVal: Public, non-virtual methods
// ---------------------------------------------------------------------------
TURL& TMEngURLVal::urlValue()
{
return *m_purlValue;
}
const TURL& TMEngURLVal::urlValue() const
{
return *m_purlValue;
}
tCIDLib::TVoid TMEngURLVal::Reset()
{
m_purlValue->Clear();
}
tCIDLib::TVoid TMEngURLVal::Set(const TURL& urlToSet)
{
*m_purlValue = urlToSet;
}
// ---------------------------------------------------------------------------
// CLASS: TMEngURLInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngURLInfo: Public, static methods
// ---------------------------------------------------------------------------
const TString& TMEngURLInfo::strPath()
{
return CIDMacroEng_NetClasses::strURLClassPath;
}
const TString& TMEngURLInfo::strProtosPath()
{
return CIDMacroEng_NetClasses::strURLProtosClassPath;
}
// ---------------------------------------------------------------------------
// TMEngURLInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngURLInfo::TMEngURLInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
CIDMacroEng_NetClasses::strURL
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::True
, tCIDMacroEng::EClassExt::Final
, L"MEng.Formattable"
)
, m_c2MethId_BuildURL(kCIDMacroEng::c2BadId)
, m_c2MethId_BuildURL2(kCIDMacroEng::c2BadId)
, m_c2MethId_Clear(kCIDMacroEng::c2BadId)
, m_c2MethId_DefCtor(kCIDMacroEng::c2BadId)
, m_c2MethId_Encode(kCIDMacroEng::c2BadId)
, m_c2MethId_Equal(kCIDMacroEng::c2BadId)
, m_c2MethId_Expand(kCIDMacroEng::c2BadId)
, m_c2MethId_GetEncoded(kCIDMacroEng::c2BadId)
, m_c2MethId_GetEncodedParts(kCIDMacroEng::c2BadId)
, m_c2MethId_GetFragment(kCIDMacroEng::c2BadId)
, m_c2MethId_GetFullText(kCIDMacroEng::c2BadId)
, m_c2MethId_GetHost(kCIDMacroEng::c2BadId)
, m_c2MethId_GetIPEndPoint(kCIDMacroEng::c2BadId)
, m_c2MethId_GetParams(kCIDMacroEng::c2BadId)
, m_c2MethId_GetPassword(kCIDMacroEng::c2BadId)
, m_c2MethId_GetPath(kCIDMacroEng::c2BadId)
, m_c2MethId_GetPort(kCIDMacroEng::c2BadId)
, m_c2MethId_GetProto(kCIDMacroEng::c2BadId)
, m_c2MethId_GetQParms(kCIDMacroEng::c2BadId)
, m_c2MethId_GetQParmsFmt(kCIDMacroEng::c2BadId)
, m_c2MethId_GetResource(kCIDMacroEng::c2BadId)
, m_c2MethId_GetUserName(kCIDMacroEng::c2BadId)
, m_c2MethId_Set(kCIDMacroEng::c2BadId)
, m_c2MethId_Set2(kCIDMacroEng::c2BadId)
, m_c2MethId_Set3(kCIDMacroEng::c2BadId)
, m_c2MethId_Set4(kCIDMacroEng::c2BadId)
, m_c2TypeId_Comps(kCIDMacroEng::c2BadId)
, m_c2TypeId_Errors(kCIDMacroEng::c2BadId)
, m_c2TypeId_ItemList(kCIDMacroEng::c2BadId)
, m_c2TypeId_IPEP(kCIDMacroEng::c2BadId)
, m_c2TypeId_KVPair(kCIDMacroEng::c2BadId)
, m_c2TypeId_Protos(kCIDMacroEng::c2BadId)
, m_c4ErrId_Encoding(kCIDLib::c4MaxCard)
, m_c4ErrId_NoIPEP(kCIDMacroEng::c2BadId)
, m_c4ErrId_Query(kCIDLib::c4MaxCard)
, m_c4ErrId_Set(kCIDLib::c4MaxCard)
, m_pmeciIPAddrTypes(nullptr)
, m_pmeciComps(nullptr)
, m_pmeciErrors(nullptr)
, m_pmeciProtos(nullptr)
{
// Add imports for any non-intrinsic classes we use in our signatures
bAddClassImport(TMEngBaseInfoInfo::strPath());
bAddClassImport(TMEngKVPairInfo::strPath());
bAddClassImport(TMEngIPEPInfo::strPath());
}
TMEngURLInfo::~TMEngURLInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngURLInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngURLInfo::Init(TCIDMacroEngine& meOwner)
{
// An enum for the URL component areas used in escaping
{
m_pmeciComps = new TMEngEnumInfo
(
meOwner, L"URLComps", strClassPath(), L"MEng.Enum", 3
);
m_pmeciComps->c4AddEnumItem(L"Path", L"Path", TURL::EExpTypes::Path);
m_pmeciComps->c4AddEnumItem(L"Query", L"Query", TURL::EExpTypes::Query);
m_pmeciComps->c4AddEnumItem(L"Fragment", L"Fragment", TURL::EExpTypes::Fragment);
m_pmeciComps->BaseClassInit(meOwner);
m_c2TypeId_Comps = meOwner.c2AddClass(m_pmeciComps);
bAddNestedType(m_pmeciComps->strClassPath());
}
//
// An enum to represent the exceptions that this class throws. Note
// that we just use the text in the C++ exception in some cases, so there
// is no text for the enum value for those.
//
{
m_pmeciErrors = new TMEngEnumInfo
(
meOwner, L"URLErrors", strClassPath(), L"MEng.Enum", 4
);
m_c4ErrId_Encoding = m_pmeciErrors->c4AddEnumItem(L"EncodingError", TString::strEmpty());
m_c4ErrId_NoIPEP = m_pmeciErrors->c4AddEnumItem(L"NoIPEP", TString::strEmpty());
m_c4ErrId_Query = m_pmeciErrors->c4AddEnumItem(L"QueryError", TString::strEmpty());
m_c4ErrId_Set = m_pmeciErrors->c4AddEnumItem(L"SetError", TString::strEmpty());
m_pmeciErrors->BaseClassInit(meOwner);
m_c2TypeId_Errors = meOwner.c2AddClass(m_pmeciErrors);
bAddNestedType(m_pmeciErrors->strClassPath());
}
// An enum for the protocols this class recognizes
{
m_pmeciProtos = new TMEngEnumInfo
(
meOwner, L"URLProtos", strClassPath(), L"MEng.Enum", 10
);
m_pmeciProtos->c4AddEnumItem(L"None", L"None", tCIDSock::EProtos::None);
m_pmeciProtos->c4AddEnumItem(L"File", L"file", tCIDSock::EProtos::File);
m_pmeciProtos->c4AddEnumItem(L"HTTP", L"http", tCIDSock::EProtos::HTTP);
m_pmeciProtos->c4AddEnumItem(L"FTP", L"ftp", tCIDSock::EProtos::FTP);
m_pmeciProtos->c4AddEnumItem(L"MailTo", L"mailto", tCIDSock::EProtos::MailTo);
m_pmeciProtos->c4AddEnumItem(L"News", L"news", tCIDSock::EProtos::News);
m_pmeciProtos->c4AddEnumItem(L"HTTPS", L"https", tCIDSock::EProtos::HTTPS);
m_pmeciProtos->c4AddEnumItem(L"SIP", L"sip", tCIDSock::EProtos::SIP);
m_pmeciProtos->c4AddEnumItem(L"WS", L"ws", tCIDSock::EProtos::WS);
m_pmeciProtos->c4AddEnumItem(L"WSS", L"wss", tCIDSock::EProtos::WSS);
m_pmeciProtos->BaseClassInit(meOwner);
m_c2TypeId_Protos = meOwner.c2AddClass(m_pmeciProtos);
bAddNestedType(m_pmeciProtos->strClassPath());
}
// Look up some types we need
m_c2TypeId_IPEP = meOwner.c2FindClassId(TMEngIPEPInfo::strPath());
m_c2TypeId_KVPair = meOwner.c2FindClassId(TMEngKVPairInfo::strPath());
m_pmeciIPAddrTypes = meOwner.pmeciFindAs<TMEngEnumInfo>
(
TMEngIPEPInfo::strIPAddrTypesPath(), kCIDLib::True
);
const tCIDLib::TCard2 c2FQTypes = meOwner.c2FindClassId
(
TMEngBaseInfoInfo::strFQTypesPath()
);
//
// Create a vector of kvpairs, since we have parameters of that type
// below. Any equiv type can be actually be passed in.
//
{
TMEngVectorInfo* pmeciNew = new TMEngVectorInfo
(
meOwner
, L"QPairs"
, strClassPath()
, TMEngVectorInfo::strPath()
, m_c2TypeId_KVPair
);
TJanitor<TMEngVectorInfo> janNewClass(pmeciNew);
pmeciNew->BaseClassInit(meOwner);
bAddNestedType(pmeciNew->strClassPath());
m_c2TypeId_ItemList = meOwner.c2AddClass(janNewClass.pobjOrphan());
}
//
// Build up a URL out of constituent parts. We have two. The second
// takes a list of key/value pairs for query parameters.
//
{
TMEngMethodInfo methiNew
(
L"BuildURL"
, tCIDMacroEng::EIntrinsics::String
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"Protocol", m_c2TypeId_Protos);
methiNew.c2AddInParm(L"User", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Password", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Host", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PortNum", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Path", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Params", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Fragment", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_BuildURL = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"BuildURL2"
, tCIDMacroEng::EIntrinsics::String
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"Protocol", m_c2TypeId_Protos);
methiNew.c2AddInParm(L"User", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Password", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Host", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PortNum", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Path", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Params", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Fragment", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"QParms", m_c2TypeId_ItemList);
m_c2MethId_BuildURL2 = c2AddMethodInfo(methiNew);
}
// Clear the URL
{
TMEngMethodInfo methiNew
(
L"Clear"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
m_c2MethId_Clear = c2AddMethodInfo(methiNew);
}
// Default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.Runtime.URL"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Encode a string based on component type
{
TMEngMethodInfo methiNew
(
L"Encode"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"ToEncode", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Component", m_c2TypeId_Comps);
methiNew.c2AddInParm(L"Append", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_Encode = c2AddMethodInfo(methiNew);
}
// Add the equal method
{
TMEngMethodInfo methiNew
(
L"Equal"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"Val", c2Id());
m_c2MethId_Equal = c2AddMethodInfo(methiNew);
}
// Expand a string based on component type
{
TMEngMethodInfo methiNew
(
L"Expand"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddInParm(L"ToExpand", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Component", m_c2TypeId_Comps);
methiNew.c2AddInParm(L"Append", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_Expand = c2AddMethodInfo(methiNew);
}
// Get the full URL encoded
{
TMEngMethodInfo methiNew
(
L"GetEncoded"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetEncoded = c2AddMethodInfo(methiNew);
}
// Get the individual encoded parts
{
TMEngMethodInfo methiNew
(
L"GetEncodedParts"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"Proto", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"User", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Host", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Path", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddOutParm(L"Suffix", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetEncodedParts = c2AddMethodInfo(methiNew);
}
// Get the fragment
{
TMEngMethodInfo methiNew
(
L"GetFragment"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetFragment = c2AddMethodInfo(methiNew);
}
// Get the full URL unencoded
{
TMEngMethodInfo methiNew
(
L"GetFullText"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetFullText = c2AddMethodInfo(methiNew);
}
// Get the host name part
{
TMEngMethodInfo methiNew
(
L"GetHost"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetHost = c2AddMethodInfo(methiNew);
}
// Get an IP end point that reflects the info in the URL, if available
{
TMEngMethodInfo methiNew
(
L"GetIPEndPoint"
, tCIDMacroEng::EIntrinsics::Boolean
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", m_c2TypeId_IPEP);
methiNew.c2AddInParm(L"AddrType", m_pmeciIPAddrTypes->c2Id());
methiNew.c2AddInParm(L"ThrowIfNot", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_GetIPEndPoint = c2AddMethodInfo(methiNew);
}
// Get the params part
{
TMEngMethodInfo methiNew
(
L"GetParams"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetParams = c2AddMethodInfo(methiNew);
}
// Get the password part
{
TMEngMethodInfo methiNew
(
L"GetPassword"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetPassword = c2AddMethodInfo(methiNew);
}
// Get the path part
{
TMEngMethodInfo methiNew
(
L"GetPath"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetPath = c2AddMethodInfo(methiNew);
}
// Get the port number
{
TMEngMethodInfo methiNew
(
L"GetPort"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetPort = c2AddMethodInfo(methiNew);
}
// Get the protocol
{
TMEngMethodInfo methiNew
(
L"GetProto"
, m_c2TypeId_Protos
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetProto = c2AddMethodInfo(methiNew);
}
// Get the query parameter list as K/V pairs
{
TMEngMethodInfo methiNew
(
L"GetQParms"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", m_c2TypeId_ItemList);
m_c2MethId_GetQParms = c2AddMethodInfo(methiNew);
}
// Get the query parameter list formatted out
{
TMEngMethodInfo methiNew
(
L"GetQParmsFmt"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetQParmsFmt = c2AddMethodInfo(methiNew);
}
// Get the URL resource, optionally expanded and optionally with suffix
{
TMEngMethodInfo methiNew
(
L"GetResource"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Expanded", tCIDMacroEng::EIntrinsics::Boolean);
methiNew.c2AddInParm(L"WithSuffix", tCIDMacroEng::EIntrinsics::Boolean);
m_c2MethId_GetResource = c2AddMethodInfo(methiNew);
}
// Get the user name part
{
TMEngMethodInfo methiNew
(
L"GetUserName"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
methiNew.c2AddOutParm(L"ToFill", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_GetUserName = c2AddMethodInfo(methiNew);
}
// Set from text
{
TMEngMethodInfo methiNew
(
L"Set"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"Text", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"FullyQual", c2FQTypes);
m_c2MethId_Set = c2AddMethodInfo(methiNew);
}
// Set from Base text + relative text
{
TMEngMethodInfo methiNew
(
L"Set2"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"BaseText", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"RelativeText", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_Set2 = c2AddMethodInfo(methiNew);
}
// Set from base URL + relative text
{
TMEngMethodInfo methiNew
(
L"Set3"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"BaseURL", c2Id());
methiNew.c2AddInParm(L"RelativeText", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_Set3 = c2AddMethodInfo(methiNew);
}
// Set from all of the info
{
TMEngMethodInfo methiNew
(
L"Set4"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"Protocol", m_c2TypeId_Protos);
methiNew.c2AddInParm(L"User", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Password", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Host", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"PortNum", tCIDMacroEng::EIntrinsics::Card4);
methiNew.c2AddInParm(L"Path", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Params", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Fragment", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"QParms", m_c2TypeId_ItemList);
m_c2MethId_Set4 = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngURLInfo::pmecvMakeStorage( const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngURLVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMEngURLInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngURLInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
TMEngURLVal& mecvActual = static_cast<TMEngURLVal&>(mecvInstance);
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_Clear)
{
mecvActual.Reset();
}
else if ((c2MethId == m_c2MethId_BuildURL)
|| (c2MethId == m_c2MethId_BuildURL2))
{
//
// If it is the 2 version we have to get out the KV pairs into
// a C++ list to pass in, else we pass a null pointer.
//
tCIDLib::TKVPList* pcolQPairs = nullptr;
if (c2MethId == m_c2MethId_BuildURL2)
{
const TMEngVectorVal& mecvQPs
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 8)
);
tCIDLib::TCard4 c4Count = mecvQPs.c4ElemCount();
// Use +1 for max in case of zero count
pcolQPairs = new tCIDLib::TKVPList(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvQPs.mecvAt(meOwner, c4Index)
)
);
pcolQPairs->objAdd
(
TKeyValuePair(mecvCur.strKey(), mecvCur.strValue())
);
}
}
TJanitor<tCIDLib::TKVPList> janQPs(pcolQPairs);
// We have to ranslate the protocol enum to text
TMEngEnumVal& mecvProto = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd);
// Build the URL into the return string
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd - 1);
TURL::BuildURL
(
m_pmeciProtos->strTextValue(mecvProto)
, meOwner.strStackValAt(c4FirstInd + 1)
, meOwner.strStackValAt(c4FirstInd + 2)
, meOwner.strStackValAt(c4FirstInd + 3)
, meOwner.c4StackValAt(c4FirstInd + 4)
, meOwner.strStackValAt(c4FirstInd + 5)
, meOwner.strStackValAt(c4FirstInd + 6)
, meOwner.strStackValAt(c4FirstInd + 7)
, pcolQPairs
, mecvRet.strValue()
, tCIDSock::EExpOpts::Encode
);
}
else if (c2MethId == m_c2MethId_DefCtor)
{
// Reset the value object
mecvActual.Reset();
}
else if (c2MethId == m_c2MethId_Encode)
{
try
{
TMEngStringVal& mecvTar = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 1);
TMEngEnumVal& mecvComp = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd + 2);
TURL::EncodeTo
(
meOwner.strStackValAt(c4FirstInd)
, mecvTar.strValue()
, TURL::EExpTypes(m_pmeciComps->c4MapValue(mecvComp))
, meOwner.bStackValAt(c4FirstInd + 3) ?
tCIDLib::EAppendOver::Append : tCIDLib::EAppendOver::Overwrite
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Encoding, errToCatch);
}
}
else if (c2MethId == m_c2MethId_Equal)
{
TMEngBooleanVal& mecvRet
= meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
mecvRet.bValue
(
meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd).urlValue()
== mecvActual.urlValue()
);
}
else if (c2MethId == m_c2MethId_Expand)
{
try
{
TMEngStringVal& mecvTar = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 1);
TMEngEnumVal& mecvComp = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd + 2);
TURL::ExpandTo
(
meOwner.strStackValAt(c4FirstInd)
, mecvTar.strValue()
, TURL::EExpTypes(m_pmeciComps->c4MapValue(mecvComp))
, meOwner.bStackValAt(c4FirstInd + 3) ?
tCIDLib::EAppendOver::Append : tCIDLib::EAppendOver::Overwrite
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Encoding, errToCatch);
}
}
else if (c2MethId == TMEngFormattableInfo::c2FormatToId())
{
//
// The parm is a text stream object. In our case, we can kind of
// cheat and just call to it directly.
//
TMEngTextOutStreamVal& mecvTarget
= meOwner.mecvStackAtAs<TMEngTextOutStreamVal>(c4FirstInd);
mecvTarget.strmTarget(meOwner) << mecvActual.urlValue();
}
else if (c2MethId == m_c2MethId_GetEncoded)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvActual.urlValue().QueryText
(
mecvRet.strValue(), kCIDLib::False, kCIDLib::True
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetEncodedParts)
{
try
{
TMEngStringVal& mecvProto = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
TMEngStringVal& mecvUser = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 1);
TMEngStringVal& mecvHost = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 2);
TMEngStringVal& mecvPath = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 3);
TMEngStringVal& mecvSuffix = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd + 4);
mecvActual.urlValue().QueryEncodedForm
(
mecvProto.strValue()
, mecvUser.strValue()
, mecvHost.strValue()
, mecvPath.strValue()
, mecvSuffix.strValue()
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetFragment)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strFragment());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetFullText)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvActual.urlValue().QueryText
(
mecvRet.strValue(), kCIDLib::True, kCIDLib::True
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetHost)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strHost());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetIPEndPoint)
{
TMEngBooleanVal& mecvRet = meOwner.mecvStackAtAs<TMEngBooleanVal>(c4FirstInd - 1);
try
{
// Get the IP address type value
TMEngEnumVal& mecvType = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd + 1);
TIPEndPoint ipepOut = mecvActual.urlValue().ipepHost
(
tCIDSock::EAddrTypes(m_pmeciIPAddrTypes->c4MapValue(mecvType))
);
// It worked, so set it on the caller's output parameter
meOwner.mecvStackAtAs<TMEngIPEPVal>(c4FirstInd).ipepValue(ipepOut);
mecvRet.bValue(kCIDLib::True);
}
catch(TError& errToCatch)
{
// Either throw or return false
if (meOwner.bStackValAt(c4FirstInd + 2))
ThrowAnErr(meOwner, m_c4ErrId_NoIPEP, errToCatch);
mecvRet.bValue(kCIDLib::False);
}
}
else if (c2MethId == m_c2MethId_GetParams)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strParams());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetPassword)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strPassword());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetPath)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strPath());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetPort)
{
TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(mecvActual.urlValue().ippnHost());
}
else if (c2MethId == m_c2MethId_GetProto)
{
TMEngEnumVal& mecvRet = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd - 1);
mecvRet.c4Ordinal(m_pmeciProtos->c4FromMapValue(mecvActual.urlValue().eProto()));
}
else if (c2MethId == m_c2MethId_GetQParms)
{
try
{
// Get the output list and clear it
TMEngVectorVal& mecvQPs(meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd));
mecvQPs.RemoveAll();
// Loop through the query parms list from the incoming URL
const tCIDLib::TKVPList& colQPs = mecvActual.urlValue().colQParms();
tCIDLib::TCard4 c4Count = colQPs.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Add a CML level KVPair into the caller's list for this one
const TKeyValuePair& kvalCur = colQPs[c4Index];
mecvQPs.AddObject
(
new TMEngKVPairVal
(
TString::strEmpty()
, m_c2TypeId_KVPair
, tCIDMacroEng::EConstTypes::NonConst
, kvalCur.strKey()
, kvalCur.strValue()
)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetQParmsFmt)
{
try
{
// Get the parms from our URL
const tCIDLib::TKVPList& colQPs = mecvActual.urlValue().colQParms();
// Format them out to the caller's string
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
TURL::FormatQParms
(
colQPs
, mecvRet.strValue()
, tCIDSock::EExpOpts::None
, tCIDLib::EAppendOver::Overwrite
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetResource)
{
try
{
TMEngStringVal& mecvToFill = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvActual.urlValue().QueryResource
(
mecvToFill.strValue()
, meOwner.bStackValAt(c4FirstInd + 1)
, meOwner.bStackValAt(c4FirstInd + 2)
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if (c2MethId == m_c2MethId_GetUserName)
{
try
{
TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd);
mecvRet.strValue(mecvActual.urlValue().strUser());
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Query, errToCatch);
}
}
else if ((c2MethId == m_c2MethId_Set) || (c2MethId == m_c2MethId_Set2))
{
try
{
if (c2MethId == m_c2MethId_Set)
{
TMEngEnumVal& mecvQual = meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd + 1);
mecvActual.urlValue().Reset
(
meOwner.strStackValAt(c4FirstInd)
, tCIDSock::EQualified(mecvQual.c4Ordinal())
);
}
else if (c2MethId == m_c2MethId_Set2)
{
mecvActual.urlValue().Reset
(
meOwner.strStackValAt(c4FirstInd)
, meOwner.strStackValAt(c4FirstInd + 1)
);
}
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Set, errToCatch);
}
}
else if (c2MethId == m_c2MethId_Set3)
{
try
{
mecvActual.urlValue().Reset
(
meOwner.mecvStackAtAs<TMEngURLVal>(c4FirstInd).urlValue()
, meOwner.strStackValAt(c4FirstInd + 1)
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Set, errToCatch);
}
}
else if (c2MethId == m_c2MethId_Set4)
{
// Get out any CML level query parameters into a C++ version of the list
const TMEngVectorVal& mecvQPs
(
meOwner.mecvStackAtAs<TMEngVectorVal>(c4FirstInd + 8)
);
tCIDLib::TCard4 c4Count = mecvQPs.c4ElemCount();
// Use +1 for max in case of zero count
tCIDLib::TKVPList colQPairs(c4Count);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Get the element and cast to its real type
const TMEngKVPairVal& mecvCur
(
static_cast<const TMEngKVPairVal&>
(
mecvQPs.mecvAt(meOwner, c4Index)
)
);
colQPairs.objAdd(TKeyValuePair(mecvCur.strKey(), mecvCur.strValue()));
}
try
{
const TMEngEnumVal& mecvProto(meOwner.mecvStackAtAs<TMEngEnumVal>(c4FirstInd));
mecvActual.urlValue().Set
(
tCIDSock::EProtos(m_pmeciProtos->c4MapValue(mecvProto))
, meOwner.strStackValAt(c4FirstInd + 1)
, meOwner.strStackValAt(c4FirstInd + 2)
, meOwner.strStackValAt(c4FirstInd + 3)
, meOwner.c4StackValAt(c4FirstInd + 4)
, meOwner.strStackValAt(c4FirstInd + 5)
, meOwner.strStackValAt(c4FirstInd + 6)
, meOwner.strStackValAt(c4FirstInd + 7)
, colQPairs
, kCIDLib::True
);
}
catch(TError& errToCatch)
{
ThrowAnErr(meOwner, m_c4ErrId_Set, errToCatch);
}
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TMEngURLInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TMEngURLInfo::ThrowAnErr( TCIDMacroEngine& meOwner
, const tCIDLib::TCard4 c4ToThrow
, TError& errCaught)
{
// If verbose log mode, we'll log the C++ level exception
if (!errCaught.bLogged() && facCIDMacroEng().bLogWarnings())
{
errCaught.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errCaught);
}
// Set the exception info on the engine
meOwner.SetException
(
m_c2TypeId_Errors
, strClassPath()
, c4ToThrow
, m_pmeciErrors->strPartialName(c4ToThrow)
, errCaught.strErrText()
, meOwner.c4CurLine()
);
// And throw the excpetion that represents a macro level exception
throw TExceptException();
}
| 0 | 0.872384 | 1 | 0.872384 | game-dev | MEDIA | 0.40493 | game-dev | 0.902467 | 1 | 0.902467 |
STJr/Kart-Public | 35,873 | src/m_cheat.c | // SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 1998-2000 by DooM Legacy Team.
// Copyright (C) 1999-2018 by Sonic Team Junior.
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file m_cheat.c
/// \brief Cheat sequence checking
#include "doomdef.h"
#include "g_input.h"
#include "g_game.h"
#include "s_sound.h"
#include "r_local.h"
#include "p_local.h"
#include "p_setup.h"
#include "d_net.h"
#include "m_cheat.h"
#include "m_menu.h"
#include "m_random.h"
#include "m_misc.h"
#include "hu_stuff.h"
#include "m_cond.h" // secrets unlocked?
#include "v_video.h"
#include "z_zone.h"
#include "p_slopes.h"
#include "k_kart.h" // srb2kart
#include "lua_script.h"
#include "lua_hook.h"
//
// CHEAT SEQUENCE PACKAGE
//
#define SCRAMBLE(a) \
((((a)&1)<<7) + (((a)&2)<<5) + ((a)&4) + (((a)&8)<<1) \
+ (((a)&16)>>1) + ((a)&32) + (((a)&64)>>5) + (((a)&128)>>7))
typedef struct
{
UINT8 *p;
UINT8 (*func)(void); // called when cheat confirmed.
UINT8 sequence[];
} cheatseq_t;
// ==========================================================================
// CHEAT Structures
// ==========================================================================
// Cheat responders
/*static UINT8 cheatf_ultimate(void)
{
if (menuactive && (currentMenu != &MainDef && currentMenu != &SP_LoadDef))
return 0; // Only on the main menu, or the save select!
S_StartSound(0, sfx_itemup);
ultimate_selectable = (!ultimate_selectable);
// If on the save select, move to what is now Ultimate Mode!
if (currentMenu == &SP_LoadDef)
M_ForceSaveSlotSelected(NOSAVESLOT);
return 1;
}*/
static UINT8 cheatf_warp(void)
{
UINT8 i;
boolean success = false;
/*if (modifiedgame)
return 0;*/
if (menuactive && currentMenu != &MainDef)
return 0; // Only on the main menu!
// Temporarily unlock EVERYTHING.
for (i = 0; i < MAXUNLOCKABLES; i++)
{
if (!unlockables[i].conditionset)
continue;
if (!unlockables[i].unlocked)
{
unlockables[i].unlocked = true;
success = true;
}
}
if (success)
{
G_SaveGameData(true); //G_SetGameModified(false);
S_StartSound(0, sfx_kc42);
}
// Refresh secrets menu existing.
M_ClearMenus(true);
M_StartControlPanel();
return 1;
}
#ifdef DEVELOP
static UINT8 cheatf_devmode(void)
{
UINT8 i;
if (modifiedgame)
return 0;
if (menuactive && currentMenu != &MainDef)
return 0; // Only on the main menu!
S_StartSound(0, sfx_itemup);
// Just unlock all the things and turn on -debug and console devmode.
G_SetGameModified(false, false); // might need to revist the latter later
for (i = 0; i < MAXUNLOCKABLES; i++)
unlockables[i].unlocked = true;
devparm = true;
cv_debug |= 0x8000;
// Refresh secrets menu existing.
M_ClearMenus(true);
M_StartControlPanel();
return 1;
}
#endif
/*static cheatseq_t cheat_ultimate = {
0, cheatf_ultimate,
{ SCRAMBLE('u'), SCRAMBLE('l'), SCRAMBLE('t'), SCRAMBLE('i'), SCRAMBLE('m'), SCRAMBLE('a'), SCRAMBLE('t'), SCRAMBLE('e'), 0xff }
};*/
/*static cheatseq_t cheat_ultimate_joy = {
0, cheatf_ultimate,
{ SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_DOWNARROW), SCRAMBLE(KEY_DOWNARROW),
SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_RIGHTARROW),
SCRAMBLE(KEY_ENTER), 0xff }
};*/
static cheatseq_t cheat_warp = {
0, cheatf_warp,
//{ SCRAMBLE('r'), SCRAMBLE('e'), SCRAMBLE('d'), SCRAMBLE('x'), SCRAMBLE('v'), SCRAMBLE('i'), 0xff }
{ SCRAMBLE('b'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), 0xff }
};
static cheatseq_t cheat_warp_joy = {
0, cheatf_warp,
/*{ SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW),
SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_UPARROW),
SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW),
SCRAMBLE(KEY_ENTER), 0xff }*/
{ SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_RIGHTARROW),
SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_LEFTARROW),
SCRAMBLE(KEY_DOWNARROW), SCRAMBLE(KEY_RIGHTARROW),
SCRAMBLE(KEY_ENTER), 0xff }
};
#ifdef DEVELOP
static cheatseq_t cheat_devmode = {
0, cheatf_devmode,
{ SCRAMBLE('d'), SCRAMBLE('e'), SCRAMBLE('v'), SCRAMBLE('m'), SCRAMBLE('o'), SCRAMBLE('d'), SCRAMBLE('e'), 0xff }
};
#endif
// ==========================================================================
// CHEAT SEQUENCE PACKAGE
// ==========================================================================
static UINT8 cheat_xlate_table[256];
void cht_Init(void)
{
size_t i = 0;
INT16 pi = 0;
for (; i < 256; i++, pi++)
{
const INT32 cc = SCRAMBLE(pi);
cheat_xlate_table[i] = (UINT8)cc;
}
}
//
// Called in st_stuff module, which handles the input.
// Returns a 1 if the cheat was successful, 0 if failed.
//
static UINT8 cht_CheckCheat(cheatseq_t *cht, char key)
{
UINT8 rc = 0;
if (!cht->p)
cht->p = cht->sequence; // initialize if first time
if (*cht->p == 0)
*(cht->p++) = key;
else if (cheat_xlate_table[(UINT8)key] == *cht->p)
cht->p++;
else
cht->p = cht->sequence;
if (*cht->p == 1)
cht->p++;
else if (*cht->p == 0xff) // end of sequence character
{
cht->p = cht->sequence;
rc = cht->func();
}
return rc;
}
boolean cht_Responder(event_t *ev)
{
UINT8 ret = 0, ch = 0;
if (ev->type != ev_keydown)
return false;
if (ev->data1 > 0xFF)
{
// map some fake (joy) inputs into keys
// map joy inputs into keys
switch (ev->data1)
{
case KEY_JOY1:
case KEY_JOY1 + 2:
ch = KEY_ENTER;
break;
case KEY_HAT1:
ch = KEY_UPARROW;
break;
case KEY_HAT1 + 1:
ch = KEY_DOWNARROW;
break;
case KEY_HAT1 + 2:
ch = KEY_LEFTARROW;
break;
case KEY_HAT1 + 3:
ch = KEY_RIGHTARROW;
break;
default:
// no mapping
return false;
}
}
else
ch = (UINT8)ev->data1;
//ret += cht_CheckCheat(&cheat_ultimate, (char)ch);
//ret += cht_CheckCheat(&cheat_ultimate_joy, (char)ch);
ret += cht_CheckCheat(&cheat_warp, (char)ch);
ret += cht_CheckCheat(&cheat_warp_joy, (char)ch);
#ifdef DEVELOP
ret += cht_CheckCheat(&cheat_devmode, (char)ch);
#endif
return (ret != 0);
}
// Console cheat commands rely on these a lot...
#define REQUIRE_PANDORA if (!M_SecretUnlocked(SECRET_PANDORA) && !cv_debug)\
{ CONS_Printf(M_GetText("You haven't earned this yet.\n")); return; }
#define REQUIRE_DEVMODE if (!cv_debug)\
{ CONS_Printf(M_GetText("DEVMODE must be enabled.\n")); return; }
#define REQUIRE_OBJECTPLACE if (!objectplacing)\
{ CONS_Printf(M_GetText("OBJECTPLACE must be enabled.\n")); return; }
#define REQUIRE_INLEVEL if (gamestate != GS_LEVEL || demo.playback)\
{ CONS_Printf(M_GetText("You must be in a level to use this.\n")); return; }
#define REQUIRE_SINGLEPLAYER if (netgame || multiplayer)\
{ CONS_Printf(M_GetText("This only works in single player.\n")); return; }
#define REQUIRE_NOULTIMATE if (ultimatemode)\
{ CONS_Printf(M_GetText("You're too good to be cheating!\n")); return; }
// command that can be typed at the console!
void Command_CheatNoClip_f(void)
{
player_t *plyr;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
plyr = &players[consoleplayer];
plyr->pflags ^= PF_NOCLIP;
CONS_Printf(M_GetText("No Clipping %s\n"), plyr->pflags & PF_NOCLIP ? M_GetText("On") : M_GetText("Off"));
G_SetGameModified(multiplayer, true);
}
void Command_CheatGod_f(void)
{
player_t *plyr;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
plyr = &players[consoleplayer];
plyr->pflags ^= PF_GODMODE;
CONS_Printf(M_GetText("Sissy Mode %s\n"), plyr->pflags & PF_GODMODE ? M_GetText("On") : M_GetText("Off"));
G_SetGameModified(multiplayer, true);
}
void Command_CheatNoTarget_f(void)
{
player_t *plyr;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
plyr = &players[consoleplayer];
plyr->pflags ^= PF_INVIS;
CONS_Printf(M_GetText("SEP Field %s\n"), plyr->pflags & PF_INVIS ? M_GetText("On") : M_GetText("Off"));
G_SetGameModified(multiplayer, true);
}
void Command_Scale_f(void)
{
const double scaled = atof(COM_Argv(1));
fixed_t scale = FLOAT_TO_FIXED(scaled);
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (scale < FRACUNIT/100 || scale > 100*FRACUNIT) //COM_Argv(1) will return a null string if they did not give a paramater, so...
{
CONS_Printf(M_GetText("scale <value> (0.01-100.0): set player scale size\n"));
return;
}
if (!players[consoleplayer].mo)
return;
players[consoleplayer].mo->destscale = scale;
CONS_Printf(M_GetText("Scale set to %s\n"), COM_Argv(1));
}
void Command_Gravflip_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (players[consoleplayer].mo)
players[consoleplayer].mo->flags2 ^= MF2_OBJECTFLIP;
}
void Command_Hurtme_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() < 2)
{
CONS_Printf(M_GetText("hurtme <damage>: Damage yourself by a specific amount\n"));
return;
}
P_DamageMobj(players[consoleplayer].mo, NULL, NULL, atoi(COM_Argv(1)));
}
// Moves the NiGHTS player to another axis within the current mare
/*void Command_JumpToAxis_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() != 2)
{
CONS_Printf(M_GetText("jumptoaxis <axisnum>: Jump to axis within current mare.\n"));
return;
}
P_TransferToAxis(&players[consoleplayer], atoi(COM_Argv(1)));
}
void Command_Charability_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() < 3)
{
CONS_Printf(M_GetText("charability <1/2> <value>: change character abilities\n"));
return;
}
if (atoi(COM_Argv(1)) == 1)
players[consoleplayer].charability = (UINT8)atoi(COM_Argv(2));
else if (atoi(COM_Argv(1)) == 2)
players[consoleplayer].charability2 = (UINT8)atoi(COM_Argv(2));
else
CONS_Printf(M_GetText("charability <1/2> <value>: change character abilities\n"));
}
void Command_Charspeed_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() < 3)
{
CONS_Printf(M_GetText("charspeed <normalspeed/runspeed/thrustfactor/accelstart/acceleration/actionspd> <value>: set character speed\n"));
return;
}
if (!strcasecmp(COM_Argv(1), "normalspeed"))
players[consoleplayer].normalspeed = atoi(COM_Argv(2))<<FRACBITS;
else if (!strcasecmp(COM_Argv(1), "runspeed"))
players[consoleplayer].runspeed = atoi(COM_Argv(2))<<FRACBITS;
else if (!strcasecmp(COM_Argv(1), "thrustfactor"))
players[consoleplayer].thrustfactor = atoi(COM_Argv(2));
else if (!strcasecmp(COM_Argv(1), "accelstart"))
players[consoleplayer].accelstart = atoi(COM_Argv(2));
else if (!strcasecmp(COM_Argv(1), "acceleration"))
players[consoleplayer].acceleration = atoi(COM_Argv(2));
else if (!strcasecmp(COM_Argv(1), "actionspd"))
players[consoleplayer].actionspd = atoi(COM_Argv(2))<<FRACBITS;
else
CONS_Printf(M_GetText("charspeed <normalspeed/runspeed/thrustfactor/accelstart/acceleration/actionspd> <value>: set character speed\n"));
}*/
void Command_RTeleport_f(void)
{
fixed_t intx, inty, intz;
size_t i;
player_t *p = &players[consoleplayer];
subsector_t *ss;
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() < 3 || COM_Argc() > 7)
{
CONS_Printf(M_GetText("rteleport -x <value> -y <value> -z <value>: relative teleport to a location\n"));
return;
}
if (!p->mo)
return;
i = COM_CheckParm("-x");
if (i)
intx = atoi(COM_Argv(i + 1));
else
intx = 0;
i = COM_CheckParm("-y");
if (i)
inty = atoi(COM_Argv(i + 1));
else
inty = 0;
ss = R_IsPointInSubsector(p->mo->x + intx*FRACUNIT, p->mo->y + inty*FRACUNIT);
if (!ss || ss->sector->ceilingheight - ss->sector->floorheight < p->mo->height)
{
CONS_Alert(CONS_NOTICE, M_GetText("Not a valid location.\n"));
return;
}
i = COM_CheckParm("-z");
if (i)
{
intz = atoi(COM_Argv(i + 1));
intz <<= FRACBITS;
intz += p->mo->z;
if (intz < ss->sector->floorheight)
intz = ss->sector->floorheight;
if (intz > ss->sector->ceilingheight - p->mo->height)
intz = ss->sector->ceilingheight - p->mo->height;
}
else
intz = p->mo->z;
CONS_Printf(M_GetText("Teleporting by %d, %d, %d...\n"), intx, inty, FixedInt((intz-p->mo->z)));
P_MapStart();
if (!P_SetOrigin(p->mo, p->mo->x+intx*FRACUNIT, p->mo->y+inty*FRACUNIT, intz))
CONS_Alert(CONS_WARNING, M_GetText("Unable to teleport to that spot!\n"));
else
S_StartSound(p->mo, sfx_mixup);
P_MapEnd();
}
void Command_Teleport_f(void)
{
fixed_t intx, inty, intz;
size_t i;
player_t *p = &players[consoleplayer];
subsector_t *ss;
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() < 3 || COM_Argc() > 7)
{
CONS_Printf(M_GetText("teleport -x <value> -y <value> -z <value>: teleport to a location\n"));
return;
}
if (!p->mo)
return;
i = COM_CheckParm("-x");
if (i)
intx = atoi(COM_Argv(i + 1));
else
{
CONS_Alert(CONS_NOTICE, M_GetText("%s value not specified\n"), "X");
return;
}
i = COM_CheckParm("-y");
if (i)
inty = atoi(COM_Argv(i + 1));
else
{
CONS_Alert(CONS_NOTICE, M_GetText("%s value not specified\n"), "Y");
return;
}
ss = R_PointInSubsector(intx*FRACUNIT, inty*FRACUNIT);
if (!ss || ss->sector->ceilingheight - ss->sector->floorheight < p->mo->height)
{
CONS_Alert(CONS_NOTICE, M_GetText("Not a valid location.\n"));
return;
}
i = COM_CheckParm("-z");
if (i)
{
intz = atoi(COM_Argv(i + 1));
intz <<= FRACBITS;
if (intz < ss->sector->floorheight)
intz = ss->sector->floorheight;
if (intz > ss->sector->ceilingheight - p->mo->height)
intz = ss->sector->ceilingheight - p->mo->height;
}
else
intz = ss->sector->floorheight;
CONS_Printf(M_GetText("Teleporting to %d, %d, %d...\n"), intx, inty, FixedInt(intz));
P_MapStart();
if (!P_SetOrigin(p->mo, intx*FRACUNIT, inty*FRACUNIT, intz))
CONS_Alert(CONS_WARNING, M_GetText("Unable to teleport to that spot!\n"));
else
S_StartSound(p->mo, sfx_mixup);
P_MapEnd();
}
void Command_Skynum_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() != 2)
{
CONS_Printf(M_GetText("skynum <sky#>: change the sky\n"));
CONS_Printf(M_GetText("Current sky is %d\n"), levelskynum);
return;
}
CONS_Printf(M_GetText("Previewing sky %s...\n"), COM_Argv(1));
P_SetupLevelSky(atoi(COM_Argv(1)), false);
}
void Command_Weather_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
if (COM_Argc() != 2)
{
CONS_Printf(M_GetText("weather <weather#>: change the weather\n"));
CONS_Printf(M_GetText("Current weather is %d\n"), curWeather);
return;
}
CONS_Printf(M_GetText("Previewing weather %s...\n"), COM_Argv(1));
P_SwitchWeather(atoi(COM_Argv(1)));
}
#ifdef _DEBUG
// You never thought you needed this, did you? >=D
// Yes, this has the specific purpose of completely screwing you up
// to see if the consistency restoration code can fix you.
// Don't enable this for normal builds...
void Command_CauseCfail_f(void)
{
if (consoleplayer == serverplayer)
{
CONS_Printf(M_GetText("Only remote players can use this command.\n"));
return;
}
P_UnsetThingPosition(players[consoleplayer].mo);
P_RandomFixed();
P_RandomByte();
P_RandomFixed();
players[consoleplayer].mo->x = 0;
players[consoleplayer].mo->y = 123311; //cfail cansuled kthxbye
players[consoleplayer].mo->z = 123311;
players[consoleplayer].score = 1337;
players[consoleplayer].health = 1337;
players[consoleplayer].mo->destscale = 25;
P_SetThingPosition(players[consoleplayer].mo);
// CTF consistency test
if (gametype == GT_CTF)
{
if (blueflag) {
P_RemoveMobj(blueflag);
blueflag = NULL;
}
if (redflag)
{
redflag->x = 423423;
redflag->y = 666;
redflag->z = 123311;
}
}
}
#endif
#if defined(HAVE_BLUA) && defined(LUA_ALLOW_BYTECODE)
void Command_Dumplua_f(void)
{
if (modifiedgame)
{
CONS_Printf(M_GetText("This command has been disabled in modified games, to prevent scripted attacks.\n"));
return;
}
if (COM_Argc() < 2)
{
CONS_Printf(M_GetText("dumplua <filename>: Compile a plain text lua script (not a wad!) into bytecode.\n"));
CONS_Alert(CONS_WARNING, M_GetText("This command makes irreversible file changes, please use with caution!\n"));
return;
}
LUA_DumpFile(COM_Argv(1));
}
#endif
void Command_Savecheckpoint_f(void)
{
REQUIRE_DEVMODE;
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
players[consoleplayer].starposttime = players[consoleplayer].realtime;
players[consoleplayer].starpostx = players[consoleplayer].mo->x>>FRACBITS;
players[consoleplayer].starposty = players[consoleplayer].mo->y>>FRACBITS;
players[consoleplayer].starpostz = players[consoleplayer].mo->floorz>>FRACBITS;
players[consoleplayer].starpostangle = players[consoleplayer].mo->angle;
CONS_Printf(M_GetText("Temporary checkpoint created at %d, %d, %d\n"), players[consoleplayer].starpostx, players[consoleplayer].starposty, players[consoleplayer].starpostz);
}
// Like M_GetAllEmeralds() but for console devmode junkies.
/*void Command_Getallemeralds_f(void)
{
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
REQUIRE_PANDORA;
emeralds = ((EMERALD7)*2)-1;
CONS_Printf(M_GetText("You now have all 7 emeralds.\n"));
}
void Command_Resetemeralds_f(void)
{
REQUIRE_SINGLEPLAYER;
REQUIRE_PANDORA;
emeralds = 0;
CONS_Printf(M_GetText("Emeralds reset to zero.\n"));
}*/
void Command_Devmode_f(void)
{
#ifndef _DEBUG
REQUIRE_SINGLEPLAYER;
#endif
REQUIRE_NOULTIMATE;
if (COM_Argc() > 1)
{
const char *arg = COM_Argv(1);
if (arg[0] && arg[0] == '0' &&
arg[1] && arg[1] == 'x') // Use hexadecimal!
cv_debug = axtoi(arg+2);
else
cv_debug = atoi(arg);
}
else
{
CONS_Printf(M_GetText("devmode <flags>: enable debugging tools and info, prepend with 0x to use hexadecimal\n"));
return;
}
G_SetGameModified(multiplayer, true);
}
/*void Command_Setrings_f(void)
{
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
REQUIRE_PANDORA;
if (COM_Argc() > 1)
{
// P_GivePlayerRings does value clamping
players[consoleplayer].health = players[consoleplayer].mo->health = 1;
P_GivePlayerRings(&players[consoleplayer], atoi(COM_Argv(1)));
if (!G_IsSpecialStage(gamemap) || !useNightsSS)
players[consoleplayer].totalring -= atoi(COM_Argv(1)); //undo totalring addition done in P_GivePlayerRings
G_SetGameModified(multiplayer);
}
}
void Command_Setlives_f(void)
{
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
REQUIRE_PANDORA;
if (COM_Argc() > 1)
{
// P_GivePlayerLives does value clamping
players[consoleplayer].lives = 0;
P_GivePlayerLives(&players[consoleplayer], atoi(COM_Argv(1)));
G_SetGameModified(multiplayer);
}
}
void Command_Setcontinues_f(void)
{
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
REQUIRE_PANDORA;
if (COM_Argc() > 1)
{
INT32 numcontinues = atoi(COM_Argv(1));
if (numcontinues > 99)
numcontinues = 99;
else if (numcontinues < 0)
numcontinues = 0;
players[consoleplayer].continues = numcontinues;
G_SetGameModified(multiplayer);
}
}*/
//
// OBJECTPLACE (and related variables)
//
static CV_PossibleValue_t op_mapthing_t[] = {{0, "MIN"}, {4095, "MAX"}, {0, NULL}};
static CV_PossibleValue_t op_speed_t[] = {{1, "MIN"}, {128, "MAX"}, {0, NULL}};
static CV_PossibleValue_t op_flags_t[] = {{0, "MIN"}, {15, "MAX"}, {0, NULL}};
consvar_t cv_mapthingnum = {"op_mapthingnum", "0", CV_NOTINNET, op_mapthing_t, NULL, 0, NULL, NULL, 0, 0, NULL};
consvar_t cv_speed = {"op_speed", "16", CV_NOTINNET, op_speed_t, NULL, 0, NULL, NULL, 0, 0, NULL};
consvar_t cv_opflags = {"op_flags", "0", CV_NOTINNET, op_flags_t, NULL, 0, NULL, NULL, 0, 0, NULL};
boolean objectplacing = false;
mobjtype_t op_currentthing = 0; // For the object placement mode
UINT16 op_currentdoomednum = 0; // For display, etc
UINT32 op_displayflags = 0; // for display in ST_stuff
static pflags_t op_oldpflags = 0;
static mobjflag_t op_oldflags1 = 0;
static mobjflag2_t op_oldflags2 = 0;
static UINT32 op_oldeflags = 0;
static fixed_t op_oldmomx = 0, op_oldmomy = 0, op_oldmomz = 0, op_oldheight = 0;
static statenum_t op_oldstate = 0;
static UINT8 op_oldcolor = 0;
//
// Static calculation / common output help
//
static void OP_CycleThings(INT32 amt)
{
INT32 add = (amt > 0 ? 1 : -1);
while (amt)
{
do
{
op_currentthing += add;
if (op_currentthing <= 0)
op_currentthing = NUMMOBJTYPES-1;
if (op_currentthing >= NUMMOBJTYPES)
op_currentthing = 0;
} while
(mobjinfo[op_currentthing].doomednum == -1
|| op_currentthing == MT_NIGHTSDRONE
|| mobjinfo[op_currentthing].flags & (MF_AMBIENT|MF_NOSECTOR)
|| (states[mobjinfo[op_currentthing].spawnstate].sprite == SPR_NULL
&& states[mobjinfo[op_currentthing].seestate].sprite == SPR_NULL)
);
amt -= add;
}
// HACK, minus has SPR_NULL sprite
if (states[mobjinfo[op_currentthing].spawnstate].sprite == SPR_NULL)
{
states[S_OBJPLACE_DUMMY].sprite = states[mobjinfo[op_currentthing].seestate].sprite;
states[S_OBJPLACE_DUMMY].frame = states[mobjinfo[op_currentthing].seestate].frame;
}
else
{
states[S_OBJPLACE_DUMMY].sprite = states[mobjinfo[op_currentthing].spawnstate].sprite;
states[S_OBJPLACE_DUMMY].frame = states[mobjinfo[op_currentthing].spawnstate].frame;
}
if (players[0].mo->eflags & MFE_VERTICALFLIP) // correct z when flipped
players[0].mo->z += players[0].mo->height - mobjinfo[op_currentthing].height;
players[0].mo->height = mobjinfo[op_currentthing].height;
P_SetPlayerMobjState(players[0].mo, S_OBJPLACE_DUMMY);
op_currentdoomednum = mobjinfo[op_currentthing].doomednum;
}
static boolean OP_HeightOkay(player_t *player, UINT8 ceiling)
{
sector_t *sec = player->mo->subsector->sector;
if (ceiling)
{
// Truncate position to match where mapthing would be when spawned
// (this applies to every further P_GetZAt call as well)
fixed_t cheight = sec->c_slope ? P_GetZAt(sec->c_slope, player->mo->x & 0xFFFF0000, player->mo->y & 0xFFFF0000) : sec->ceilingheight;
if (((cheight - player->mo->z - player->mo->height)>>FRACBITS) >= (1 << (16-ZSHIFT)))
{
CONS_Printf(M_GetText("Sorry, you're too %s to place this object (max: %d %s).\n"), M_GetText("low"),
(1 << (16-ZSHIFT)), M_GetText("below top ceiling"));
return false;
}
}
else
{
fixed_t fheight = sec->f_slope ? P_GetZAt(sec->f_slope, player->mo->x & 0xFFFF0000, player->mo->y & 0xFFFF0000) : sec->floorheight;
if (((player->mo->z - fheight)>>FRACBITS) >= (1 << (16-ZSHIFT)))
{
CONS_Printf(M_GetText("Sorry, you're too %s to place this object (max: %d %s).\n"), M_GetText("high"),
(1 << (16-ZSHIFT)), M_GetText("above bottom floor"));
return false;
}
}
return true;
}
static mapthing_t *OP_CreateNewMapThing(player_t *player, UINT16 type, boolean ceiling)
{
mapthing_t *mt = mapthings;
sector_t *sec = player->mo->subsector->sector;
#ifdef HAVE_BLUA
LUA_InvalidateMapthings();
#endif
mapthings = Z_Realloc(mapthings, ++nummapthings * sizeof (*mapthings), PU_LEVEL, NULL);
// as Z_Realloc can relocate mapthings, quickly go through thinker list and correct
// the spawnpoints of any objects that have them to the new location
if (mt != mapthings)
{
thinker_t *th;
mobj_t *mo;
for (th = thinkercap.next; th != &thinkercap; th = th->next)
{
if (th->function.acp1 != (actionf_p1)P_MobjThinker)
continue;
mo = (mobj_t *)th;
// get offset from mt, which points to old mapthings, then add new location
if (mo->spawnpoint)
mo->spawnpoint = (mo->spawnpoint - mt) + mapthings;
}
}
mt = (mapthings+nummapthings-1);
mt->type = type;
mt->x = (INT16)(player->mo->x>>FRACBITS);
mt->y = (INT16)(player->mo->y>>FRACBITS);
if (ceiling)
{
fixed_t cheight = sec->c_slope ? P_GetZAt(sec->c_slope, mt->x << FRACBITS, mt->y << FRACBITS) : sec->ceilingheight;
mt->options = (UINT16)((cheight - player->mo->z - player->mo->height)>>FRACBITS);
}
else
{
fixed_t fheight = sec->f_slope ? P_GetZAt(sec->f_slope, mt->x << FRACBITS, mt->y << FRACBITS) : sec->floorheight;
mt->options = (UINT16)((player->mo->z - fheight)>>FRACBITS);
}
mt->options <<= ZSHIFT;
mt->angle = (INT16)(FixedInt(AngleFixed(player->mo->angle)));
mt->options |= (UINT16)cv_opflags.value;
return mt;
}
//
// Helper functions
//
boolean OP_FreezeObjectplace(void)
{
if (!objectplacing)
return false;
if ((maptol & TOL_NIGHTS) && (players[consoleplayer].pflags & PF_NIGHTSMODE))
return false;
return true;
}
void OP_ResetObjectplace(void)
{
objectplacing = false;
op_currentthing = 0;
}
//
// Main meat of objectplace: handling functions
//
void OP_NightsObjectplace(player_t *player)
{
ticcmd_t *cmd = &player->cmd;
mapthing_t *mt;
player->nightstime = 3*TICRATE;
player->drillmeter = TICRATE;
if (player->pflags & PF_ATTACKDOWN)
{
// Are ANY objectplace buttons pressed? If no, remove flag.
if (!(cmd->buttons & (BT_ATTACK|BT_ACCELERATE|BT_BRAKE|BT_FORWARD|BT_BACKWARD)))
player->pflags &= ~PF_ATTACKDOWN;
// Do nothing.
return;
}
// This places a hoop!
if (cmd->buttons & BT_ATTACK)
{
UINT16 angle = (UINT16)(player->anotherflyangle % 360);
INT16 temp = (INT16)FixedInt(AngleFixed(player->mo->angle)); // Traditional 2D Angle
sector_t *sec = player->mo->subsector->sector;
fixed_t fheight = sec->f_slope ? P_GetZAt(sec->f_slope, player->mo->x & 0xFFFF0000, player->mo->y & 0xFFFF0000) : sec->floorheight;
player->pflags |= PF_ATTACKDOWN;
mt = OP_CreateNewMapThing(player, 1705, false);
// Tilt
mt->angle = (INT16)FixedInt(FixedDiv(angle*FRACUNIT, 360*(FRACUNIT/256)));
if (player->anotherflyangle < 90 || player->anotherflyangle > 270)
temp -= 90;
else
temp += 90;
temp %= 360;
mt->options = (UINT16)((player->mo->z - fheight)>>FRACBITS);
mt->angle = (INT16)(mt->angle+(INT16)((FixedInt(FixedDiv(temp*FRACUNIT, 360*(FRACUNIT/256))))<<8));
P_SpawnHoopsAndRings(mt);
}
// This places a bumper!
/*if (cmd->buttons & BT_SPECTATE)
{
player->pflags |= PF_ATTACKDOWN;
if (!OP_HeightOkay(player, false))
return;
mt = OP_CreateNewMapThing(player, (UINT16)mobjinfo[MT_NIGHTSBUMPER].doomednum, false);
P_SpawnMapThing(mt);
}*/
// This places a ring!
if (cmd->buttons & BT_BACKWARD)
{
player->pflags |= PF_ATTACKDOWN;
if (!OP_HeightOkay(player, false))
return;
mt = OP_CreateNewMapThing(player, (UINT16)mobjinfo[MT_RING].doomednum, false);
P_SpawnHoopsAndRings(mt);
}
// This places a wing item!
if (cmd->buttons & BT_FORWARD)
{
player->pflags |= PF_ATTACKDOWN;
if (!OP_HeightOkay(player, false))
return;
mt = OP_CreateNewMapThing(player, (UINT16)mobjinfo[MT_NIGHTSWING].doomednum, false);
P_SpawnHoopsAndRings(mt);
}
// This places a custom object as defined in the console cv_mapthingnum.
if (cmd->buttons & BT_BRAKE)
{
UINT16 angle;
player->pflags |= PF_ATTACKDOWN;
if (!cv_mapthingnum.value)
{
CONS_Alert(CONS_WARNING, "Set op_mapthingnum first!\n");
return;
}
if (!OP_HeightOkay(player, false))
return;
if (player->mo->target->flags2 & MF2_AMBUSH)
angle = (UINT16)player->anotherflyangle;
else
{
angle = (UINT16)((360-player->anotherflyangle) % 360);
if (angle > 90 && angle < 270)
{
angle += 180;
angle %= 360;
}
}
mt = OP_CreateNewMapThing(player, (UINT16)cv_mapthingnum.value, false);
mt->angle = angle;
if (mt->type == 300 // Ring
|| mt->type == 308 || mt->type == 309 // Team Rings
|| mt->type == 1706 // Nights Wing
|| (mt->type >= 600 && mt->type <= 609) // Placement patterns
|| mt->type == 1705 || mt->type == 1713 // NiGHTS Hoops
|| mt->type == 1800) // Mario Coin
{
P_SpawnHoopsAndRings(mt);
}
else
P_SpawnMapThing(mt);
}
}
//
// OP_ObjectplaceMovement
//
// Control code for Objectplace mode
//
void OP_ObjectplaceMovement(player_t *player)
{
ticcmd_t *cmd = &player->cmd;
if (!player->climbing && (netgame || !cv_analog.value || (player->pflags & PF_SPINNING)))
player->mo->angle = (cmd->angleturn<<16 /* not FRACBITS */);
ticruned++;
if (!(cmd->angleturn & TICCMD_RECEIVED))
ticmiss++;
if (cmd->buttons & BT_ACCELERATE)
player->mo->z += FRACUNIT*cv_speed.value;
else if (cmd->buttons & BT_BRAKE)
player->mo->z -= FRACUNIT*cv_speed.value;
if (cmd->forwardmove != 0)
{
P_Thrust(player->mo, player->mo->angle, (cmd->forwardmove*FRACUNIT/MAXPLMOVE)*cv_speed.value);
P_MoveOrigin(player->mo, player->mo->x+player->mo->momx, player->mo->y+player->mo->momy, player->mo->z);
player->mo->momx = player->mo->momy = 0;
}
/*if (cmd->sidemove != 0) -- was disabled in practice anyways, since sidemove was suppressed
{
P_Thrust(player->mo, player->mo->angle-ANGLE_90, (cmd->sidemove*FRACUNIT/MAXPLMOVE)*cv_speed.value);
P_MoveOrigin(player->mo, player->mo->x+player->mo->momx, player->mo->y+player->mo->momy, player->mo->z);
player->mo->momx = player->mo->momy = 0;
}*/
if (player->mo->z > player->mo->ceilingz - player->mo->height)
player->mo->z = player->mo->ceilingz - player->mo->height;
if (player->mo->z < player->mo->floorz)
player->mo->z = player->mo->floorz;
if (cv_opflags.value & MTF_OBJECTFLIP)
player->mo->eflags |= MFE_VERTICALFLIP;
else
player->mo->eflags &= ~MFE_VERTICALFLIP;
// make sure viewz follows player if in 1st person mode
//player->deltaviewheight = 0;
player->viewheight = FixedMul(32 << FRACBITS, player->mo->scale);
if (player->mo->eflags & MFE_VERTICALFLIP)
player->viewz = player->mo->z + player->mo->height - player->viewheight;
else
player->viewz = player->mo->z + player->viewheight;
// Display flag information
// Moved up so it always updates.
{
sector_t *sec = player->mo->subsector->sector;
if (!!(mobjinfo[op_currentthing].flags & MF_SPAWNCEILING) ^ !!(cv_opflags.value & MTF_OBJECTFLIP))
{
fixed_t cheight = sec->c_slope ? P_GetZAt(sec->c_slope, player->mo->x & 0xFFFF0000, player->mo->y & 0xFFFF0000) : sec->ceilingheight;
op_displayflags = (UINT16)((cheight - player->mo->z - mobjinfo[op_currentthing].height)>>FRACBITS);
}
else
{
fixed_t fheight = sec->f_slope ? P_GetZAt(sec->f_slope, player->mo->x & 0xFFFF0000, player->mo->y & 0xFFFF0000) : sec->floorheight;
op_displayflags = (UINT16)((player->mo->z - fheight)>>FRACBITS);
}
op_displayflags <<= ZSHIFT;
op_displayflags |= (UINT16)cv_opflags.value;
}
if (player->pflags & PF_ATTACKDOWN)
{
// Are ANY objectplace buttons pressed? If no, remove flag.
if (!(cmd->buttons & (BT_ATTACK|BT_DRIFT)))
player->pflags &= ~PF_ATTACKDOWN;
// Do nothing.
return;
}
/*if (cmd->buttons & BT_FORWARD)
{
OP_CycleThings(-1);
player->pflags |= PF_ATTACKDOWN;
}
else*/ if (cmd->buttons & BT_DRIFT)
{
OP_CycleThings(1);
player->pflags |= PF_ATTACKDOWN;
}
// Place an object and add it to the maplist
if (cmd->buttons & BT_ATTACK)
{
mapthing_t *mt;
mobjtype_t spawnmid = op_currentthing;
mobjtype_t spawnthing = op_currentdoomednum;
boolean ceiling;
player->pflags |= PF_ATTACKDOWN;
if (cv_mapthingnum.value > 0 && cv_mapthingnum.value < 4096)
{
// find which type to spawn
for (spawnmid = 0; spawnmid < NUMMOBJTYPES; ++spawnmid)
if (cv_mapthingnum.value == mobjinfo[spawnmid].doomednum)
break;
if (spawnmid == NUMMOBJTYPES)
{
CONS_Alert(CONS_ERROR, M_GetText("Can't place an object with mapthingnum %d.\n"), cv_mapthingnum.value);
return;
}
spawnthing = mobjinfo[spawnmid].doomednum;
}
ceiling = !!(mobjinfo[spawnmid].flags & MF_SPAWNCEILING) ^ !!(cv_opflags.value & MTF_OBJECTFLIP);
if (!OP_HeightOkay(player, ceiling))
return;
mt = OP_CreateNewMapThing(player, (UINT16)spawnthing, ceiling);
if (mt->type == 300 // Ring
|| mt->type == 308 || mt->type == 309 // Team Rings
|| mt->type == 1706 // Nights Wing
|| (mt->type >= 600 && mt->type <= 609) // Placement patterns
|| mt->type == 1705 || mt->type == 1713 // NiGHTS Hoops
|| mt->type == 1800) // Mario Coin
{
P_SpawnHoopsAndRings(mt);
}
else
P_SpawnMapThing(mt);
CONS_Printf(M_GetText("Placed object type %d at %d, %d, %d, %d\n"), mt->type, mt->x, mt->y, mt->options>>ZSHIFT, mt->angle);
}
}
//
// Objectplace related commands.
//
void Command_Writethings_f(void)
{
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_OBJECTPLACE;
P_WriteThings(W_GetNumForName(G_BuildMapName(gamemap)) + ML_THINGS);
}
void Command_ObjectPlace_f(void)
{
REQUIRE_INLEVEL;
REQUIRE_SINGLEPLAYER;
REQUIRE_NOULTIMATE;
G_SetGameModified(multiplayer, true);
// Entering objectplace?
if (!objectplacing)
{
objectplacing = true;
if ((players[0].pflags & PF_NIGHTSMODE))
return;
if (!COM_CheckParm("-silent"))
{
HU_SetCEchoFlags(V_RETURN8|V_MONOSPACE);
HU_SetCEchoDuration(10);
HU_DoCEcho(va(M_GetText(
"\\\\\\\\\\\\\\\\\\\\\\\\\x82"
" Objectplace Controls: \x80\\\\"
" Drift: Cycle mapthings\\"
"Accelerate: Float up \\"
" Brake: Float down \\"
" Item: Place object \\")));
}
// Save all the player's data.
op_oldflags1 = players[0].mo->flags;
op_oldflags2 = players[0].mo->flags2;
op_oldeflags = players[0].mo->eflags;
op_oldpflags = players[0].pflags;
op_oldmomx = players[0].mo->momx;
op_oldmomy = players[0].mo->momy;
op_oldmomz = players[0].mo->momz;
op_oldheight = players[0].mo->height;
op_oldstate = S_KART_STND1; // SRB2kart - was S_PLAY_STND
op_oldcolor = players[0].mo->color; // save color too in case of super/fireflower
// Remove ALL flags and motion.
P_UnsetThingPosition(players[0].mo);
players[0].pflags = 0;
players[0].mo->flags2 = 0;
players[0].mo->eflags = 0;
players[0].mo->flags = (MF_NOCLIP|MF_NOGRAVITY|MF_NOBLOCKMAP);
players[0].mo->momx = players[0].mo->momy = players[0].mo->momz = 0;
P_SetThingPosition(players[0].mo);
// Take away color so things display properly
players[0].mo->color = 0;
// Like the classics, recover from death by entering objectplace
if (players[0].mo->health <= 0)
{
players[0].mo->health = players[0].health = 1;
players[0].deadtimer = 0;
op_oldflags1 = mobjinfo[MT_PLAYER].flags;
++players[0].lives;
players[0].playerstate = PST_LIVE;
P_RestoreMusic(&players[0]);
}
else
op_oldstate = (statenum_t)(players[0].mo->state-states);
// If no thing set, then cycle a little
if (!op_currentthing)
{
op_currentthing = 1;
OP_CycleThings(1);
}
else // Cycle things sets this for the former.
players[0].mo->height = mobjinfo[op_currentthing].height;
P_SetPlayerMobjState(players[0].mo, S_OBJPLACE_DUMMY);
}
// Or are we leaving it instead?
else
{
objectplacing = false;
// Don't touch the NiGHTS Objectplace stuff.
// ... or if the mo mysteriously vanished.
if (!players[0].mo || (players[0].pflags & PF_NIGHTSMODE))
return;
// If still in dummy state, get out of it.
if (players[0].mo->state == &states[S_OBJPLACE_DUMMY])
P_SetPlayerMobjState(players[0].mo, op_oldstate);
// Reset everything back to how it was before we entered objectplace.
P_UnsetThingPosition(players[0].mo);
players[0].mo->flags = op_oldflags1;
players[0].mo->flags2 = op_oldflags2;
players[0].mo->eflags = op_oldeflags;
players[0].pflags = op_oldpflags;
players[0].mo->momx = op_oldmomx;
players[0].mo->momy = op_oldmomy;
players[0].mo->momz = op_oldmomz;
players[0].mo->height = op_oldheight;
P_SetThingPosition(players[0].mo);
// Return their color to normal.
players[0].mo->color = op_oldcolor;
// This is necessary for recovery of dying players.
if (players[0].powers[pw_flashing] >= K_GetKartFlashing(&players[0]))
players[0].powers[pw_flashing] = K_GetKartFlashing(&players[0]) - 1;
}
}
| 0 | 0.855211 | 1 | 0.855211 | game-dev | MEDIA | 0.972188 | game-dev | 0.830357 | 1 | 0.830357 |
fail4k/TW-Bot-Spammer | 23,299 | lib/snapshot.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Snapshot = exports.items = void 0;
const UUIDManager_1 = require("./UUIDManager");
const MsgUnpacker_1 = require("./MsgUnpacker");
var decoder = new TextDecoder('utf-8');
const ___itemAppendix = [
{ "type_id": 0, "size": 0, "name": "obj_ex" },
{ "type_id": 1, "size": 10, "name": "obj_player_input" },
{ "type_id": 2, "size": 6, "name": "obj_projectile" },
{ "type_id": 3, "size": 5, "name": "obj_laser" },
{ "type_id": 4, "size": 4, "name": "obj_pickup" },
{ "type_id": 5, "size": 3, "name": "obj_flag" },
{ "type_id": 6, "size": 8, "name": "obj_game_info" },
{ "type_id": 7, "size": 4, "name": "obj_game_data" },
{ "type_id": 8, "size": 15, "name": "obj_character_core" },
{ "type_id": 9, "size": 22, "name": "obj_character" },
{ "type_id": 10, "size": 5, "name": "obj_player_info" },
{ "type_id": 11, "size": 17, "name": "obj_client_info" },
{ "type_id": 12, "size": 3, "name": "obj_spectator_info" },
{ "type_id": 13, "size": 2, "name": "common" }, // event_common
{ "type_id": 14, "size": 2, "name": "explosion" }, // event_explosion
{ "type_id": 15, "size": 2, "name": "spawn" }, // event_spawn
{ "type_id": 16, "size": 2, "name": "hammerhit" }, // event_hammerhit
{ "type_id": 17, "size": 3, "name": "death" }, // event_death
{ "type_id": 18, "size": 3, "name": "sound_global" }, // event_sound_global
{ "type_id": 19, "size": 3, "name": "sound_world" }, // event_sound_world
{ "type_id": 20, "size": 3, "name": "damage_indicator" } // event_damage_indicator
];
const itemAppendix = [
0,
10,
6,
5,
4,
3,
8,
4,
15,
22,
5,
17,
3,
2,
2,
2,
2,
3,
3,
3,
3,
];
var items;
(function (items) {
items[items["OBJ_EX"] = 0] = "OBJ_EX";
items[items["OBJ_PLAYER_INPUT"] = 1] = "OBJ_PLAYER_INPUT";
items[items["OBJ_PROJECTILE"] = 2] = "OBJ_PROJECTILE";
items[items["OBJ_LASER"] = 3] = "OBJ_LASER";
items[items["OBJ_PICKUP"] = 4] = "OBJ_PICKUP";
items[items["OBJ_FLAG"] = 5] = "OBJ_FLAG";
items[items["OBJ_GAME_INFO"] = 6] = "OBJ_GAME_INFO";
items[items["OBJ_GAME_DATA"] = 7] = "OBJ_GAME_DATA";
items[items["OBJ_CHARACTER_CORE"] = 8] = "OBJ_CHARACTER_CORE";
items[items["OBJ_CHARACTER"] = 9] = "OBJ_CHARACTER";
items[items["OBJ_PLAYER_INFO"] = 10] = "OBJ_PLAYER_INFO";
items[items["OBJ_CLIENT_INFO"] = 11] = "OBJ_CLIENT_INFO";
items[items["OBJ_SPECTATOR_INFO"] = 12] = "OBJ_SPECTATOR_INFO";
items[items["EVENT_COMMON"] = 13] = "EVENT_COMMON";
items[items["EVENT_EXPLOSION"] = 14] = "EVENT_EXPLOSION";
items[items["EVENT_SPAWN"] = 15] = "EVENT_SPAWN";
items[items["EVENT_HAMMERHIT"] = 16] = "EVENT_HAMMERHIT";
items[items["EVENT_DEATH"] = 17] = "EVENT_DEATH";
items[items["EVENT_SOUND_GLOBAL"] = 18] = "EVENT_SOUND_GLOBAL";
items[items["EVENT_SOUND_WORLD"] = 19] = "EVENT_SOUND_WORLD";
items[items["EVENT_DAMAGE_INDICATOR"] = 20] = "EVENT_DAMAGE_INDICATOR";
})(items || (exports.items = items = {}));
// https://github.com/ddnet/ddnet/blob/571b0b36de83d18f2524ee371fc3223d04b94135/datasrc/network.py#L236
let supported_uuids = [
"my-own-object@heinrich5991.de",
"character@netobj.ddnet.tw", // validate_size=False
"player@netobj.ddnet.tw",
"gameinfo@netobj.ddnet.tw", // validate_size=False
"projectile@netobj.ddnet.tw",
"laser@netobj.ddnet.tw",
];
class Snapshot {
constructor(_client) {
this.deltas = [];
this.eSnapHolder = [];
this.crc_errors = 0;
this.uuid_manager = new UUIDManager_1.UUIDManager(32767, true); // snapshot max_type
this.client = _client;
}
IntsToStr(pInts) {
var pIntz = [];
// var pStr = ''
for (let x of pInts) {
// pStr += String.fromCharCode((((x) >> 24) & 0xff) - 128);
pIntz.push((((x) >> 24) & 0xff) - 128);
// pStr += String.fromCharCode((((x) >> 16) & 0xff) - 128);
pIntz.push((((x) >> 16) & 0xff) - 128);
// pStr += String.fromCharCode((((x) >> 8) & 0xff) - 128);
pIntz.push((((x) >> 8) & 0xff) - 128);
// pStr += String.fromCharCode(((x) & 0xff) - 128);
pIntz.push(((x) & 0xff) - 128);
}
pIntz.splice(-1, 1);
let pStr = decoder.decode(new Uint8Array(pIntz));
pStr = pStr.replace(/\0.*/g, ''); // Remove content from first null char to end.
return pStr;
}
parseItem(data, Type, id) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
var _item = {};
if (Type >= 0x4000) { // offset uuid type
if (((_a = this.uuid_manager.LookupType(Type)) === null || _a === void 0 ? void 0 : _a.name) == "my-own-object@heinrich5991.de") {
_item = {
m_Test: data[0]
};
}
else if (((_b = this.uuid_manager.LookupType(Type)) === null || _b === void 0 ? void 0 : _b.name) == "character@netobj.ddnet.tw") {
_item = {
m_Flags: data[0],
m_FreezeEnd: data[1],
m_Jumps: data[2],
m_TeleCheckpoint: data[3],
m_StrongWeakID: data[4],
// # New data fields for jump display, freeze bar and ninja bar
// # Default values indicate that these values should not be used
m_JumpedTotal: (_c = data[5]) !== null && _c !== void 0 ? _c : null,
m_NinjaActivationTick: (_d = data[6]) !== null && _d !== void 0 ? _d : null,
m_FreezeStart: (_e = data[7]) !== null && _e !== void 0 ? _e : null,
// # New data fields for improved target accuracy
m_TargetX: (_f = data[8]) !== null && _f !== void 0 ? _f : null,
m_TargetY: (_g = data[9]) !== null && _g !== void 0 ? _g : null,
id: id
};
}
else if (((_h = this.uuid_manager.LookupType(Type)) === null || _h === void 0 ? void 0 : _h.name) == "player@netobj.ddnet.tw") {
_item = {
m_Flags: data[0],
m_AuthLevel: data[1],
id: id
};
}
else if (((_j = this.uuid_manager.LookupType(Type)) === null || _j === void 0 ? void 0 : _j.name) == "gameinfo@netobj.ddnet.tw") {
_item = {
m_Flags: data[0],
m_Version: data[1],
m_Flags2: data[2]
};
}
else if (((_k = this.uuid_manager.LookupType(Type)) === null || _k === void 0 ? void 0 : _k.name) == "projectile@netobj.ddnet.tw") {
_item = {
m_X: data[0],
m_Y: data[1],
m_Angle: data[2],
m_Data: data[3],
m_Type: data[3],
m_StartTick: data[3]
};
}
else if (((_l = this.uuid_manager.LookupType(Type)) === null || _l === void 0 ? void 0 : _l.name) == "laser@netobj.ddnet.tw") {
_item = {
m_ToX: data[0],
m_ToY: data[1],
m_FromX: data[2],
m_FromY: data[3],
m_Owner: data[3],
m_Type: data[3]
};
}
return _item;
}
switch (Type) {
case items.OBJ_EX:
break;
case items.OBJ_PLAYER_INPUT:
_item = {
direction: data[0],
target_x: data[1],
target_y: data[2],
jump: data[3],
fire: data[4],
hook: data[5],
player_flags: data[6],
wanted_weapon: data[7],
next_weapon: data[8],
prev_weapon: data[9],
};
break;
case items.OBJ_PROJECTILE:
_item = {
x: data[0],
y: data[1],
vel_x: data[2],
vel_y: data[3],
type_: data[4],
start_tick: data[5],
};
break;
case items.OBJ_LASER:
_item = {
x: data[0],
y: data[1],
from_x: data[2],
from_y: data[3],
start_tick: data[4],
};
break;
case items.OBJ_PICKUP:
_item = {
x: data[0],
y: data[1],
type_: data[2],
subtype: data[3],
};
break;
case items.OBJ_FLAG:
_item = {
x: data[0],
y: data[1],
team: data[2],
};
break;
case items.OBJ_GAME_INFO:
_item = {
game_flags: data[0],
game_state_flags: data[1],
round_start_tick: data[2],
warmup_timer: data[3],
score_limit: data[4],
time_limit: data[5],
round_num: data[6],
round_current: data[7],
};
break;
case items.OBJ_GAME_DATA:
_item = {
teamscore_red: data[0],
teamscore_blue: data[1],
flag_carrier_red: data[2],
flag_carrier_blue: data[3],
};
break;
case items.OBJ_CHARACTER_CORE:
_item = {
tick: data[0],
x: data[1],
y: data[2],
vel_x: data[3],
vel_y: data[4],
angle: data[5],
direction: data[6],
jumped: data[7],
hooked_player: data[8],
hook_state: data[9],
hook_tick: data[10],
hook_x: data[11],
hook_y: data[12],
hook_dx: data[13],
hook_dy: data[14],
};
break;
case items.OBJ_CHARACTER:
_item = {
character_core: {
tick: data[0],
x: data[1],
y: data[2],
vel_x: data[3],
vel_y: data[4],
angle: data[5],
direction: data[6],
jumped: data[7],
hooked_player: data[8],
hook_state: data[9],
hook_tick: data[10],
hook_x: data[11],
hook_y: data[12],
hook_dx: data[13],
hook_dy: data[14],
},
player_flags: data[15],
health: data[16],
armor: data[17],
ammo_count: data[18],
weapon: data[19],
emote: data[20],
attack_tick: data[21],
client_id: id
};
break;
case items.OBJ_PLAYER_INFO:
_item = {
local: data[0],
client_id: data[1],
team: data[2],
score: data[3],
latency: data[4],
};
break;
case items.OBJ_CLIENT_INFO:
_item = {
name: this.IntsToStr([data[0], data[1], data[2], data[3]]),
clan: this.IntsToStr([data[4], data[5], data[6]]),
country: data[7],
skin: this.IntsToStr([data[8], data[9], data[10], data[11], data[12], data[13]]),
use_custom_color: Number(data.slice(14, 15)),
color_body: Number(data.slice(15, 16)),
color_feet: Number(data.slice(16, 17)),
id: id
};
break;
case items.OBJ_SPECTATOR_INFO:
_item = {
spectator_id: data[0],
x: data[1],
y: data[2],
};
break;
case items.EVENT_COMMON:
_item = {
x: data[0],
y: data[1],
};
break;
case items.EVENT_EXPLOSION:
_item = {
common: {
x: data[0],
y: data[1]
}
};
break;
case items.EVENT_SPAWN:
_item = {
common: {
x: data[0],
y: data[1]
}
};
break;
case items.EVENT_HAMMERHIT:
_item = {
common: {
x: data[0],
y: data[1]
}
};
break;
case items.EVENT_DEATH:
_item = {
client_id: data[0],
common: {
x: data[1],
y: data[2]
}
};
break;
case items.EVENT_SOUND_GLOBAL:
_item = {
common: {
x: data[0],
y: data[1]
},
sound_id: data[2]
};
break;
case items.EVENT_SOUND_WORLD:
_item = {
common: {
x: data[0],
y: data[1]
},
sound_id: data[2]
};
break;
case items.EVENT_DAMAGE_INDICATOR:
_item = {
angle: data[0],
common: {
x: data[0],
y: data[1]
},
};
break;
}
return _item;
}
crc() {
var checksum = 0;
// this.eSnapHolder.forEach(snap => {
// if (snap.ack == tick)
// snap.Snapshot.Data.forEach(el => checksum += el);
// })
this.deltas.forEach(snap => {
// if (snap.ack == tick)
snap.data.forEach(el => checksum += el);
});
return checksum & 0xffffffff;
}
unpackSnapshot(snap, deltatick, recvTick, WantedCrc) {
let unpacker = new MsgUnpacker_1.MsgUnpacker(snap);
let deltaSnaps = [];
if (deltatick == -1) {
this.eSnapHolder = [];
this.deltas = [];
}
else {
this.eSnapHolder = this.eSnapHolder.filter(a => {
if (a.ack == deltatick)
deltaSnaps.push(a);
return a.ack >= deltatick;
});
}
if (snap.length == 0) {
// empty snap, copy old one into new ack
this.eSnapHolder.forEach(snap => {
if (snap.ack == deltatick)
this.eSnapHolder.push({ Snapshot: snap.Snapshot, ack: recvTick });
});
return { items: [], recvTick: recvTick };
}
let oldDeltas = this.deltas;
this.deltas = [];
/* key = (((type_id) << 16) | (id))
* key_to_id = ((key) & 0xffff)
* key_to_type_id = ((key >> 16) & 0xffff)
* https://github.com/heinrich5991/libtw2/blob/master/snapshot/src/
* https://github.com/heinrich5991/libtw2/blob/master/doc/snapshot.md
*/
var _events = [];
let num_removed_items = unpacker.unpackInt();
let num_item_deltas = unpacker.unpackInt();
unpacker.unpackInt(); // _zero padding
/*snapshot_delta:
[ 4] num_removed_items
[ 4] num_item_deltas
[ 4] _zero
[*4] removed_item_keys
[ ] item_deltas
*/
var deleted = [];
for (let i = 0; i < num_removed_items; i++) {
let deleted_key = unpacker.unpackInt(); // removed_item_keys
deleted.push(deleted_key);
}
/*item_delta:
[ 4] type_id
[ 4] id
[ 4] _size
[*4] data_delta*/
// let items: {'items': {'data': number[], 'type_id': number, 'id': number, 'key': number}[]/*, 'client_infos': client_info[], 'player_infos': player_info[]*/, lost: number} = {items: [],/* client_infos: client_infos, player_infos: player_infos,*/ lost: 0};
// let deltaSnaps = this.eSnapHolder.filter(a => a.ack === deltatick);
if (deltaSnaps.length == 0 && deltatick >= 0) {
return { items: [], recvTick: -1 };
}
for (let i = 0; i < num_item_deltas; i++) {
let type_id = unpacker.unpackInt();
let id = unpacker.unpackInt();
const key = (((type_id) << 16) | (id));
let _size;
if (type_id > 0 && type_id < itemAppendix.length) {
_size = itemAppendix[type_id];
}
else
_size = unpacker.unpackInt();
let data = [];
for (let j = 0; j < _size; j++) {
// if (unpacker.remaining.length > 0) {
data[j] = (unpacker.unpackInt());
// } else console.log(_size, "???")
}
let changed = false;
if (deltatick >= 0) {
// let index = deltaSnaps.map(delta => delta.Snapshot.Key).indexOf(key)
let delta = deltaSnaps.find(delta => delta.Snapshot.Key === key);
if (delta !== undefined) {
let out = UndiffItem(delta.Snapshot.Data, data);
data = out;
changed = true;
} // else no previous, use new data
}
let parsed;
if (type_id !== 0) {
if (!changed) {
let oldDelta = oldDeltas.find(delta => delta.key == key);
if (oldDelta !== undefined && compareArrays(data, oldDelta.data)) {
parsed = oldDelta.parsed;
}
else
parsed = this.parseItem(data, type_id, id);
}
else
parsed = this.parseItem(data, type_id, id);
this.eSnapHolder.push({ Snapshot: { Data: data, Key: key }, ack: recvTick });
this.deltas.push({
data,
key,
id,
type_id,
parsed
});
if (type_id >= items.EVENT_COMMON && type_id <= items.EVENT_DAMAGE_INDICATOR) {
// this.client.SnapshotUnpacker.
_events.push({ type_id, parsed });
// this.client.SnapshotUnpacker.emit(___itemAppendix[type_id].name, parsed);
}
}
else {
this.eSnapHolder.push({ Snapshot: { Data: data, Key: key }, ack: recvTick });
this.deltas.push({
data,
key,
id,
type_id,
parsed: {}
});
let test = (int) => [(int >> 24) & 0xff, (int >> 16) & 0xff, (int >> 8) & 0xff, (int) & 0xff];
let test2 = (ints) => ints.map(a => test(a)).flat();
let targetUUID = Buffer.from(test2(data));
if (!this.uuid_manager.LookupType(id)) {
supported_uuids.forEach((a, i) => {
let uuid = (0, UUIDManager_1.createTwMD5Hash)(a);
if (targetUUID.compare(uuid) == 0) {
this.uuid_manager.RegisterName(a, id);
supported_uuids.splice(i, 1);
}
});
}
}
}
for (let newSnap of deltaSnaps) {
if (deleted.includes(newSnap.Snapshot.Key)) {
continue;
}
if (this.eSnapHolder.findIndex(a => a.ack == recvTick && a.Snapshot.Key == newSnap.Snapshot.Key) === -1) { // ugly copy new snap to eSnapHolder (if it isnt pushed already)
this.eSnapHolder.push({ Snapshot: { Data: newSnap.Snapshot.Data, Key: newSnap.Snapshot.Key }, ack: recvTick });
let oldDelta = oldDeltas.find(delta => delta.key == newSnap.Snapshot.Key);
if (oldDelta !== undefined && compareArrays(newSnap.Snapshot.Data, oldDelta.data)) {
this.deltas.push(oldDelta);
}
else {
this.deltas.push({
data: newSnap.Snapshot.Data,
key: newSnap.Snapshot.Key,
id: newSnap.Snapshot.Key & 0xffff,
type_id: ((newSnap.Snapshot.Key >> 16) & 0xffff),
parsed: this.parseItem(newSnap.Snapshot.Data, ((newSnap.Snapshot.Key >> 16) & 0xffff), ((newSnap.Snapshot.Key) & 0xffff))
});
}
}
}
let _crc = this.crc();
if (_crc !== WantedCrc) {
this.deltas = oldDeltas;
this.crc_errors++;
if (this.crc_errors > 5) {
recvTick = -1;
this.crc_errors = 0;
this.eSnapHolder = [];
this.deltas = [];
}
else {
recvTick = deltatick;
}
}
else if (this.crc_errors > 0)
this.crc_errors--;
_events.forEach(a => this.client.SnapshotUnpacker.emit(___itemAppendix[a.type_id].name, a.parsed));
return { items: this.deltas, recvTick };
}
}
exports.Snapshot = Snapshot;
function compareArrays(first, second) {
if (first.length !== second.length)
return false;
for (var i = 0; i < first.length; i++) {
if (first[i] !== second[i])
return false;
}
return true;
}
function UndiffItem(oldItem, newItem) {
let out = newItem;
// if (JSON.stringify(newItem) === JSON.stringify(oldItem))
// return newItem;
oldItem.forEach((a, i) => {
if (a !== undefined && out[i] !== undefined) {
out[i] += a;
}
else {
out[i] = 0;
}
});
return out;
}
| 0 | 0.834035 | 1 | 0.834035 | game-dev | MEDIA | 0.856835 | game-dev | 0.8234 | 1 | 0.8234 |
kbengine/unity3d_nav_critterai | 4,663 | sources/src/main/Assets/CAI/nav/CrowdProximityGrid.cs | /*
* Copyright (c) 2011 Stephen A. Pratt
*
* 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.
*/
using System;
using org.critterai.nav.rcn;
using org.critterai.interop;
namespace org.critterai.nav
{
/// <summary>
/// Represents proximity data generated by a <see cref="CrowdManager"/> object during
/// its update method.
/// </summary>
/// <remarks>
/// <para>
/// Objects of this type can only be obtained from a <see cref="CrowdManager"/> object.
/// </para>
/// <code>
/// // Example: Iterating the proximity data.
///
/// // Where 'grid' is a CrowdProximityGrid object.
///
/// int[] bounds = new int[4];
/// grid.GetBounds(bounds);
/// float cs = grid.GetCellSize();
///
/// for (int y = bounds[1]; y <= bounds[3]; ++y)
/// {
/// // y-bounds of the cell in world units.
/// float minY = y * cs;
/// float maxY = y * cs + cs;
/// for (int x = bounds[0]; x <= bounds[2]; ++x)
/// {
/// int count = grid->getItemCountAt(x, y);
/// // x-bounds of the cell in world units.
/// float minX = x * cs;
/// float maxX = x * cs + cs;
/// }
/// }
/// </code>
/// <para>
/// Behavior is undefined if used after disposal.
/// </para>
/// </remarks>
public sealed class CrowdProximityGrid
{
private IntPtr root;
private bool mIsDisposed = false;
internal CrowdProximityGrid(IntPtr grid)
{
root = grid;
}
/// <summary>
/// Destructor
/// </summary>
~CrowdProximityGrid()
{
Dispose();
}
internal void Dispose()
{
root = IntPtr.Zero;
mIsDisposed = true;
}
/// <summary>
/// True if the object has been disposed.
/// </summary>
public bool IsDisposed
{
get { return mIsDisposed; }
}
/// <summary>
/// The item count at the specified grid location.
/// </summary>
/// <param name="x">
/// The x-value of the grid location. [Limits: bounds[0] <= value <= bounds[2]]
/// </param>
/// <param name="y">
/// The y-value of the grid location. [Limits: bounds[1] <= value <= bounds[3]]
/// </param>
/// <returns>The item count at the specified grid location.</returns>
public int GetItemCountAt(int x, int y)
{
if (IsDisposed)
return -1;
return CrowdProximityGridEx.dtpgGetItemCountAt(root, x, y);
}
/// <summary>
/// The cell size of the grid.
/// </summary>
/// <remarks>
/// <para>
/// Used for converting from grid units to world units.
/// </para>
/// </remarks>
/// <returns>The cell size of the grid.</returns>
public float GetCellSize()
{
if (IsDisposed)
return -1;
return CrowdProximityGridEx.dtpgGetCellSize(root);
}
/// <summary>
/// Gets the bounds of the grid. [(minX, minY, maxX, maxY)]
/// </summary>
/// <remarks>
/// To convert from grid units to world units, multipy by the grid's cell size.
/// </remarks>
/// <returns>The bounds of the grid.</returns>
public int[] GetBounds()
{
if (IsDisposed)
return null;
int[] bounds = new int[4];
CrowdProximityGridEx.dtpgGetBounds(root, bounds);
return bounds;
}
}
}
| 0 | 0.944374 | 1 | 0.944374 | game-dev | MEDIA | 0.80337 | game-dev | 0.949535 | 1 | 0.949535 |
lzk228/space-axolotl-14 | 24,405 | Content.Shared/Tag/TagSystem.cs | using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
namespace Content.Shared.Tag;
/// <summary>
/// The system that is responsible for working with tags.
/// Checking the existence of the <see cref="TagPrototype"/> only happens in DEBUG builds,
/// to improve performance, so don't forget to check it.
/// </summary>
/// <summary>
/// The methods to add or remove a list of tags have only an implementation with the <see cref="IEnumerable{T}"/> type,
/// it's not much, but it takes away performance,
/// if you need to use them often, it's better to make a proper implementation,
/// you can read more <a href="https://github.com/space-wizards/space-station-14/pull/28272">HERE</a>.
/// </summary>
public sealed class TagSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _proto = default!;
private EntityQuery<TagComponent> _tagQuery;
public override void Initialize()
{
base.Initialize();
_tagQuery = GetEntityQuery<TagComponent>();
#if DEBUG
SubscribeLocalEvent<TagComponent, ComponentInit>(OnTagInit);
#endif
}
#if DEBUG
private void OnTagInit(EntityUid uid, TagComponent component, ComponentInit args)
{
foreach (var tag in component.Tags)
{
AssertValidTag(tag);
}
}
#endif
/// <summary>
/// Tries to add a tag to an entity if the tag doesn't already exist.
/// </summary>
/// <returns>
/// true if it was added, false otherwise even if it already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool AddTag(EntityUid entityUid, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
return AddTag((entityUid, EnsureComp<TagComponent>(entityUid)), tag);
}
/// <summary>
/// Tries to add the given tags to an entity if the tags don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false otherwise even if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool AddTags(EntityUid entityUid, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return AddTags(entityUid, (IEnumerable<ProtoId<TagPrototype>>)tags);
}
/// <summary>
/// Tries to add the given tags to an entity if the tags don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false otherwise even if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool AddTags(EntityUid entityUid, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
return AddTags((entityUid, EnsureComp<TagComponent>(entityUid)), tags);
}
/// <summary>
/// Tries to add a tag to an entity if it has a <see cref="TagComponent"/>
/// and the tag doesn't already exist.
/// </summary>
/// <returns>
/// true if it was added, false otherwise even if it already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool TryAddTag(EntityUid entityUid, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
return _tagQuery.TryComp(entityUid, out var component) &&
AddTag((entityUid, component), tag);
}
/// <summary>
/// Tries to add the given tags to an entity if it has a
/// <see cref="TagComponent"/> and the tags don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false otherwise even if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool TryAddTags(EntityUid entityUid, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return TryAddTags(entityUid, (IEnumerable<ProtoId<TagPrototype>>)tags);
}
/// <summary>
/// Tries to add the given tags to an entity if it has a
/// <see cref="TagComponent"/> and the tags don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false otherwise even if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool TryAddTags(EntityUid entityUid, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
AddTags((entityUid, component), tags);
}
/// <summary>
/// Checks if a tag has been added to an entity.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasTag(EntityUid entityUid, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasTag(component, tag);
}
/// <summary>
/// Checks if a tag has been added to an entity.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasAllTags(EntityUid entityUid, ProtoId<TagPrototype> tag) =>
HasTag(entityUid, tag);
/// <summary>
/// Checks if all of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(EntityUid entityUid, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAllTags(component, tags);
}
/// <summary>
/// Checks if all of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(EntityUid entityUid, [ForbidLiteral] HashSet<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAllTags(component, tags);
}
/// <summary>
/// Checks if all of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(EntityUid entityUid, [ForbidLiteral] List<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAllTags(component, tags);
}
/// <summary>
/// Checks if all of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(EntityUid entityUid, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAllTags(component, tags);
}
/// <summary>
/// Checks if a tag has been added to an entity.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasAnyTag(EntityUid entityUid, [ForbidLiteral] ProtoId<TagPrototype> tag) =>
HasTag(entityUid, tag);
/// <summary>
/// Checks if any of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(EntityUid entityUid, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAnyTag(component, tags);
}
/// <summary>
/// Checks if any of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(EntityUid entityUid, [ForbidLiteral] HashSet<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAnyTag(component, tags);
}
/// <summary>
/// Checks if any of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(EntityUid entityUid, [ForbidLiteral] List<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAnyTag(component, tags);
}
/// <summary>
/// Checks if any of the given tags have been added to an entity.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(EntityUid entityUid, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
HasAnyTag(component, tags);
}
/// <summary>
/// Checks if a tag has been added to an component.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasTag(TagComponent component, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
#if DEBUG
AssertValidTag(tag);
#endif
return component.Tags.Contains(tag);
}
/// <summary>
/// Checks if a tag has been added to an component.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasAllTags(TagComponent component, [ForbidLiteral] ProtoId<TagPrototype> tag) =>
HasTag(component, tag);
/// <summary>
/// Checks if all of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(TagComponent component, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!component.Tags.Contains(tag))
return false;
}
return true;
}
/// <summary>
/// Checks if all of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTagsArray(TagComponent component, [ForbidLiteral] ProtoId<TagPrototype>[] tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!component.Tags.Contains(tag))
return false;
}
return true;
}
/// <summary>
/// Checks if all of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(TagComponent component, [ForbidLiteral] List<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!component.Tags.Contains(tag))
return false;
}
return true;
}
/// <summary>
/// Checks if all of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(TagComponent component, [ForbidLiteral] HashSet<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!component.Tags.Contains(tag))
return false;
}
return true;
}
/// <summary>
/// Checks if all of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if they all exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAllTags(TagComponent component, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!component.Tags.Contains(tag))
return false;
}
return true;
}
/// <summary>
/// Checks if a tag has been added to an component.
/// </summary>
/// <returns>
/// true if it exists, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool HasAnyTag(TagComponent component, [ForbidLiteral] ProtoId<TagPrototype> tag) =>
HasTag(component, tag);
/// <summary>
/// Checks if any of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(TagComponent component, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (component.Tags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// Checks if any of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(TagComponent component, [ForbidLiteral] HashSet<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (component.Tags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// Checks if any of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(TagComponent component, [ForbidLiteral] List<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (component.Tags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// Checks if any of the given tags have been added to an component.
/// </summary>
/// <returns>
/// true if any of them exist, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool HasAnyTag(TagComponent component, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (component.Tags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// Tries to remove a tag from an entity if it exists.
/// </summary>
/// <returns>
/// true if it was removed, false otherwise even if it didn't exist.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool RemoveTag(EntityUid entityUid, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
return _tagQuery.TryComp(entityUid, out var component) &&
RemoveTag((entityUid, component), tag);
}
/// <summary>
/// Tries to remove a tag from an entity if it exists.
/// </summary>
/// <returns>
/// true if it was removed, false otherwise even if it didn't exist.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool RemoveTags(EntityUid entityUid, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return RemoveTags(entityUid, (IEnumerable<ProtoId<TagPrototype>>)tags);
}
/// <summary>
/// Tries to remove a tag from an entity if it exists.
/// </summary>
/// <returns>
/// true if it was removed, false otherwise even if it didn't exist.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool RemoveTags(EntityUid entityUid, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
return _tagQuery.TryComp(entityUid, out var component) &&
RemoveTags((entityUid, component), tags);
}
/// <summary>
/// Tries to add a tag if it doesn't already exist.
/// </summary>
/// <returns>
/// true if it was added, false if it already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool AddTag(Entity<TagComponent> entity, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!entity.Comp.Tags.Add(tag))
return false;
Dirty(entity);
return true;
}
/// <summary>
/// Tries to add the given tags if they don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool AddTags(Entity<TagComponent> entity, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return AddTags(entity, (IEnumerable<ProtoId<TagPrototype>>)tags);
}
/// <summary>
/// Tries to add the given tags if they don't already exist.
/// </summary>
/// <returns>
/// true if any tags were added, false if they all already existed.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool AddTags(Entity<TagComponent> entity, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
var update = false;
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (entity.Comp.Tags.Add(tag) && !update)
update = true;
}
if (!update)
return false;
Dirty(entity);
return true;
}
/// <summary>
/// Tries to remove a tag if it exists.
/// </summary>
/// <returns>
/// true if it was removed, false otherwise even if it didn't exist.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if no <see cref="TagPrototype"/> exists with the given id.
/// </exception>
public bool RemoveTag(Entity<TagComponent> entity, [ForbidLiteral] ProtoId<TagPrototype> tag)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (!entity.Comp.Tags.Remove(tag))
return false;
Dirty(entity);
return true;
}
/// <summary>
/// Tries to remove all of the given tags if they exist.
/// </summary>
/// <returns>
/// true if any tag was removed, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool RemoveTags(Entity<TagComponent> entity, [ForbidLiteral] params ProtoId<TagPrototype>[] tags)
{
return RemoveTags(entity, (IEnumerable<ProtoId<TagPrototype>>)tags);
}
/// <summary>
/// Tries to remove all of the given tags if they exist.
/// </summary>
/// <returns>
/// true if any tag was removed, false otherwise.
/// </returns>
/// <exception cref="UnknownPrototypeException">
/// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>.
/// </exception>
public bool RemoveTags(Entity<TagComponent> entity, [ForbidLiteral] IEnumerable<ProtoId<TagPrototype>> tags)
{
var update = false;
foreach (var tag in tags)
{
#if DEBUG
AssertValidTag(tag);
#endif
if (entity.Comp.Tags.Remove(tag) && !update)
update = true;
}
if (!update)
return false;
Dirty(entity);
return true;
}
private void AssertValidTag(string id)
{
DebugTools.Assert(_proto.HasIndex<TagPrototype>(id), $"Unknown tag: {id}");
}
}
| 0 | 0.830958 | 1 | 0.830958 | game-dev | MEDIA | 0.731548 | game-dev | 0.629077 | 1 | 0.629077 |
jarjin/SimpleFramework_UGUI | 31,649 | Assets/uLua/Core/Lua.cs | //#if UNITY_IPHONE
#define __NOGEN__
//#endif
namespace LuaInterface
{
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using UnityEngine;
using SimpleFramework;
public class LuaState : IDisposable
{
public IntPtr L;
internal LuaCSFunction tracebackFunction;
internal ObjectTranslator translator;
internal LuaCSFunction panicCallback;
// Overrides
internal LuaCSFunction printFunction;
internal LuaCSFunction loadfileFunction;
internal LuaCSFunction loaderFunction;
internal LuaCSFunction dofileFunction;
internal LuaCSFunction import_wrapFunction;
public LuaState()
{
// Create State
L = LuaDLL.luaL_newstate();
// Create LuaInterface library
LuaDLL.luaL_openlibs(L);
LuaDLL.lua_pushstring(L, "LUAINTERFACE LOADED");
LuaDLL.lua_pushboolean(L, true);
LuaDLL.lua_settable(L, (int)LuaIndexes.LUA_REGISTRYINDEX);
LuaDLL.lua_newtable(L);
LuaDLL.lua_setglobal(L, "luanet");
LuaDLL.lua_pushvalue(L, (int)LuaIndexes.LUA_GLOBALSINDEX); //压入了_G表
LuaDLL.lua_getglobal(L, "luanet");
LuaDLL.lua_pushstring(L, "getmetatable");
LuaDLL.lua_getglobal(L, "getmetatable");
LuaDLL.lua_settable(L, -3);
LuaDLL.lua_pushstring(L, "rawget");
LuaDLL.lua_getglobal(L, "rawget");
LuaDLL.lua_settable(L, -3);
LuaDLL.lua_pushstring(L, "rawset");
LuaDLL.lua_getglobal(L, "rawset");
LuaDLL.lua_settable(L, -3);
// Set luanet as global for object translator
LuaDLL.lua_replace(L, (int)LuaIndexes.LUA_GLOBALSINDEX); //用luanet替换_G表
translator = new ObjectTranslator(this, L);
LuaDLL.lua_replace(L, (int)LuaIndexes.LUA_GLOBALSINDEX); //恢复_G表
translator.PushTranslator(L);
// We need to keep this in a managed reference so the delegate doesn't get garbage collected
panicCallback = new LuaCSFunction(LuaStatic.panic);
LuaDLL.lua_atpanic(L, panicCallback);
printFunction = new LuaCSFunction(LuaStatic.print);
LuaDLL.lua_pushstdcallcfunction(L, printFunction);
LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "print");
loadfileFunction = new LuaCSFunction(LuaStatic.loadfile);
LuaDLL.lua_pushstdcallcfunction(L, loadfileFunction);
LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "loadfile");
dofileFunction = new LuaCSFunction(LuaStatic.dofile);
LuaDLL.lua_pushstdcallcfunction(L, dofileFunction);
LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "dofile");
import_wrapFunction = new LuaCSFunction(LuaStatic.importWrap);
LuaDLL.lua_pushstdcallcfunction(L, import_wrapFunction);
LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "import");
// Insert our loader FIRST
loaderFunction = new LuaCSFunction(LuaStatic.loader);
LuaDLL.lua_pushstdcallcfunction(L, loaderFunction);
int loaderFunc = LuaDLL.lua_gettop(L);
LuaDLL.lua_getfield(L, LuaIndexes.LUA_GLOBALSINDEX, "package");
LuaDLL.lua_getfield(L, -1, "loaders");
int loaderTable = LuaDLL.lua_gettop(L);
// Shift table elements right
for (int e = LuaDLL.luaL_getn(L, loaderTable) + 1; e > 1; e--)
{
LuaDLL.lua_rawgeti(L, loaderTable, e - 1);
LuaDLL.lua_rawseti(L, loaderTable, e);
}
LuaDLL.lua_pushvalue(L, loaderFunc);
LuaDLL.lua_rawseti(L, loaderTable, 1);
LuaDLL.lua_settop(L, 0);
DoString(LuaStatic.init_luanet);
tracebackFunction = new LuaCSFunction(LuaStatic.traceback);
}
public void Close()
{
if (L != IntPtr.Zero)
{
translator.Destroy();
LuaDLL.lua_close(L);
}
}
public ObjectTranslator GetTranslator()
{
return translator;
}
/// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary>
/// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception>
internal void ThrowExceptionFromError(int oldTop)
{
string err = LuaDLL.lua_tostring(L, -1);
LuaDLL.lua_settop(L, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
// comment by topameng
//LuaScriptException luaEx = err as LuaScriptException;
//if (luaEx != null) throw luaEx;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if (err == null) err = "Unknown Lua Error";
throw new LuaScriptException(err, "");
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
internal int SetPendingException(Exception e)
{
if (e != null)
{
translator.throwError(L, e.ToString());
LuaDLL.lua_pushnil(L);
return 1;
}
else
return 0;
}
/// <summary>
///
/// </summary>
/// <param name="chunk"></param>
/// <param name="name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name, LuaTable env)
{
int oldTop = LuaDLL.lua_gettop(L);
byte[] bt = Encoding.UTF8.GetBytes(chunk);
if (LuaDLL.luaL_loadbuffer(L, bt, bt.Length, name) != 0)
ThrowExceptionFromError(oldTop);
if (env != null)
{
env.push(L);
LuaDLL.lua_setfenv(L, -2);
}
LuaFunction result = translator.getFunction(L, -1);
translator.popValues(L, oldTop);
return result;
}
public LuaFunction LoadString(string chunk, string name)
{
return LoadString(chunk, name, null);
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = LuaDLL.lua_gettop(L);
// Load with Unity3D resources
//string text = LuaHelper.Load(fileName);
byte[] bt = null;
string path = Util.LuaPath(fileName);
using (FileStream fs = new FileStream(path, FileMode.Open))
{
BinaryReader br = new BinaryReader(fs);
bt = br.ReadBytes((int)fs.Length);
fs.Close();
}
//if( text == null )
//{
// ThrowExceptionFromError(oldTop);
//}
if (LuaDLL.luaL_loadbuffer(L, bt, bt.Length, fileName) != 0)
{
ThrowExceptionFromError(oldTop);
}
LuaFunction result = translator.getFunction(L, -1);
translator.popValues(L, oldTop);
return result;
}
/*
* Excutes a Lua chunk and returns all the chunk's return
* values in an array
*/
public object[] DoString(string chunk)
{
return DoString(chunk, "chunk", null);
}
/// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary>
/// <param name="chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param>
/// <returns></returns>
public object[] DoString(string chunk, string chunkName, LuaTable env)
{
int oldTop = LuaDLL.lua_gettop(L);
byte[] bt = Encoding.UTF8.GetBytes(chunk);
if (LuaDLL.luaL_loadbuffer(L, bt, bt.Length, chunkName) == 0)
{
if (env != null)
{
env.push(L);
//LuaDLL.lua_setfenv(L, -1);
LuaDLL.lua_setfenv(L, -2);
}
if (LuaDLL.lua_pcall(L, 0, -1, 0) == 0)
return translator.popValues(L, oldTop);
else
ThrowExceptionFromError(oldTop);
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
public object[] DoFile(string fileName)
{
return DoFile(fileName, null);
}
/*
* Excutes a Lua file and returns all the chunk's return
* values in an array
*/
public object[] DoFile(string fileName, LuaTable env)
{
LuaDLL.lua_pushstdcallcfunction(L, tracebackFunction);
int oldTop = LuaDLL.lua_gettop(L);
// Load with Unity3D resources
byte[] text = LuaStatic.Load(fileName);
if (text == null)
{
if (!fileName.Contains("mobdebug")) {
Debugger.LogError("Loader lua file failed: {0}", fileName);
}
LuaDLL.lua_pop(L, 1);
return null;
}
string luafile = Util.LuaPath(fileName);
//Encoding.UTF8.GetByteCount(text)
if (LuaDLL.luaL_loadbuffer(L, text, text.Length, luafile) == 0)
{
if (env != null)
{
env.push(L);
//LuaDLL.lua_setfenv(L, -1);
LuaDLL.lua_setfenv(L, -2);
}
if (LuaDLL.lua_pcall(L, 0, -1, -2) == 0)
{
object[] results = translator.popValues(L, oldTop);
LuaDLL.lua_pop(L, 1);
return results;
}
else
{
ThrowExceptionFromError(oldTop);
LuaDLL.lua_pop(L, 1);
}
}
else
{
ThrowExceptionFromError(oldTop);
LuaDLL.lua_pop(L, 1);
}
return null; // Never reached - keeps compiler happy
}
/*
* Indexer for global variables from the LuaInterpreter
* Supports navigation of tables by using . operator
*/
public object this[string fullPath]
{
get
{
object returnValue = null;
int oldTop = LuaDLL.lua_gettop(L);
string[] path = fullPath.Split(new char[] { '.' });
LuaDLL.lua_getglobal(L, path[0]);
returnValue = translator.getObject(L, -1);
if (path.Length > 1)
{
string[] remainingPath = new string[path.Length - 1];
Array.Copy(path, 1, remainingPath, 0, path.Length - 1);
returnValue = getObject(remainingPath);
}
LuaDLL.lua_settop(L, oldTop);
return returnValue;
}
set
{
int oldTop = LuaDLL.lua_gettop(L);
string[] path = fullPath.Split(new char[] { '.' });
if (path.Length == 1)
{
translator.push(L, value);
LuaDLL.lua_setglobal(L, fullPath);
}
else
{
//LuaDLL.lua_getglobal(L, path[0]);
LuaDLL.lua_rawglobal(L, path[0]);
LuaTypes type = LuaDLL.lua_type(L, -1);
if (type == LuaTypes.LUA_TNIL)
{
Debugger.LogError("Table {0} not exists", path[0]);
LuaDLL.lua_settop(L, oldTop);
return;
}
string[] remainingPath = new string[path.Length - 1];
Array.Copy(path, 1, remainingPath, 0, path.Length - 1);
setObject(remainingPath, value);
}
LuaDLL.lua_settop(L, oldTop);
// Globals auto-complete
// comment by topameng, too many time cost, you shound register you type in other position
/*if (value == null)
{
// Remove now obsolete entries
globals.Remove(fullPath);
}
else
{
// Add new entries
if (!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}*/
}
}
#region Globals auto-complete
//private readonly List<string> globals = new List<string>(); //完全无用的逗比
//private bool globalsSorted;
/// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
//public IEnumerable<string> Globals
//{
// get
// {
// // Only sort list when necessary
// if (!globalsSorted)
// {
// globals.Sort();
// globalsSorted = true;
// }
// return globals;
// }
//}
/// <summary>
/// Adds an entry to <see cref="globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <param name="path">The index accessor path ot the entry</param>
/// <param name="type">The type of the entry</param>
/// <param name="recursionCounter">How deep have we gone with recursion?</param>
//private void registerGlobal(string path, Type type, int recursionCounter)
//{
// // If the type is a global method, list it directly
// if (type == typeof(LuaCSFunction))
// {
// // Format for easy method invocation
// globals.Add(path + "(");
// }
// // If the type is a class or an interface and recursion hasn't been running too long, list the members
// else if ((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
// {
// #region Methods
// foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
// {
// if (
// // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
// (method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
// (method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
// // Exclude some generic .NET methods that wouldn't be very usefull in Lua
// method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
// method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
// method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
// !method.Name.StartsWith("get_", StringComparison.Ordinal) &&
// !method.Name.StartsWith("set_", StringComparison.Ordinal) &&
// !method.Name.StartsWith("add_", StringComparison.Ordinal) &&
// !method.Name.StartsWith("remove_", StringComparison.Ordinal))
// {
// // Format for easy method invocation
// string command = path + ":" + method.Name + "(";
// if (method.GetParameters().Length == 0) command += ")";
// globals.Add(command);
// }
// }
// #endregion
// #region Fields
// foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
// {
// if (
// // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
// (field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
// (field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
// {
// // Go into recursion for members
// registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
// }
// }
// #endregion
// #region Properties
// foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
// {
// if (
// // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
// (property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
// (property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// // Exclude some generic .NET properties that wouldn't be very usefull in Lua
// && property.Name != "Item")
// {
// // Go into recursion for members
// registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
// }
// }
// #endregion
// }
// // Otherwise simply add the element to the list
// else globals.Add(path);
// // List will need to be sorted on next access
// globalsSorted = false;
//}
#endregion
/*
* Navigates a table in the top of the stack, returning
* the value of the specified field
*/
internal object getObject(string[] remainingPath)
{
object returnValue = null;
for (int i = 0; i < remainingPath.Length; i++)
{
LuaDLL.lua_pushstring(L, remainingPath[i]);
LuaDLL.lua_gettable(L, -2);
returnValue = translator.getObject(L, -1);
if (returnValue == null) break;
}
return returnValue;
}
/*
* Gets a numeric global variable
*/
public double GetNumber(string fullPath)
{
return (double)this[fullPath];
}
/*
* Gets a string global variable
*/
public string GetString(string fullPath)
{
return (string)this[fullPath];
}
/*
* Gets a table global variable
*/
public LuaTable GetTable(string fullPath)
{
return (LuaTable)this[fullPath];
}
#if ! __NOGEN__
/*
* Gets a table global variable as an object implementing
* the interfaceType interface
*/
public object GetTable(Type interfaceType, string fullPath)
{
translator.throwError(L,"Tables as interfaces not implemnented");
return CodeGeneration.Instance.GetClassInstance(interfaceType,GetTable(fullPath));
}
#endif
/*
* Gets a function global variable
*/
public LuaFunction GetFunction(string fullPath)
{
object obj = this[fullPath];
return (obj is LuaCSFunction ? new LuaFunction((LuaCSFunction)obj, this) : (LuaFunction)obj);
}
/*
* Gets a function global variable as a delegate of
* type delegateType
*/
public Delegate GetFunction(Type delegateType, string fullPath)
{
#if __NOGEN__
translator.throwError(L, "function delegates not implemnented");
return null;
#else
return CodeGeneration.Instance.GetDelegate(delegateType,GetFunction(fullPath));
#endif
}
/*
* Calls the object as a function with the provided arguments,
* returning the function's returned values inside an array
*/
//internal object[] callFunction(object function,object[] args)
//{
// return callFunction(function, args, null);
//}
/*
* Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning
* them in an array
*/
//internal object[] callFunction(object function,object[] args,Type[] returnTypes)
//{
// int nArgs = 0;
// LuaDLL.lua_getglobal(L, "traceback");
// int oldTop = LuaDLL.lua_gettop(L);
// if (!LuaDLL.lua_checkstack(L, args.Length + 6))
// {
// LuaDLL.lua_pop(L, 1);
// throw new LuaException("Lua stack overflow");
// }
// translator.push(L, function);
// if (args != null)
// {
// nArgs = args.Length;
// for (int i = 0; i < args.Length; i++)
// {
// translator.push(L, args[i]);
// }
// }
// int error = LuaDLL.lua_pcall(L, nArgs, -1, -nArgs - 2);
// if (error != 0)
// {
// string err = LuaDLL.lua_tostring(L, -1);
// LuaDLL.lua_settop(L, oldTop);
// //LuaTypes luatype = LuaDLL.lua_type(L, -1);
// LuaDLL.lua_pop(L, 1);
// if (err == null) err = "Unknown Lua Error";
// throw new LuaScriptException(err.ToString(), "");
// }
// object[] ret = returnTypes != null ? translator.popValues(L, oldTop, returnTypes) : translator.popValues(L, oldTop);
// LuaDLL.lua_pop(L, 1);
// return ret;
//}
/*
* Navigates a table to set the value of one of its fields
*/
internal void setObject(string[] remainingPath, object val)
{
for (int i = 0; i < remainingPath.Length - 1; i++)
{
LuaDLL.lua_pushstring(L, remainingPath[i]);
LuaDLL.lua_gettable(L, -2);
}
LuaDLL.lua_pushstring(L, remainingPath[remainingPath.Length - 1]);
//可以释放先
//if (val == null)
//{
// LuaDLL.lua_gettable(L, -2);
// LuaTypes type = LuaDLL.lua_type(L, -1);
// if (type == LuaTypes.LUA_TUSERDATA)
// {
// int udata = LuaDLL.luanet_tonetobject(L, -1);
// if (udata != -1)
// {
// translator.collectObject(udata);
// }
// }
//}
translator.push(L, val);
LuaDLL.lua_settable(L, -3);
}
/*
* Creates a new table as a global variable or as a field
* inside an existing table
*/
public void NewTable(string fullPath)
{
string[] path = fullPath.Split(new char[] { '.' });
int oldTop = LuaDLL.lua_gettop(L);
if (path.Length == 1)
{
LuaDLL.lua_newtable(L);
LuaDLL.lua_setglobal(L, fullPath);
}
else
{
LuaDLL.lua_getglobal(L, path[0]);
for (int i = 1; i < path.Length - 1; i++)
{
LuaDLL.lua_pushstring(L, path[i]);
LuaDLL.lua_gettable(L, -2);
}
LuaDLL.lua_pushstring(L, path[path.Length - 1]);
LuaDLL.lua_newtable(L);
LuaDLL.lua_settable(L, -3);
}
LuaDLL.lua_settop(L, oldTop);
}
public LuaTable NewTable()
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_newtable(L);
LuaTable returnVal = (LuaTable)translator.getObject(L, -1);
LuaDLL.lua_settop(L, oldTop);
return returnVal;
}
public ListDictionary GetTableDict(LuaTable table)
{
ListDictionary dict = new ListDictionary();
int oldTop = LuaDLL.lua_gettop(L);
translator.push(L, table);
LuaDLL.lua_pushnil(L);
while (LuaDLL.lua_next(L, -2) != 0)
{
dict[translator.getObject(L, -2)] = translator.getObject(L, -1);
LuaDLL.lua_settop(L, -2);
}
LuaDLL.lua_settop(L, oldTop);
return dict;
}
/*
* Lets go of a previously allocated reference to a table, function
* or userdata
*/
internal void dispose(int reference)
{
if (L != IntPtr.Zero) //Fix submitted by Qingrui Li
{
LuaDLL.lua_unref(L, reference);
}
}
/*
* Gets a field of the table corresponding to the provided reference
* using rawget (do not use metatables)
*/
internal object rawGetObject(int reference, string field)
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, reference);
LuaDLL.lua_pushstring(L, field);
LuaDLL.lua_rawget(L, -2);
object obj = translator.getObject(L, -1);
LuaDLL.lua_settop(L, oldTop);
return obj;
}
/*
* Gets a field of the table or userdata corresponding to the provided reference
*/
internal object getObject(int reference, string field)
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, reference);
object returnValue = getObject(field.Split(new char[] { '.' }));
LuaDLL.lua_settop(L, oldTop);
return returnValue;
}
/*
* Gets a numeric field of the table or userdata corresponding the the provided reference
*/
internal object getObject(int reference, object field)
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, reference);
translator.push(L, field);
LuaDLL.lua_gettable(L, -2);
object returnValue = translator.getObject(L, -1);
LuaDLL.lua_settop(L, oldTop);
return returnValue;
}
/*
* Sets a field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, string field, object val)
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, reference);
setObject(field.Split(new char[] { '.' }), val);
LuaDLL.lua_settop(L, oldTop);
}
/*
* Sets a numeric field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, object field, object val)
{
int oldTop = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, reference);
translator.push(L, field);
translator.push(L, val);
LuaDLL.lua_settable(L, -3);
LuaDLL.lua_settop(L, oldTop);
}
/*
* Registers an object's method as a Lua function (global or table field)
* The method may have any signature
*/
public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id=2859&forum_id=145)
{
// We leave nothing on the stack when we are done
int oldTop = LuaDLL.lua_gettop(L);
LuaMethodWrapper wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
translator.push(L, new LuaCSFunction(wrapper.call));
this[path] = translator.getObject(L, -1);
LuaFunction f = GetFunction(path);
LuaDLL.lua_settop(L, oldTop);
return f;
}
public LuaFunction CreateFunction(object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id=2859&forum_id=145)
{
// We leave nothing on the stack when we are done
int oldTop = LuaDLL.lua_gettop(L);
LuaMethodWrapper wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
translator.push(L, new LuaCSFunction(wrapper.call));
object obj = translator.getObject(L, -1);
LuaFunction f = (obj is LuaCSFunction ? new LuaFunction((LuaCSFunction)obj, this) : (LuaFunction)obj);
LuaDLL.lua_settop(L, oldTop);
return f;
}
/*
* Compares the two values referenced by ref1 and ref2 for equality
*/
internal bool compareRef(int ref1, int ref2)
{
if (ref1 == ref2)
{
return true;
}
int top = LuaDLL.lua_gettop(L);
LuaDLL.lua_getref(L, ref1);
LuaDLL.lua_getref(L, ref2);
int equal = LuaDLL.lua_equal(L, -1, -2);
LuaDLL.lua_settop(L, top);
return (equal != 0);
}
internal void pushCSFunction(LuaCSFunction function)
{
translator.pushFunction(L, function);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
L = IntPtr.Zero;
GC.SuppressFinalize(this);
GC.Collect();
GC.WaitForPendingFinalizers();
}
public virtual void Dispose(bool dispose)
{
if (dispose)
{
if (translator != null)
{
translator.pendingEvents.Dispose();
translator = null;
}
}
}
#endregion
}
}
| 0 | 0.857075 | 1 | 0.857075 | game-dev | MEDIA | 0.613304 | game-dev | 0.824308 | 1 | 0.824308 |
dufernst/LegionCore-7.3.5 | 3,670 | src/server/scripts/EasternKingdoms/BlackrockDepths/boss_anubshiah.cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
enum Spells
{
SPELL_SHADOWBOLT = 17228,
SPELL_CURSEOFTONGUES = 15470,
SPELL_CURSEOFWEAKNESS = 17227,
SPELL_DEMONARMOR = 11735,
SPELL_ENVELOPINGWEB = 15471
};
class boss_anubshiah : public CreatureScript
{
public:
boss_anubshiah() : CreatureScript("boss_anubshiah") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_anubshiahAI (creature);
}
struct boss_anubshiahAI : public ScriptedAI
{
boss_anubshiahAI(Creature* creature) : ScriptedAI(creature) {}
uint32 ShadowBolt_Timer;
uint32 CurseOfTongues_Timer;
uint32 CurseOfWeakness_Timer;
uint32 DemonArmor_Timer;
uint32 EnvelopingWeb_Timer;
void Reset()
{
ShadowBolt_Timer = 7000;
CurseOfTongues_Timer = 24000;
CurseOfWeakness_Timer = 12000;
DemonArmor_Timer = 3000;
EnvelopingWeb_Timer = 16000;
}
void EnterCombat(Unit* /*who*/) {}
void UpdateAI(uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
//ShadowBolt_Timer
if (ShadowBolt_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SHADOWBOLT);
ShadowBolt_Timer = 7000;
} else ShadowBolt_Timer -= diff;
//CurseOfTongues_Timer
if (CurseOfTongues_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(target, SPELL_CURSEOFTONGUES);
CurseOfTongues_Timer = 18000;
} else CurseOfTongues_Timer -= diff;
//CurseOfWeakness_Timer
if (CurseOfWeakness_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CURSEOFWEAKNESS);
CurseOfWeakness_Timer = 45000;
} else CurseOfWeakness_Timer -= diff;
//DemonArmor_Timer
if (DemonArmor_Timer <= diff)
{
DoCast(me, SPELL_DEMONARMOR);
DemonArmor_Timer = 300000;
} else DemonArmor_Timer -= diff;
//EnvelopingWeb_Timer
if (EnvelopingWeb_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(target, SPELL_ENVELOPINGWEB);
EnvelopingWeb_Timer = 12000;
} else EnvelopingWeb_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_anubshiah()
{
new boss_anubshiah();
}
| 0 | 0.865456 | 1 | 0.865456 | game-dev | MEDIA | 0.918069 | game-dev | 0.801409 | 1 | 0.801409 |
Darkrp-community/OpenKeep | 1,869 | code/datums/elements/ai_flee_when_hurt.dm | /**
* Attached to a mob with an AI controller, simply sets a flag on whether or not to run away based on current health values.
*/
/datum/element/ai_flee_while_injured
/// Health value to end fleeing if at or above
var/stop_fleeing_at
/// Health value to start fleeing if at or below
var/start_fleeing_below
/datum/element/ai_flee_while_injured/Attach(datum/target, stop_fleeing_at = 1, start_fleeing_below = 0.5)
. = ..()
if(!isliving(target))
return ELEMENT_INCOMPATIBLE
var/mob/living/living_target = target
if(!living_target.ai_controller)
return ELEMENT_INCOMPATIBLE
src.stop_fleeing_at = stop_fleeing_at
src.start_fleeing_below = start_fleeing_below
RegisterSignal(target, COMSIG_LIVING_HEALTH_UPDATE, PROC_REF(on_health_changed))
/datum/element/ai_flee_while_injured/Detach(datum/source)
. = ..()
UnregisterSignal(source, COMSIG_LIVING_HEALTH_UPDATE)
/// When the mob's health changes, check what the blackboard state should be
/datum/element/ai_flee_while_injured/proc/on_health_changed(mob/living/source)
SIGNAL_HANDLER
if (!source.ai_controller)
return
var/current_health_percentage = source.health / source.maxHealth
if (source.ai_controller.blackboard[BB_BASIC_MOB_FLEEING])
if (current_health_percentage < stop_fleeing_at)
return
source.ai_controller.CancelActions() // Stop fleeing go back to whatever you were doing
source.ai_controller.set_blackboard_key(BB_BASIC_MOB_FLEEING, FALSE)
return
if (current_health_percentage > start_fleeing_below)
return
source.ai_controller.CancelActions()
source.ai_controller.set_blackboard_key(BB_BASIC_MOB_FLEEING, TRUE)
///we don't want ai's to run forever this makes us run for 10 seconds then fight until
addtimer(CALLBACK(source.ai_controller, TYPE_PROC_REF(/datum/ai_controller, set_blackboard_key), BB_BASIC_MOB_FLEEING, FALSE), 10 SECONDS, flags = TIMER_UNIQUE)
| 0 | 0.943487 | 1 | 0.943487 | game-dev | MEDIA | 0.733784 | game-dev | 0.996054 | 1 | 0.996054 |
electronicarts/CnC_Red_Alert | 20,858 | CODE/RNDSTRAW.CPP | /*
** Command & Conquer Red Alert(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Header: /CounterStrike/RNDSTRAW.CPP 1 3/03/97 10:25a Joe_bostic $ */
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : Command & Conquer *
* *
* File Name : RNDSTRAW.CPP *
* *
* Programmer : Joe L. Bostic *
* *
* Start Date : 07/04/96 *
* *
* Last Update : July 10, 1996 [JLB] *
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* RandomStraw::Get -- Fetch random data. *
* RandomStraw::RandomStraw -- Constructor for the random straw class. *
* RandomStraw::Reset -- Reset the data to known initial state. *
* RandomStraw::Scramble_Seed -- Masks any coorelation between the seed bits. *
* RandomStraw::Seed_Bit -- Add a random bit to the accumulated seed value. *
* RandomStraw::Seed_Bits_Needed -- Fetches the number of seed bits needed. *
* RandomStraw::Seed_Byte -- Submit 8 bits to the random number seed. *
* RandomStraw::Seed_Long -- Submit 32 bits to the random number seed. *
* RandomStraw::Seed_Short -- Submit 16 bits to the random number seed. *
* RandomStraw::~RandomStraw -- Destructor for random straw class. *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include <limits.h>
#include <string.h>
#include "rndstraw.h"
#include "sha.h"
/***********************************************************************************************
* RandomStraw::RandomStraw -- Constructor for the random straw class. *
* *
* This will initialize the random straw into a known state. The initial state is useless *
* for cryptographic purposes. It must be seeded before it should be used. *
* *
* INPUT: none *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
RandomStraw::RandomStraw(void) :
SeedBits(0),
Current(0)
{
Reset();
}
/***********************************************************************************************
* RandomStraw::~RandomStraw -- Destructor for random straw class. *
* *
* This destructor will clear out the seed data so that there won't be any sensitive *
* information left over in the memory this object occupied. *
* *
* INPUT: none *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
RandomStraw::~RandomStraw(void)
{
Reset();
}
/***********************************************************************************************
* RandomStraw::Reset -- Reset the data to known initial state. *
* *
* This routine is functionally equivalent to performing an placement new on the object. It *
* clears out all the seed data. *
* *
* INPUT: none *
* *
* OUTPUT: none *
* *
* WARNINGS: You must reseed it before fetching random numbers. *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Reset(void)
{
SeedBits = 0;
Current = 0;
memset(Random, '\0', sizeof(Random));
}
/***********************************************************************************************
* RandomStraw::Seed_Bits_Needed -- Fetches the number of seed bits needed. *
* *
* This routine is used when seeding the random straw. Keep feeding random bits to this *
* class until the Seed_Bits_Needed value returns zero. Random bits should be gathered from *
* sources external to the immediate program. Examples would be the system clock (good for *
* a few bits), the delay between player keystrokes (good for a few bits per keystroke), *
* etc. When gathering random bits from integers, use the low order bits (since they *
* characteristically are less predictable and more 'random' than the others). *
* *
* INPUT: none *
* *
* OUTPUT: Returns with the number of bits required in order to fully seed this random *
* number generator. *
* *
* WARNINGS: Even if this routine returns zero, you are still allowed and encouraged to feed *
* more random bits when the opportunity arrises. *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
int RandomStraw::Seed_Bits_Needed(void) const
{
const int total = sizeof(Random) * CHAR_BIT;
if (SeedBits < total) {
return(total - SeedBits);
}
return(0);
}
/***********************************************************************************************
* RandomStraw::Seed_Bit -- Add a random bit to the accumulated seed value. *
* *
* This routine should be called to feed a single random bit to the random straw object. *
* You must feed as many bits as requested by the Seed_Bits_Needed() function. Submitting *
* additional bits is not only allowed, but encouraged. *
* *
* INPUT: seed -- The bit (lowest order bit) to feed to the random number seed. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Seed_Bit(int seed)
{
char * ptr = ((char *)&Random[0]) + ((SeedBits / CHAR_BIT) % sizeof(Random));
char frac = (char)(1 << (SeedBits & (CHAR_BIT-1)));
if (seed & 0x01) {
*ptr ^= frac;
}
SeedBits++;
if (SeedBits == (sizeof(Random) * CHAR_BIT)) {
Scramble_Seed();
}
}
/***********************************************************************************************
* RandomStraw::Seed_Byte -- Submit 8 bits to the random number seed. *
* *
* This will submit 8 bits (as specified) to the random number seed. *
* *
* INPUT: seed -- The seed bits to submit. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Seed_Byte(char seed)
{
for (int index = 0; index < CHAR_BIT; index++) {
Seed_Bit(seed);
seed >>= 1;
}
}
/***********************************************************************************************
* RandomStraw::Seed_Short -- Submit 16 bits to the random number seed. *
* *
* This will submit 16 bits to the accumulated seed. *
* *
* INPUT: seed -- The 16 bits to submit to the seed. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Seed_Short(short seed)
{
for (int index = 0; index < (sizeof(seed)*CHAR_BIT); index++) {
Seed_Bit(seed);
seed >>= 1;
}
}
/***********************************************************************************************
* RandomStraw::Seed_Long -- Submit 32 bits to the random number seed. *
* *
* This will submit a full 32 bits to the accumulated seed value. *
* *
* INPUT: seed -- The 32 bits to submit. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Seed_Long(long seed)
{
for (int index = 0; index < (sizeof(seed)*CHAR_BIT); index++) {
Seed_Bit(seed);
seed >>= 1;
}
}
/***********************************************************************************************
* RandomStraw::Scramble_Seed -- Masks any coorelation between the seed bits. *
* *
* This routine is called when a full set of seed bits has been accumulated. It will take *
* the existing seed and scramble the bits. An effective way of doing this is to use the *
* Secure Hash Algorithm. It is necessary to have this routine because there might be *
* some coorelation in the seed bits. Even more important is that this routine will result *
* in every bit of the seed having a scrambling effect on every other bit. *
* *
* INPUT: none *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/10/1996 JLB : Created. *
*=============================================================================================*/
void RandomStraw::Scramble_Seed(void)
{
SHAEngine sha;
for (int index = 0; index < sizeof(Random); index++) {
char digest[20];
sha.Hash(&Random[0], sizeof(Random));
sha.Result(digest);
int tocopy = sizeof(digest) < (sizeof(Random)-index) ? sizeof(digest) : (sizeof(Random)-index);
memmove(((char *)&Random[0]) + index, digest, tocopy);
}
}
/***********************************************************************************************
* RandomStraw::Get -- Fetch random data. *
* *
* This routine will fetch random data and store it into the buffer specified. *
* *
* INPUT: source -- Pointer to the buffer to fill with random data. *
* *
* length -- The number of bytes to store into the buffer. *
* *
* OUTPUT: Returns with the actual number of bytes stored into the buffer. This will always *
* be the number of bytes requested since random numbers are unexhaustible. *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 07/04/1996 JLB : Created. *
* 07/10/1996 JLB : Revamped to make cryptographically secure. *
*=============================================================================================*/
int RandomStraw::Get(void * source, int slen)
{
if (source == NULL || slen < 1) {
return(Straw::Get(source, slen));
}
int total = 0;
while (slen > 0) {
*(char *)source = (char)Random[Current++];
Current = Current % (sizeof(Random) / sizeof(Random[0]));
source = (char*)source + sizeof(char);
slen--;
total++;
}
return(total);
}
| 0 | 0.515695 | 1 | 0.515695 | game-dev | MEDIA | 0.467262 | game-dev | 0.827307 | 1 | 0.827307 |
pulumi/pulumi | 2,087 | sdk/python/lib/test/langhost/component_dependencies/__main__.py | # Copyright 2016-2021, Pulumi Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
from pulumi import ComponentResource, CustomResource, Output, ResourceOptions
class MyResource(CustomResource):
def __init__(self, name, args, opts=None):
CustomResource.__init__(
self,
"test:index:MyResource",
name,
props={
**args,
"outprop": None,
},
opts=opts,
)
class MyComponent(ComponentResource):
def __init__(self, name, opts=None):
ComponentResource.__init__(
self, "test:index:MyComponent", name, props={}, opts=opts
)
resA = MyResource("resA", {})
comp1 = MyComponent("comp1")
resB = MyResource("resB", {}, ResourceOptions(parent=comp1))
resC = MyResource("resC", {}, ResourceOptions(parent=resB))
comp2 = MyComponent("comp2", ResourceOptions(parent=comp1))
resD = MyResource("resD", {"propA": resA}, ResourceOptions(parent=comp2))
resE = MyResource("resE", {"propA": resD}, ResourceOptions(parent=comp2))
resF = MyResource("resF", {"propA": resA})
resG = MyResource("resG", {"propA": comp1})
resH = MyResource("resH", {"propA": comp2})
resI = MyResource("resI", {"propA": resG})
resJ = MyResource("resJ", {}, ResourceOptions(depends_on=[comp2]))
first = MyComponent("first")
firstChild = MyResource("firstChild", {}, ResourceOptions(parent=first))
second = MyComponent("second", ResourceOptions(parent=first, depends_on=[first]))
myresource = MyResource("myresource", {}, ResourceOptions(parent=second))
| 0 | 0.569392 | 1 | 0.569392 | game-dev | MEDIA | 0.155358 | game-dev | 0.711823 | 1 | 0.711823 |
folgerwang/UnrealEngine | 2,859 | Engine/Source/Runtime/MovieSceneTracks/Private/Evaluation/MovieSceneObjectPropertyTemplate.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "Evaluation/MovieSceneObjectPropertyTemplate.h"
#include "Tracks/MovieSceneObjectPropertyTrack.h"
#include "Sections/MovieSceneObjectPropertySection.h"
struct FObjectPropertyExecToken : IMovieSceneExecutionToken
{
FObjectPropertyExecToken(UObject* InValue)
: NewObjectValue(MoveTemp(InValue))
{}
virtual void Execute(const FMovieSceneContext& Context, const FMovieSceneEvaluationOperand& Operand, FPersistentEvaluationData& PersistentData, IMovieScenePlayer& Player) override
{
using namespace PropertyTemplate;
FSectionData& PropertyTrackData = PersistentData.GetSectionData<FSectionData>();
FTrackInstancePropertyBindings* PropertyBindings = PropertyTrackData.PropertyBindings.Get();
check(PropertyBindings);
for (TWeakObjectPtr<> WeakObject : Player.FindBoundObjects(Operand))
{
UObject* ObjectPtr = WeakObject.Get();
if (!ObjectPtr)
{
continue;
}
UObjectPropertyBase* ObjectProperty = Cast<UObjectPropertyBase>(PropertyBindings->GetProperty(*ObjectPtr));
if (!ObjectProperty || !CanAssignValue(ObjectProperty, NewObjectValue))
{
continue;
}
Player.SavePreAnimatedState(*ObjectPtr, PropertyTrackData.PropertyID, FTokenProducer<UObject*>(*PropertyBindings));
UObject* ExistingValue = PropertyBindings->GetCurrentValue<UObject*>(*ObjectPtr);
if (ExistingValue != NewObjectValue)
{
PropertyBindings->CallFunction<UObject*>(*ObjectPtr, NewObjectValue);
}
}
}
bool CanAssignValue(UObjectPropertyBase* TargetProperty, UObject* DesiredValue) const
{
check(TargetProperty);
if (!TargetProperty->PropertyClass)
{
return false;
}
else if (!DesiredValue)
{
return !TargetProperty->HasAnyPropertyFlags(CPF_NoClear);
}
else if (DesiredValue->GetClass() != nullptr)
{
return DesiredValue->GetClass()->IsChildOf(TargetProperty->PropertyClass);
}
return false;
}
UObject* NewObjectValue;
};
FMovieSceneObjectPropertyTemplate::FMovieSceneObjectPropertyTemplate(const UMovieSceneObjectPropertySection& Section, const UMovieSceneObjectPropertyTrack& Track)
: FMovieScenePropertySectionTemplate(Track.GetPropertyName(), Track.GetPropertyPath())
, ObjectChannel(Section.ObjectChannel)
{}
void FMovieSceneObjectPropertyTemplate::SetupOverrides()
{
// We need FMovieScenePropertySectionTemplate::Setup to be called for initialization of the track instance bindings
EnableOverrides(RequiresSetupFlag);
}
void FMovieSceneObjectPropertyTemplate::Evaluate(const FMovieSceneEvaluationOperand& Operand, const FMovieSceneContext& Context, const FPersistentEvaluationData& PersistentData, FMovieSceneExecutionTokens& ExecutionTokens) const
{
UObject* Object = nullptr;
if (ObjectChannel.Evaluate(Context.GetTime(), Object))
{
ExecutionTokens.Add(FObjectPropertyExecToken(Object));
}
}
| 0 | 0.821314 | 1 | 0.821314 | game-dev | MEDIA | 0.581553 | game-dev,desktop-app | 0.923835 | 1 | 0.923835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.