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
soyware/heck_csgo_external
4,607
src/NetVars.hpp
#pragma once #ifdef GetProp #undef GetProp #endif namespace NetVars { RecvTable* GetTable(const char* name) { ClientClass cc; Mem::Read<ClientClass>(Signatures::g_pClientClassHead, cc); while (true) { char varname[64]; Mem::Read<char[64]>(reinterpret_cast<uintptr_t>(cc.m_pNetworkName), varname); if (!strcmp(varname, name)) return cc.m_pRecvTable; if (cc.m_pNext == 0) break; Mem::Read<ClientClass>(reinterpret_cast<uintptr_t>(cc.m_pNext), cc); } return nullptr; } int GetProp(RecvTable* pTable, const char* name) { RecvTable table; Mem::Read<RecvTable>(reinterpret_cast<uintptr_t>(pTable), table); int offset = 0; for (int i = 0; i < table.m_nProps; ++i) { RecvProp prop; Mem::Read<RecvProp>(reinterpret_cast<uintptr_t>(table.m_pProps) + i * sizeof(RecvProp), prop); if (prop.m_RecvType == DPT_DataTable) { int extra = GetProp(prop.m_pDataTable, name); if (extra) offset += prop.m_Offset + extra; } else { char varname[64]; Mem::Read<char[64]>(reinterpret_cast<uintptr_t>(prop.m_pVarName), varname); if (!strcmp(varname, name)) return prop.m_Offset; } } return offset; } int GetOffset(const char* tableName, const char* varName) { RecvTable* table = GetTable(tableName); if (!table) ErrorExit("Failed to find a netvar"); int offset = GetProp(table, varName); if (!offset) ErrorExit("Failed to find a netvar"); #ifdef _DEBUG std::cout << "Found " << varName << " -> 0x" << std::hex << offset << '\n'; #endif return offset; } int m_clrRender, m_iTeamNum, m_vecOrigin, m_nModelIndex, m_flSimulationTime, m_bSpotted, m_pBones, m_iHealth, m_fFlags, m_vecViewOffset, m_vecVelocity, m_lifeState, m_aimPunchAngle, m_iDefaultFOV, m_nTickBase, m_hActiveWeapon, m_bIsScoped, m_bIsWalking, m_bGunGameImmunity, m_iShotsFired, m_nSurvivalTeam, m_flFlashAlpha, m_flFlashMaxAlpha, m_angEyeAngles, m_iIDEntIndex, m_iItemDefinitionIndex, m_flNextPrimaryAttack, m_iClip1, m_bInReload, m_weaponMode, m_fAccuracyPenalty, m_zoomLevel, m_bFreezePeriod, m_bWarmupPeriod, m_bIsQueuedMatchmaking; void Find() { #ifdef _DEBUG std::cout << '\n'; #endif // _DEBUG m_clrRender = GetOffset("CBaseEntity", "m_clrRender"); m_iTeamNum = GetOffset("CBaseEntity", "m_iTeamNum"); m_vecOrigin = GetOffset("CBaseEntity", "m_vecOrigin"); m_nModelIndex = GetOffset("CBaseEntity", "m_nModelIndex"); m_flSimulationTime = GetOffset("CBaseEntity", "m_flSimulationTime"); m_bSpotted = GetOffset("CBaseEntity", "m_bSpotted"); m_pBones = GetOffset("CBaseAnimating", "m_nForceBone") + 28; m_iHealth = GetOffset("CBasePlayer", "m_iHealth"); m_fFlags = GetOffset("CBasePlayer", "m_fFlags"); m_vecViewOffset = GetOffset("CBasePlayer", "m_vecViewOffset[0]"); m_vecVelocity = GetOffset("CBasePlayer", "m_vecVelocity[0]"); m_lifeState = GetOffset("CBasePlayer", "m_lifeState"); m_aimPunchAngle = GetOffset("CBasePlayer", "m_aimPunchAngle"); m_iDefaultFOV = GetOffset("CBasePlayer", "m_iDefaultFOV"); m_nTickBase = GetOffset("CBasePlayer", "m_nTickBase"); m_hActiveWeapon = GetOffset("CBaseCombatCharacter", "m_hActiveWeapon"); m_bIsScoped = GetOffset("CCSPlayer", "m_bIsScoped"); m_bIsWalking = GetOffset("CCSPlayer", "m_bIsWalking"); m_bGunGameImmunity = GetOffset("CCSPlayer", "m_bGunGameImmunity"); m_iShotsFired = GetOffset("CCSPlayer", "m_iShotsFired"); m_nSurvivalTeam = GetOffset("CCSPlayer", "m_nSurvivalTeam"); m_flFlashMaxAlpha = GetOffset("CCSPlayer", "m_flFlashMaxAlpha"); m_flFlashAlpha = m_flFlashMaxAlpha - 12; m_angEyeAngles = GetOffset("CCSPlayer", "m_angEyeAngles[0]"); m_iIDEntIndex = GetOffset("CCSPlayer", "m_bHasDefuser") + 92; m_iItemDefinitionIndex = GetOffset("CEconEntity", "m_iItemDefinitionIndex"); m_flNextPrimaryAttack = GetOffset("CBaseCombatWeapon", "m_flNextPrimaryAttack"); m_iClip1 = GetOffset("CBaseCombatWeapon", "m_iClip1"); m_bInReload = GetOffset("CBaseCombatWeapon", "m_flTimeWeaponIdle") + 49; m_weaponMode = GetOffset("CWeaponCSBase", "m_weaponMode"); m_fAccuracyPenalty = GetOffset("CWeaponCSBase", "m_fAccuracyPenalty"); m_zoomLevel = GetOffset("CWeaponCSBaseGun", "m_zoomLevel"); m_bFreezePeriod = GetOffset("CCSGameRulesProxy", "m_bFreezePeriod"); m_bWarmupPeriod = GetOffset("CCSGameRulesProxy", "m_bWarmupPeriod"); m_bIsQueuedMatchmaking = GetOffset("CCSGameRulesProxy", "m_bIsQueuedMatchmaking"); } }
1
0.872435
1
0.872435
game-dev
MEDIA
0.890019
game-dev
0.856855
1
0.856855
smilehao/fog-of-war
2,409
Assets/Editor/NGUI/UIButtonColorEditor.cs
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2016 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using UnityEditor; #if UNITY_3_5 [CustomEditor(typeof(UIButtonColor))] #else [CustomEditor(typeof(UIButtonColor), true)] #endif public class UIButtonColorEditor : UIWidgetContainerEditor { public override void OnInspectorGUI () { GUILayout.Space(6f); NGUIEditorTools.SetLabelWidth(86f); serializedObject.Update(); NGUIEditorTools.DrawProperty("Tween Target", serializedObject, "tweenTarget"); DrawProperties(); serializedObject.ApplyModifiedProperties(); if (target.GetType() == typeof(UIButtonColor)) { GUILayout.Space(3f); if (GUILayout.Button("Upgrade to a Button")) { NGUIEditorTools.ReplaceClass(serializedObject, typeof(UIButton)); Selection.activeGameObject = null; } } } protected virtual void DrawProperties () { DrawTransition(); DrawColors(); } protected void DrawColors () { if (serializedObject.FindProperty("tweenTarget").objectReferenceValue == null) return; if (NGUIEditorTools.DrawHeader("Colors", "Colors", false, true)) { NGUIEditorTools.BeginContents(true); NGUIEditorTools.SetLabelWidth(76f); UIButtonColor btn = target as UIButtonColor; if (btn.tweenTarget != null) { UIWidget widget = btn.tweenTarget.GetComponent<UIWidget>(); if (widget != null) { EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects); { SerializedObject obj = new SerializedObject(widget); obj.Update(); NGUIEditorTools.DrawProperty("Normal", obj, "mColor"); obj.ApplyModifiedProperties(); } EditorGUI.EndDisabledGroup(); } } NGUIEditorTools.DrawProperty("Hover", serializedObject, "hover"); NGUIEditorTools.DrawProperty("Pressed", serializedObject, "pressed"); NGUIEditorTools.DrawProperty("Disabled", serializedObject, "disabledColor"); if (Application.isPlaying) EditorGUILayout.ColorField("Default", (target as UIButtonColor).defaultColor); NGUIEditorTools.EndContents(); } } protected void DrawTransition () { GUILayout.BeginHorizontal(); NGUIEditorTools.DrawProperty("Transition", serializedObject, "duration", GUILayout.Width(120f)); GUILayout.Label("seconds"); GUILayout.EndHorizontal(); GUILayout.Space(3f); } }
1
0.926182
1
0.926182
game-dev
MEDIA
0.79648
game-dev,desktop-app
0.933433
1
0.933433
ddiakopoulos/sandbox
1,845
vr-environment/third_party/bullet3/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.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_GJK_CONVEX_CAST_H #define BT_GJK_CONVEX_CAST_H #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "LinearMath/btVector3.h" #include "btConvexCast.h" class btConvexShape; class btMinkowskiSumShape; #include "btSimplexSolverInterface.h" ///GjkConvexCast performs a raycast on a convex object using support mapping. class btGjkConvexCast : public btConvexCast { btSimplexSolverInterface* m_simplexSolver; const btConvexShape* m_convexA; const btConvexShape* m_convexB; public: btGjkConvexCast(const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver); /// cast a convex against another convex object virtual bool calcTimeOfImpact( const btTransform& fromA, const btTransform& toA, const btTransform& fromB, const btTransform& toB, CastResult& result); }; #endif //BT_GJK_CONVEX_CAST_H
1
0.820069
1
0.820069
game-dev
MEDIA
0.991866
game-dev
0.609948
1
0.609948
dotnet/dotnet
15,550
src/winforms/src/System.Windows.Forms/System/Windows/Forms/Dialogs/CommonDialogs/FontDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Drawing; using System.Drawing.Interop; using System.Runtime.CompilerServices; using Windows.Win32.UI.Controls.Dialogs; namespace System.Windows.Forms; /// <summary> /// Represents a common dialog box that displays a list of fonts that are currently installed on the system. /// </summary> [DefaultEvent(nameof(Apply))] [DefaultProperty(nameof(Font))] [SRDescription(nameof(SR.DescriptionFontDialog))] public class FontDialog : CommonDialog { protected static readonly object EventApply = new(); private const int DefaultMinSize = 0; private const int DefaultMaxSize = 0; private CHOOSEFONT_FLAGS _options; private Font? _font; private Color _color; private int _minSize = DefaultMinSize; private int _maxSize = DefaultMaxSize; private bool _usingDefaultIndirectColor; /// <summary> /// Initializes a new instance of the <see cref="FontDialog"/> class. /// </summary> public FontDialog() => Reset(); /// <summary> /// Gets or sets a value indicating whether the dialog box allows graphics device interface /// (GDI) font simulations. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(true)] [SRDescription(nameof(SR.FnDallowSimulationsDescr))] public bool AllowSimulations { get => !GetOption(CHOOSEFONT_FLAGS.CF_NOSIMULATIONS); set => SetOption(CHOOSEFONT_FLAGS.CF_NOSIMULATIONS, !value); } /// <summary> /// Gets or sets a value indicating whether the dialog box allows vector font selections. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(true)] [SRDescription(nameof(SR.FnDallowVectorFontsDescr))] public bool AllowVectorFonts { get => !GetOption(CHOOSEFONT_FLAGS.CF_NOVECTORFONTS); set => SetOption(CHOOSEFONT_FLAGS.CF_NOVECTORFONTS, !value); } /// <summary> /// Gets or sets a value indicating whether /// the dialog box displays both vertical and horizontal fonts or only /// horizontal fonts. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(true)] [SRDescription(nameof(SR.FnDallowVerticalFontsDescr))] public bool AllowVerticalFonts { get => !GetOption(CHOOSEFONT_FLAGS.CF_NOVERTFONTS); set => SetOption(CHOOSEFONT_FLAGS.CF_NOVERTFONTS, !value); } /// <summary> /// Gets or sets a value indicating whether the user can change the character set specified in the Script combo /// box to display a character set other than the one currently displayed. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(true)] [SRDescription(nameof(SR.FnDallowScriptChangeDescr))] public bool AllowScriptChange { get => !GetOption(CHOOSEFONT_FLAGS.CF_SELECTSCRIPT); set => SetOption(CHOOSEFONT_FLAGS.CF_SELECTSCRIPT, !value); } /// <summary> /// Gets or sets a value indicating the selected font color. /// </summary> [SRCategory(nameof(SR.CatData))] [SRDescription(nameof(SR.FnDcolorDescr))] [DefaultValue(typeof(Color), "Black")] public Color Color { get { // Convert to RGB and back to resolve indirect colors like SystemColors.ControlText // to real color values like Color.Lime return !_usingDefaultIndirectColor ? _color : ColorTranslator.FromWin32(ColorTranslator.ToWin32(_color)); } set { if (!value.IsEmpty) { _color = value; _usingDefaultIndirectColor = false; } else { _color = SystemColors.ControlText; _usingDefaultIndirectColor = true; } } } /// <summary> /// Gets or sets a value indicating whether the dialog box allows only the selection of fixed-pitch fonts. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDfixedPitchOnlyDescr))] public bool FixedPitchOnly { get => GetOption(CHOOSEFONT_FLAGS.CF_FIXEDPITCHONLY); set => SetOption(CHOOSEFONT_FLAGS.CF_FIXEDPITCHONLY, value); } /// <summary> /// Gets or sets a value indicating the selected font. /// </summary> [SRCategory(nameof(SR.CatData))] [SRDescription(nameof(SR.FnDfontDescr))] public Font Font { get { Font? result = _font ?? Control.DefaultFont; float actualSize = result.SizeInPoints; if (_minSize != DefaultMinSize && actualSize < MinSize) { result = new Font(result.FontFamily, MinSize, result.Style, GraphicsUnit.Point); } if (_maxSize != DefaultMaxSize && actualSize > MaxSize) { result = new Font(result.FontFamily, MaxSize, result.Style, GraphicsUnit.Point); } return result; } set => _font = value; } /// <summary> /// Gets or sets a value indicating whether the dialog box specifies an error condition if the /// user attempts to select a font or style that does not exist. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDfontMustExistDescr))] public bool FontMustExist { get => GetOption(CHOOSEFONT_FLAGS.CF_FORCEFONTEXIST); set => SetOption(CHOOSEFONT_FLAGS.CF_FORCEFONTEXIST, value); } /// <summary> /// Gets or sets the maximum point size a user can select. /// </summary> [SRCategory(nameof(SR.CatData))] [DefaultValue(DefaultMaxSize)] [SRDescription(nameof(SR.FnDmaxSizeDescr))] public int MaxSize { get => _maxSize; set { if (value < 0) { value = 0; } _maxSize = value; if (_maxSize > 0 && _maxSize < _minSize) { _minSize = _maxSize; } } } /// <summary> /// Gets or sets a value indicating the minimum point size a user can select. /// </summary> [SRCategory(nameof(SR.CatData))] [DefaultValue(DefaultMinSize)] [SRDescription(nameof(SR.FnDminSizeDescr))] public int MinSize { get => _minSize; set { if (value < 0) { value = 0; } _minSize = value; if (_maxSize > 0 && _maxSize < _minSize) { _maxSize = _minSize; } } } /// <summary> /// Gets the value passed to CHOOSEFONT.Flags. /// </summary> protected int Options => (int)_options; /// <summary> /// Gets or sets a value indicating whether the dialog box allows selection of fonts for all non-OEM and Symbol /// character sets, as well as the ANSI character set. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDscriptsOnlyDescr))] public bool ScriptsOnly { get => GetOption(CHOOSEFONT_FLAGS.CF_SCRIPTSONLY); set => SetOption(CHOOSEFONT_FLAGS.CF_SCRIPTSONLY, value); } /// <summary> /// Gets or sets a value indicating whether the dialog box contains an Apply button. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDshowApplyDescr))] public bool ShowApply { get => GetOption(CHOOSEFONT_FLAGS.CF_APPLY); set => SetOption(CHOOSEFONT_FLAGS.CF_APPLY, value); } /// <summary> /// Gets or sets a value indicating whether the dialog box displays the color choice. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDshowColorDescr))] public bool ShowColor { get; set; } /// <summary> /// Gets or sets a value indicating whether the dialog box contains controls that allow the /// user to specify strikethrough, underline, and text color options. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(true)] [SRDescription(nameof(SR.FnDshowEffectsDescr))] public bool ShowEffects { get => GetOption(CHOOSEFONT_FLAGS.CF_EFFECTS); set => SetOption(CHOOSEFONT_FLAGS.CF_EFFECTS, value); } /// <summary> /// Gets or sets a value indicating whether the dialog box displays a Help button. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [SRDescription(nameof(SR.FnDshowHelpDescr))] public bool ShowHelp { get => GetOption(CHOOSEFONT_FLAGS.CF_SHOWHELP); set => SetOption(CHOOSEFONT_FLAGS.CF_SHOWHELP, value); } /// <summary> /// Occurs when the user clicks the Apply button in the font dialog box. /// </summary> [SRDescription(nameof(SR.FnDapplyDescr))] public event EventHandler? Apply { add => Events.AddHandler(EventApply, value); remove => Events.RemoveHandler(EventApply, value); } /// <summary> /// Returns the state of the given option flag. /// </summary> internal bool GetOption(CHOOSEFONT_FLAGS option) => (_options & option) != 0; /// <summary> /// Specifies the common dialog box hook procedure that is overridden to add /// specific functionality to a common dialog box. /// </summary> protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { switch ((uint)msg) { case PInvokeCore.WM_COMMAND: if (wparam != 0x402) { break; } LOGFONT logFont = default; PInvokeCore.SendMessage((HWND)hWnd, PInvokeCore.WM_CHOOSEFONT_GETLOGFONT, (WPARAM)0, ref logFont); UpdateFont(ref logFont); int index = (int)PInvoke.SendDlgItemMessage((HWND)hWnd, (int)PInvoke.cmb4, PInvoke.CB_GETCURSEL, 0, 0); if (index != PInvoke.CB_ERR) { UpdateColor((COLORREF)(int)PInvoke.SendDlgItemMessage( (HWND)hWnd, (int)PInvoke.cmb4, PInvoke.CB_GETITEMDATA, (WPARAM)index, 0)); } if (NativeWindow.WndProcShouldBeDebuggable) { OnApply(EventArgs.Empty); } else { try { OnApply(EventArgs.Empty); } catch (Exception e) { Application.OnThreadException(e); } } break; case PInvokeCore.WM_INITDIALOG: if (!ShowColor) { HWND hWndCtl = PInvoke.GetDlgItem((HWND)hWnd, (int)PInvoke.cmb4); PInvoke.ShowWindow(hWndCtl, SHOW_WINDOW_CMD.SW_HIDE); hWndCtl = PInvoke.GetDlgItem((HWND)hWnd, (int)PInvoke.stc4); PInvoke.ShowWindow(hWndCtl, SHOW_WINDOW_CMD.SW_HIDE); } break; } return base.HookProc(hWnd, msg, wparam, lparam); } /// <summary> /// Raises the <see cref="Apply"/> event. /// </summary> protected virtual void OnApply(EventArgs e) => (Events[EventApply] as EventHandler)?.Invoke(this, e); /// <summary> /// Resets all dialog box options to their default values. /// </summary> public override void Reset() { _options = CHOOSEFONT_FLAGS.CF_SCREENFONTS | CHOOSEFONT_FLAGS.CF_EFFECTS; _font = null; _color = SystemColors.ControlText; _usingDefaultIndirectColor = true; ShowColor = false; _minSize = DefaultMinSize; _maxSize = DefaultMaxSize; SetOption(CHOOSEFONT_FLAGS.CF_TTONLY, true); } private void ResetFont() => _font = null; protected override unsafe bool RunDialog(IntPtr hWndOwner) { using var dc = GetDcScope.ScreenDC; using Graphics graphics = Graphics.FromHdcInternal(dc); LOGFONTW logFont = Font.ToLogicalFont(graphics); CHOOSEFONTW cf = new() { lStructSize = (uint)sizeof(CHOOSEFONTW), hwndOwner = (HWND)hWndOwner, lpLogFont = &logFont, Flags = (CHOOSEFONT_FLAGS)Options | CHOOSEFONT_FLAGS.CF_INITTOLOGFONTSTRUCT | CHOOSEFONT_FLAGS.CF_ENABLEHOOK, lpfnHook = HookProcFunctionPointer, hInstance = PInvoke.GetModuleHandle((PCWSTR)null), nSizeMin = _minSize, nSizeMax = _maxSize == 0 ? int.MaxValue : _maxSize, rgbColors = ShowColor || ShowEffects ? _color : SystemColors.ControlText }; if (_minSize > 0 || _maxSize > 0) { cf.Flags |= CHOOSEFONT_FLAGS.CF_LIMITSIZE; } // if ShowColor=true then try to draw the sample text in color, // if ShowEffects=false then we will draw the sample text in standard control text color regardless. // (limitation of windows control) Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around"); // The native font dialog does not currently support Per Monitor V2 mode. We are setting DpiAwareness // to SystemAware as a workaround. This action has no effect when the application is not running in // Per Monitor V2 mode. // // https://microsoft.visualstudio.com/OS/_workitems/edit/42835582 using (ScaleHelper.EnterDpiAwarenessScope(DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_SYSTEM_AWARE)) { if (!PInvoke.ChooseFont(&cf)) { return false; } } if (!logFont.FaceName.IsEmpty) { UpdateFont(ref Unsafe.As<LOGFONTW, LOGFONT>(ref logFont)); UpdateColor(cf.rgbColors); } return true; } /// <summary> /// Sets the given option to the given boolean value. /// </summary> internal void SetOption(CHOOSEFONT_FLAGS option, bool value) { if (value) { _options |= option; } else { _options &= ~option; } } /// <summary> /// Indicates whether the <see cref="Font"/> property should be persisted. /// </summary> private bool ShouldSerializeFont() => !Font.Equals(Control.DefaultFont); public override string ToString() => $"{base.ToString()}, Font: {Font}"; private void UpdateColor(Color color) { if (_color != color) { _color = color; _usingDefaultIndirectColor = false; } } private void UpdateFont(ref LOGFONT lf) { using var dc = GetDcScope.ScreenDC; using Font fontInWorldUnits = Font.FromLogFont(in lf, dc); // The dialog claims its working in points (a device-independent unit), // but actually gives us something in world units (device-dependent). _font = ControlPaint.FontInPoints(fontInWorldUnits); } }
1
0.965295
1
0.965295
game-dev
MEDIA
0.487977
game-dev,desktop-app
0.941992
1
0.941992
ProjectIgnis/CardScripts
1,489
rush/c160215084.lua
--タイドライド・ブルーフィン --Tide-Ride Bluefin --scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Ritual c:EnableReviveLimit() --Send the top 2 cards of your Deck to the GY local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DECKDES+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsSummonPhaseMain() and c:IsStatus(STATUS_SPSUMMON_TURN) and c:IsSummonType(SUMMON_TYPE_RITUAL) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDiscardDeck(tp,2) end Duel.SetOperationInfo(0,CATEGORY_DECKDES,nil,0,tp,2) end function s.cfilter(c) return c:IsLocation(LOCATION_GRAVE) and (c:IsRace(RACE_FISH) or c:IsType(TYPE_SPELL)) end function s.operation(e,tp,eg,ep,ev,re,r,rp) --Effect if Duel.DiscardDeck(tp,2,REASON_EFFECT)~=2 then return end local og=Duel.GetOperatedGroup() if og:IsExists(s.cfilter,1,nil) and Duel.IsExistingMatchingCard(Card.IsSpellTrap,tp,0,LOCATION_ONFIELD,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(id,1)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local dg=Duel.SelectMatchingCard(tp,Card.IsSpellTrap,tp,0,LOCATION_ONFIELD,1,1,nil) Duel.HintSelection(dg) Duel.BreakEffect() Duel.Destroy(dg,REASON_EFFECT) end end
1
0.868586
1
0.868586
game-dev
MEDIA
0.964285
game-dev
0.965744
1
0.965744
leapmotion/AppExperiments
3,453
Assets/Plugins/LeapMotion/Modules/InteractionEngine/Scripts/Internal/NonKinematicGraspedMovement.cs
/****************************************************************************** * Copyright (C) Ultraleap, Inc. 2011-2020. * * Ultraleap proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Ultraleap and you, your company or other organization. * ******************************************************************************/ using InteractionEngineUtility; using Leap.Unity.Query; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Interaction { /// <summary> /// This implementation of IGraspedMovementHandler moves an interaction object to its /// target position and rotation by setting its rigidbody's velocity and angular /// velocity such that it will reach the target position and rotation on the next /// physics update. /// </summary> public class NonKinematicGraspedMovement : IGraspedMovementHandler { protected float _maxVelocity = 6F; private Vector3 _lastSolvedCoMPosition = Vector3.zero; protected AnimationCurve _strengthByDistance = new AnimationCurve(new Keyframe(0.0f, 1.0f, 0.0f, 0.0f), new Keyframe(0.02f, 0.3f, 0.0f, 0.0f)); public void MoveTo(Vector3 solvedPosition, Quaternion solvedRotation, InteractionBehaviour intObj, bool justGrasped) { Vector3 solvedCenterOfMass = solvedRotation * intObj.rigidbody.centerOfMass + solvedPosition; Vector3 currCenterOfMass = intObj.rigidbody.rotation * intObj.rigidbody.centerOfMass + intObj.rigidbody.position; Vector3 targetVelocity = PhysicsUtility.ToLinearVelocity(currCenterOfMass, solvedCenterOfMass, Time.fixedDeltaTime); Vector3 targetAngularVelocity = PhysicsUtility.ToAngularVelocity(intObj.rigidbody.rotation, solvedRotation, Time.fixedDeltaTime); // Clamp targetVelocity by _maxVelocity. float maxScaledVelocity = _maxVelocity * intObj.manager.SimulationScale; float targetSpeedSqrd = targetVelocity.sqrMagnitude; if (targetSpeedSqrd > maxScaledVelocity * maxScaledVelocity) { float targetPercent = maxScaledVelocity / Mathf.Sqrt(targetSpeedSqrd); targetVelocity *= targetPercent; targetAngularVelocity *= targetPercent; } float followStrength = 1F; if (!justGrasped) { float remainingDistanceLastFrame = Vector3.Distance(_lastSolvedCoMPosition, currCenterOfMass); followStrength = _strengthByDistance.Evaluate(remainingDistanceLastFrame / intObj.manager.SimulationScale); } Vector3 lerpedVelocity = Vector3.Lerp(intObj.rigidbody.velocity, targetVelocity, followStrength); Vector3 lerpedAngularVelocity = Vector3.Lerp(intObj.rigidbody.angularVelocity, targetAngularVelocity, followStrength); intObj.rigidbody.velocity = lerpedVelocity; intObj.rigidbody.angularVelocity = lerpedAngularVelocity; _lastSolvedCoMPosition = solvedCenterOfMass; // Store the target position and rotation to prevent slippage in SwapGrasp // scenarios. intObj.latestScheduledGraspPose = new Pose(solvedPosition, solvedRotation); } } }
1
0.921194
1
0.921194
game-dev
MEDIA
0.978224
game-dev
0.980009
1
0.980009
Twin1dev/MagmaGS-11.31
1,131
FortMP/SDK/GE_ShieldRegen_Delay_Damaged_functions.cpp
#pragma once // Dumped with Dumper-7! #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------------------------------------------------- // FUNCTIONS //--------------------------------------------------------------------------------------------------------------------- // BlueprintGeneratedClass GE_ShieldRegen_Delay_Damaged.GE_ShieldRegen_Delay_Damaged_C // (None) class UClass* UGE_ShieldRegen_Delay_Damaged_C::StaticClass() { static class UClass* Clss = nullptr; if (!Clss) Clss = UObject::FindClassFast("GE_ShieldRegen_Delay_Damaged_C"); return Clss; } // GE_ShieldRegen_Delay_Damaged_C GE_ShieldRegen_Delay_Damaged.Default__GE_ShieldRegen_Delay_Damaged_C // (Public, ClassDefaultObject, ArchetypeObject, WasLoaded, LoadCompleted) class UGE_ShieldRegen_Delay_Damaged_C* UGE_ShieldRegen_Delay_Damaged_C::GetDefaultObj() { static class UGE_ShieldRegen_Delay_Damaged_C* Default = nullptr; if (!Default) Default = static_cast<UGE_ShieldRegen_Delay_Damaged_C*>(UGE_ShieldRegen_Delay_Damaged_C::StaticClass()->DefaultObject); return Default; } }
1
0.63351
1
0.63351
game-dev
MEDIA
0.661442
game-dev
0.69413
1
0.69413
Sigma-Skidder-Team/SigmaRebase
1,034
src/main/java/net/minecraft/world/gen/feature/BlockWithContextFeature.java
package net.minecraft.world.gen.feature; import com.mojang.serialization.Codec; import java.util.Random; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ISeedReader; import net.minecraft.world.gen.ChunkGenerator; public class BlockWithContextFeature extends Feature<BlockWithContextConfig> { public BlockWithContextFeature(Codec<BlockWithContextConfig> p_i231991_1_) { super(p_i231991_1_); } public boolean func_241855_a(ISeedReader p_241855_1_, ChunkGenerator p_241855_2_, Random p_241855_3_, BlockPos p_241855_4_, BlockWithContextConfig p_241855_5_) { if (p_241855_5_.placeOn.contains(p_241855_1_.getBlockState(p_241855_4_.down())) && p_241855_5_.placeIn.contains(p_241855_1_.getBlockState(p_241855_4_)) && p_241855_5_.placeUnder.contains(p_241855_1_.getBlockState(p_241855_4_.up()))) { p_241855_1_.setBlockState(p_241855_4_, p_241855_5_.toPlace, 2); return true; } else { return false; } } }
1
0.63382
1
0.63382
game-dev
MEDIA
0.971314
game-dev
0.613344
1
0.613344
ixray-team/ixray-1.6-stcop
4,088
gamedata_cs/configs/scripts/agroprom/stalker_trader.ltx
[logic] active = remark@wait trade = misc\trade\trade_trader_agr_stalker.ltx level_spot = trader [remark@enemy] path_walk = agr_stalker_trader_walk path_look = agr_stalker_trader_look out_restr = agr_in_restr_stalker_trader anim = hands_up target = actor meet = no_meet on_info = {!is_smart_in_combat(agr_smart_terrain_4_4)} remark@wait combat_ignore_cond = true combat_ignore_keep_when_attacked = true [remark@wait] path_walk = agr_stalker_trader_walk path_look = agr_stalker_trader_look out_restr = agr_in_restr_stalker_trader anim = wait_trade on_info2 = smartcover@near_table meet = meet combat_ignore_cond = true combat_ignore_keep_when_attacked = true on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy [smartcover@near_table] cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = idle_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 13330 | smartcover@near_table2 def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table2] cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@near_table3 def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table3] cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = fire_no_lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 4500 | smartcover@near_table4 def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table4] cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = fire_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 6500 | smartcover@near_table def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@look_up] cover_name = agr_smart_cover_stalker_trader_2 loophole_name = lead_stand_look_down_2 cover_state = lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@look_up2 def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@look_up2] cover_name = agr_smart_cover_stalker_trader_2 loophole_name = lead_stand_look_down_2 cover_state = fire_no_lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@near_table def_state_moving = walk on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@trade] cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = idle_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader def_state_moving = walk meet = meet on_info = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@enemy on_info2 = {!actor_in_zone(agr_stalker_trader_tradezone)} smartcover@near_table [meet] meet_state = 0| nil@nil victim = 0| nil use = true abuse = false
1
0.862924
1
0.862924
game-dev
MEDIA
0.664736
game-dev
0.823575
1
0.823575
open-scan-crew/OpenScanTools
3,624
ext/ReCapSDK/include/realdwg/dbregion.h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // DESCRIPTION: // // The AcDbRegion class is the interface class for representing // regions inside AutoCAD. All the functionality supported by // this class is implemented in the class AcDbImpRegion and its // base classes. #ifndef GEOMENT_DBREGION_H #define GEOMENT_DBREGION_H #include "dbmain.h" #include "dbsubeid.h" #include "gepnt3d.h" #include "gevec3d.h" #pragma pack(push, 8) class AcDbRegion: public AcDbEntity { public: ACDB_PORT AcDbRegion(); ACDB_PORT ~AcDbRegion(); GEOMENT_DECLARE_MEMBERS(AcDbRegion); static Acad::ErrorStatus createFromCurves(const AcDbVoidPtrArray& curveSegments, AcDbVoidPtrArray& regions); virtual Acad::ErrorStatus getPerimeter(double&) const; virtual Acad::ErrorStatus getArea(double& regionArea) const; virtual void* ASMBodyCopy(bool bDeepCopy = false) const; // INTERNAL USE ONLY virtual void const * getLockedASMBody(); // INTERNAL USE ONLY virtual void unlockASMBody(); // INTERNAL USE ONLY virtual void* getLockedWritableASMBody(); // INTERNAL USE ONLY virtual void commitWritableASMBody(); // INTERNAL USE ONLY ACDB_PORT virtual Acad::ErrorStatus setASMBody(const void* modelerBody); // INTERNAL USE ONLY virtual Acad::ErrorStatus getAreaProp( const AcGePoint3d& origin, const AcGeVector3d& xAxis, const AcGeVector3d& yAxis, double& perimeter, double& area, AcGePoint2d& centroid, double momInertia[2], double& prodInertia, double prinMoments[2], AcGeVector2d prinAxes[2], double radiiGyration[2], AcGePoint2d& extentsLow, AcGePoint2d& extentsHigh)const; virtual Acad::ErrorStatus getPlane(AcGePlane& regionPlane) const; ACDB_PORT void dragStatus(const AcDb::DragStat) override; virtual Adesk::Boolean isNull () const; virtual Acad::ErrorStatus getNormal(AcGeVector3d&) const; virtual AcDbSubentId internalSubentId (void* ent) const; // INTERNAL USE ONLY virtual void* internalSubentPtr (const AcDbSubentId& id) const; // INTERNAL USE ONLY virtual Acad::ErrorStatus booleanOper(AcDb::BoolOperType operation, AcDbRegion* otherRegion); virtual Adesk::UInt32 numChanges() const; ACDB_PORT virtual bool usesGraphicsCache(); ACDB_PORT Acad::ErrorStatus getPlane(AcGePlane& plane, AcDb::Planarity& type) const override; protected: Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; #pragma pack(pop) #endif
1
0.96271
1
0.96271
game-dev
MEDIA
0.738825
game-dev
0.650864
1
0.650864
ExtraCells/ExtraCells2
2,235
src/main/scala/extracells/gui/fluid/GuiFluidCrafter.java
package extracells.gui.fluid; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; import extracells.container.fluid.ContainerFluidCrafter; import extracells.registries.BlockEnum; public class GuiFluidCrafter extends GuiContainer { public static final int xSize = 176; public static final int ySize = 166; private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/fluidcrafter.png"); public GuiFluidCrafter(InventoryPlayer player, IInventory tileentity) { super(new ContainerFluidCrafter(player, tileentity)); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); renderHoveredToolTip(mouseX, mouseY); } @Override protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { drawDefaultBackground(); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); int posX = (this.width - xSize) / 2; int posY = (this.height - ySize) / 2; drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); for (Object s : this.inventorySlots.inventorySlots) { renderBackground((Slot) s); } } @Override protected void drawGuiContainerForegroundLayer(int i, int j) { this.fontRenderer.drawString(BlockEnum.FLUIDCRAFTER.getStatName(), 5, 5, 0x000000); } public int getRowLength() { return 3; } private void renderBackground(Slot slot) { if ((slot.getStack() == null || slot.getStack().isEmpty()) && slot.slotNumber < 9) { GlStateManager.disableLighting(); GlStateManager.enableBlend(); GlStateManager.color(1.0F, 1.0F, 1.0F, 0.5F); this.mc.getTextureManager().bindTexture( new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); this.drawTexturedModalRect(this.guiLeft + slot.xPos, this.guiTop + slot.yPos, 240, 128, 16, 16); GlStateManager.disableBlend(); GlStateManager.enableLighting(); } } }
1
0.889567
1
0.889567
game-dev
MEDIA
0.92204
game-dev,graphics-rendering
0.960736
1
0.960736
MehVahdJukaar/Supplementaries
1,688
common/src/main/java/net/mehvahdjukaar/supplementaries/mixins/LiquidBlockRendererMixin.java
package net.mehvahdjukaar.supplementaries.mixins; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import net.mehvahdjukaar.supplementaries.reg.ModFluids; import net.minecraft.client.renderer.block.LiquidBlockRenderer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.material.Fluid; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @Mixin(LiquidBlockRenderer.class) public class LiquidBlockRendererMixin { @WrapOperation(method = "getHeight(Lnet/minecraft/world/level/BlockAndTintGetter;Lnet/minecraft/world/level/material/Fluid;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/material/FluidState;)F", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/material/Fluid;isSame(Lnet/minecraft/world/level/material/Fluid;)Z")) public boolean supplementaries$modifyLumiseneHeight(Fluid instance, Fluid above, Operation<Boolean> original) { return original.call(instance, above) || above.isSame(ModFluids.LUMISENE_FLUID.get()); } @WrapOperation(method = "getLightColor", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;getLightColor(Lnet/minecraft/world/level/BlockAndTintGetter;Lnet/minecraft/core/BlockPos;)I")) public int supplementaries$modifyLumiseneLight(BlockAndTintGetter level, BlockPos pos, Operation<Integer> original) { return ModFluids.getLumiseneFaceLight(level, pos, original); } }
1
0.813134
1
0.813134
game-dev
MEDIA
0.999245
game-dev
0.596782
1
0.596782
sezero/uhexen2
39,617
gamecode/hc/portals/mezzoman.hc
/* ============================================================================== Q:\art\models\monsters\mezzoman\FINAL\mezzoman.hc MG!!! ============================================================================== */ // For building the model $cd Q:\art\models\monsters\mezzoman\FINAL $origin 0 0 -2 $base BASE skin1 $skin skin1 $skin Skin2 $flags 16384 // $frame block1 block2 block3 block4 block5 $frame block6 // $frame charge1 charge2 charge3 charge4 charge5 $frame charge6 charge7 charge8 charge9 charge10 $frame charge11 charge12 charge13 charge14 charge15 $frame charge16 charge17 charge18 charge19 charge20 $frame charge21 charge22 charge23 charge24 charge25 // $frame clober1 clober2 clober3 clober4 clober5 $frame clober6 clober7 clober8 clober9 clober10 $frame clober11 clober12 clober13 clober14 clober15 $frame clober16 // $frame death1 death2 death3 death4 death5 $frame death6 death7 death8 death9 death10 $frame death11 death12 death13 death14 death15 $frame death16 // $frame dive1 dive2 dive3 dive4 dive5 $frame dive6 dive7 dive8 dive9 dive10 $frame dive11 dive12 dive13 dive14 dive15 $frame dive16 dive17 dive18 // $frame jump1 jump2 jump3 jump4 jump5 $frame jump6 jump7 jump8 jump9 jump10 $frame jump11 jump12 jump13 jump14 jump15 $frame jump16 jump17 jump18 jump19 jump20 $frame jump21 jump22 // $frame pain1 pain2 pain3 pain4 pain5 $frame pain6 pain7 // $frame roar1 roar2 roar3 roar4 roar5 $frame roar6 roar7 roar8 roar9 roar10 $frame roar11 roar12 roar13 roar14 roar15 $frame roar16 roar17 roar18 roar19 roar20 $frame roar21 roar22 roar23 roar24 roar25 $frame roar26 roar27 roar28 roar29 roar30 // $frame Roll1 Roll2 Roll3 Roll4 Roll5 $frame Roll6 Roll7 Roll8 Roll9 Roll10 $frame Roll11 Roll12 Roll13 Roll14 Roll15 $frame Roll16 Roll17 Roll18 // $frame run1 run2 run3 run4 run5 $frame run6 run7 run8 run9 run10 $frame run11 run12 run13 run14 run15 $frame run16 run17 run18 run19 run20 $frame run21 run22 // $frame stand1 stand2 stand3 stand4 stand5 $frame stand6 stand7 stand8 stand9 stand10 // $frame sword1 sword2 sword3 sword4 sword5 $frame sword6 sword7 sword8 sword9 sword10 $frame sword11 sword12 sword13 // $frame twirl1 twirl2 twirl3 twirl4 twirl5 $frame twirl6 twirl7 twirl8 twirl9 twirl10 // $frame walk1 walk2 walk3 walk4 walk5 $frame walk6 walk7 walk8 walk9 walk10 $frame walk11 walk12 walk13 walk14 walk15 $frame walk16 walk17 walk18 walk19 walk20 $frame walk21 walk22 walk23 walk24 walk25 $frame walk26 walk27 walk28 walk29 walk30 void() mezzo_skid; void() mezzo_block; void() mezzo_block_wait; void() mezzo_jump; void() mezzo_roar; void() mezzo_in_air; void() mezzo_run_loop; void()mezzo_charge; void mezzo_idle_sound () { string soundstr; if(random()<0.5) soundstr="mezzo/snort.wav"; else soundstr="mezzo/growl.wav"; sound(self,CHAN_VOICE,soundstr,1,ATTN_NORM); } void mezzo_roll_right () [-- $Roll18 .. $Roll1] { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); //SOUND? vector rollangle; makevectors(self.angles); rollangle=vectoangles(v_right); // if(!walkmove(rollangle_y,7,FALSE)&&self.frame>$Roll5 &&self.flags&FL_ONGROUND) // self.frame=$Roll5; walkmove(rollangle_y,7,FALSE); if(cycle_wrapped) { thinktime self : 0; if(!self.flags&FL_ONGROUND) self.think=mezzo_in_air; else self.think=self.th_run; } } void mezzo_roll_left () [++ $Roll1 .. $Roll18] { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); //SOUND? vector rollangle; makevectors(self.angles); rollangle=vectoangles(v_right); // if(!walkmove(rollangle_y,-7,FALSE)&&self.frame<$Roll14 &&self.flags&FL_ONGROUND) // self.frame=$Roll14; walkmove(rollangle_y,-7,FALSE); if(cycle_wrapped) { thinktime self : 0; if(!self.flags&FL_ONGROUND) self.think=mezzo_in_air; else self.think=self.th_run; } } void mezzo_roll_forward () [++ $dive1 .. $dive18] { //SOUND? //vector rollangle; // if(!walkmove(self.angles_y,7,FALSE)&&self.frame<$dive12 &&self.flags&FL_ONGROUND) // self.frame=$dive12; if(!self.flags&FL_ONGROUND) { if(!infront(self.enemy))//stay facing enemy so if land behind him, will be facing him ai_face(); } else { if(self.dflags) { sound(self,CHAN_BODY,"player/land.wav",1,ATTN_NORM); self.dflags=FALSE; } walkmove(self.angles_y,7,FALSE); } if(cycle_wrapped) { thinktime self : 0; if(!self.flags&FL_ONGROUND) self.think=mezzo_in_air; else self.think=self.th_run; } } void mezzo_duck () [++ $jump13 .. $jump22] { //FIXME: Have him keep checking for befense when staying down for .5 sec vector newmaxs; if(self.frame==$jump14) { newmaxs=self.maxs; newmaxs_z=self.maxs_z*0.5; setsize(self,self.mins,newmaxs); } else if(self.frame==$jump18) { newmaxs=self.maxs; newmaxs_z=self.maxs_z*2; setsize(self,self.mins,newmaxs); } else if(self.frame==$jump16) thinktime self : 0.5; else if(cycle_wrapped) { thinktime self : 0; self.think=self.th_run; } } float mezzo_check_duck (entity proj) { entity proj_owner; vector proj_mins,duck_hite,proj_dir; vector temp_f,temp_r,temp_u; duck_hite=self.origin; duck_hite_z=self.origin_z + self.maxs_z/2; if(proj==self.enemy) { proj_owner=proj; proj_mins=self.enemy.origin+self.enemy.proj_ofs; temp_f=v_forward; temp_r=v_right; temp_u=v_up; if(self.enemy.classname=="player") makevectors(self.enemy.v_angle); else makevectors(self.enemy.angles); proj_dir=v_forward; v_forward=temp_f; v_right=temp_r; v_up=temp_u; } else { proj_owner=proj.owner; proj_mins=proj.origin; proj_mins_z=proj.origin_z - proj.mins_z; proj_dir=normalize(duck_hite-proj_mins); } if(!proj_owner) proj_owner=proj; traceline(proj_mins,duck_hite+proj_dir*8,FALSE,proj_owner); if(trace_ent!=self)//||trace_endpos_z>duck_hite_z) { // dprint(trace_ent.classname); // dprint(" at end of trace- ok to duck!\n"); return TRUE; } else return FALSE; } float mezzo_check_jump (entity proj) { float impact_hite, jump_hite; vector proj_dir, proj_top; if(!self.flags&FL_ONGROUND) return FALSE; proj_dir=normalize(proj.velocity); proj_top=proj.origin; proj_top_z=proj.absmax_z; traceline(proj_top,proj_top+proj_dir*1000,FALSE,proj); if(trace_ent!=self) return FALSE; impact_hite=trace_endpos_z; tracearea(self.origin,self.origin+'0 0 256',self.mins,self.maxs,FALSE,self); jump_hite=trace_fraction*256; if(jump_hite<24) return FALSE; else if(jump_hite>133) jump_hite=133; else if(jump_hite<77) jump_hite=77; if(self.origin_z+jump_hite/2>impact_hite+proj.maxs_z&&random()<0.7) { self.velocity_z=jump_hite*3; self.flags(-)FL_ONGROUND; return TRUE; } return FALSE; } void mezzo_choose_roll (entity proj) { float proj_dir; proj_dir=check_heading_left_or_right(proj); if(proj_dir==0) { if(mezzo_check_duck(proj)) { thinktime self : 0; self.think=mezzo_duck; } else { thinktime self : 0; self.think=mezzo_block; } return; } else { //FIXME: Probably shouldn't try to roll in the other direction makevectors(self.angles); if(solid_under(self.origin, self.origin+v_right*105*proj_dir)) tracearea(self.origin, self.origin+v_right*105*proj_dir,self.mins,self.maxs,FALSE,self); else trace_fraction=FALSE; if(trace_fraction==1) { traceline(trace_endpos, trace_endpos-'0 0 300',TRUE,self); if(pointcontents(trace_endpos)!=CONTENT_EMPTY) trace_fraction=FALSE; else trace_fraction=TRUE; } if(trace_fraction==1) { if(proj_dir>0) { thinktime self : 0; self.think=mezzo_roll_right; } else { thinktime self : 0; self.think=mezzo_roll_left; } return; } else if(mezzo_check_duck(proj)) { thinktime self : 0; self.think=mezzo_duck; } else { thinktime self : 0; self.think=mezzo_block; } /* { tracearea(self.origin, self.origin+v_right*36*proj_dir*-1,self.mins,self.maxs,FALSE,self); if(trace_fraction==1) { if(proj_dir*-1>0) { thinktime self : 0; self.think=mezzo_roll_right; } else { thinktime self : 0; self.think=mezzo_roll_left; } return; } } */ } } void mezzo_check_defense () { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); //NOTE: Add random chance of failure based on difficulty level - highest diff means no chance of failure here if(skill+self.strength/5<random(6)) return; if((self.enemy.last_attack+0.5<time&&self.oldenemy.last_attack+0.5<time)||self.aflag) return; entity enemy_proj; float r; enemy_proj=look_projectiles(); if(!enemy_proj) if(lineofsight(self,self.enemy)) { enemy_proj=self.enemy; self.level=vlen(self.enemy.origin-self.origin)/1000; } else return; if(self.flags&FL_ONGROUND) self.velocity='0 0 0';//Clear velocity from last jump so he doesn't go nuts r=range(enemy_proj); if(self.enemy.weapon==IT_WEAPON1&&r<=RANGE_NEAR&&self.enemy.playerclass!=CLASS_SUCCUBUS) { thinktime self : 0; if(r==RANGE_MELEE) { if(random()<0.7||self.enemy.v_angle_x>=0) self.think=mezzo_duck; else if(self.think==mezzo_block_wait) { self.t_width=time+1; return; } else if(self.think==mezzo_run_loop||random()<0.3) self.think=mezzo_charge; else self.think=mezzo_block; return; } else if(random()<0.5) mezzo_choose_roll(enemy_proj); else if(random()<0.7||self.enemy.v_angle_x>=0) self.think=mezzo_duck; else if(self.think==mezzo_block_wait) { self.t_width=time+1; return; } else if(self.think==mezzo_block_wait) { self.t_width=time+1; return; } else if(self.think==mezzo_run_loop||random()<0.3) self.think=mezzo_charge; else self.think=mezzo_block; return; } if(self.level>0.3)//I've got 0.3 seconds before impact { mezzo_choose_roll(enemy_proj); return; } else if(mezzo_check_duck(enemy_proj)) { thinktime self : 0; tracearea(self.origin,self.origin+v_forward*64,self.mins,'16 16 20',FALSE,self); if(trace_fraction<1||random()<0.2||!infront(enemy_proj)) self.think=mezzo_duck; else self.think=mezzo_roll_forward; return; } else if(mezzo_check_jump(enemy_proj)) { self.think=mezzo_jump; enemy_infront=infront(self.enemy); enemy_vis=visible(self.enemy); trace_fraction=0; if((random()<0.3||self.think==mezzo_run_loop)&&enemy_infront&&enemy_vis&&self.enemy!=world)//Jump towards enemy { vector enemy_dir; enemy_dir=normalize(self.enemy.origin-self.origin); traceline(self.origin,self.origin+enemy_dir*64+'0 0 56',FALSE,self); if(trace_fraction==1) { traceline(trace_endpos,trace_endpos-'0 0 300',TRUE,self); if(pointcontents(trace_endpos)==CONTENT_EMPTY) { self.velocity_x=self.velocity_y=0; self.velocity+=enemy_dir*vlen(self.enemy.origin-self.origin); trace_fraction=1; if(random()<0.7) self.think=mezzo_roll_forward; else self.think=self.th_jump; } else { // dprint("might land in water or lava\n"); trace_fraction=0; } } else { // dprint("not enough room in front \n"); trace_fraction=0; } } // dprint(ftos(trace_fraction)); // dprint(" is the trace_fraction\n"); if(random()<0.5&&trace_fraction<1)//Jump to side { // dprint("checking to sides\n"); if(random()<0.5) r=1; else r=-1; makevectors(self.angles); traceline(self.origin,self.origin+v_right*36*r+'0 0 56',FALSE,self); if(trace_fraction<1) { traceline(self.origin,self.origin-v_right*36*r+'0 0 56',FALSE,self); if(trace_fraction<1) { // dprint("not enough room to jump on that side\n"); self.think=mezzo_jump; } else { traceline(trace_endpos,trace_endpos-'0 0 300',TRUE,self); if(pointcontents(trace_endpos)!=CONTENT_EMPTY) { // dprint("might jump into water or lava\n"); self.think=mezzo_jump; } else { self.velocity-=v_right*r*200; if(r*-1>0) self.think=mezzo_roll_right; else self.think=mezzo_roll_left; } } } else { traceline(trace_endpos,trace_endpos-'0 0 300',TRUE,self); if(pointcontents(trace_endpos)!=CONTENT_EMPTY) { // dprint("might jump into water or lava\n"); self.think=mezzo_jump; } else { self.velocity+=v_right*r*200; if(r>0) self.think=mezzo_roll_right; else self.think=mezzo_roll_left; } } } thinktime self : 0; if(self.think!=mezzo_jump&&self.think!=mezzo_roll_right&&self.think!=mezzo_roll_left&&self.think!=mezzo_roll_forward) { // dprint("What the FUCK!!!\n"); self.think=mezzo_jump; } // return; } else if(infront(enemy_proj)&&random()<0.5) { thinktime self : 0; if(self.think==mezzo_block_wait) { self.t_width=time+1; return; } else if(self.think==mezzo_run_loop||random()<0.3) self.think=mezzo_charge; else self.think=mezzo_block; return; } } void() mezzo_charge_stop; void mezzo_slam () { if(!other.movetype||other.mass>100||other.solid==SOLID_BSP) return; if(!infront(other)||other.safe_time>time) return; if(other.origin_z>self.absmax_z - 6||other.absmax_z<self.origin_z + 6) return; sound(self,CHAN_VOICE,"mezzo/slam.wav",1,ATTN_NORM); float inertia; if(other.mass<10) inertia=1; else inertia=other.mass/10; vector punchdir; makevectors(self.angles); punchdir=v_forward*300+'0 0 100'; T_Damage(other,self,self,5*(self.strength+1)*(self.aflag+1)*(coop + 1)); other.velocity+=punchdir*(1/inertia); other.flags(-)FL_ONGROUND; self.ltime+=1; other.safe_time=time+1.25;//So can't kill them instantly if they're moving against him or pinned on a wall if(self.think!=mezzo_charge_stop && self.flags2&FL_ALIVE) { thinktime self : 0; self.think=mezzo_charge_stop; } } void mezzo_reflect_trig_touch () { //vector newv; vector org, vec, dir;//, endspot,endplane, dif; float magnitude;//remainder, reflect_count, if (other.flags & FL_MONSTER || other.flags & FL_CLIENT || !other || other == self) return; if (other.safe_time>time) return; if(!self.owner) // fix the "assignment to world entity" bug { remove(self); return; } if(!self.owner.flags2&FL_ALIVE||self.owner.frozen>0) { if(self.owner.movechain==self) self.owner.movechain=world; remove(self); // return; // fix the "assignment to world entity" bug } if(other.classname=="funnal"||other.classname=="tornato") return; dir = normalize(other.velocity); magnitude=vlen(other.velocity); org = other.origin; vec = org + dir*100; traceline (org, vec, FALSE, other); if(trace_ent!=self.owner) return; if(self.owner.classname=="monster_mezzoman") sound(self,CHAN_AUTO,"mezzo/slam.wav",1,ATTN_NORM); if(!self.owner.strength&&self.owner.classname=="monster_mezzoman") {//Just block it if(!other.flags2&FL_ALIVE) other.flags2(+)FL_NODAMAGE; } else {//reflect! if(self.owner.classname!="monster_mezzoman") { sound (self, CHAN_WEAPON, "fangel/deflect.wav", 1, ATTN_NORM); CreateWhiteFlash(trace_endpos); if(self.owner.classname=="monster_fallen_angel")//deflect { dir=dir*-1; makevectors(dir); dir=v_forward + v_up*random(-0.75,.75) + v_right*random(-0.75,.75); dir=normalize(dir); } else// if(visible(other.owner))//reflect { v_forward=normalize(other.owner.origin+other.owner.view_ofs-other.origin); dir+= 2*v_forward; dir=normalize(dir); } // else // dir=dir*-1; } else { sound(self,CHAN_AUTO,"mezzo/reflect.wav",1,ATTN_NORM); starteffect(CE_MEZZO_REFLECT,self.origin); if(self.owner.strength>=3&&other.owner!=world)//Tiger reflects dir=normalize(other.owner.origin+other.owner.view_ofs-other.origin); else//others deflect { makevectors(trace_ent.angles); dir+= 2*v_forward; dir=normalize(dir); } } if(other.movedir) other.movedir=dir; if(other.o_angle) other.o_angle=dir; if(magnitude<other.speed) { // dprintf("Low mag : %s\n",magnitude); magnitude=other.speed; } other.velocity = dir*magnitude; other.angles = vectoangles(other.velocity); self.owner.last_attack=time; other.safe_time=time+100/magnitude; if(!other.controller) other.controller=other.owner; if(other.enemy==self.owner) other.enemy=other.owner; if(other.goalentity==self.owner) other.goalentity=other.owner; other.owner=self.owner; } } void reflect_think () { makevectors(self.owner.angles); setorigin(self,self.owner.origin+ v_forward*48+'0 0 40'); self.think=reflect_think; thinktime self : 0.05; } void spawn_reflect () { //FIXME: Picks up enemy missile as shield! shield not necc? makevectors(self.angles); newmis=spawn(); self.shield=newmis; newmis.movetype = MOVETYPE_NOCLIP; newmis.solid = SOLID_TRIGGER; newmis.owner = self; newmis.touch = mezzo_reflect_trig_touch; newmis.classname="mezzo_reflect"; newmis.effects=EF_NODRAW; setmodel(newmis,"models/null.spr"); if(self.classname=="monster_mezzoman") { setsize (newmis, '-32 -32 -10','32 32 30'); setorigin(newmis,self.origin+ v_forward*48+'0 0 40'); newmis.think=reflect_think; thinktime newmis : 0; } else { self.movechain=newmis; setsize (newmis, '-48 -48 -64','48 48 50'); setorigin(newmis,self.origin); } } void mezzo_clobber() [++ $clober1 .. $clober16] { float zofs; ai_charge(1); if(self.frame==$clober7) { makevectors(self.angles); zofs = self.enemy.origin_z - self.origin_z; if(zofs>20) zofs=20; else if(zofs<-20) zofs=-20; traceline(self.origin+'0 0 30',self.origin+'0 0 30'+v_forward*36+v_up*zofs,FALSE,self); if(trace_fraction==1) return; sound(self,CHAN_VOICE,"mezzo/slam.wav",1,ATTN_NORM); if(trace_ent.movetype&&trace_ent.movetype!=MOVETYPE_PUSH) trace_ent.velocity+=v_forward*200-v_right*100+'0 0 100'; if(trace_ent.takedamage) T_Damage(trace_ent,self,self,5*(self.strength+1)*(self.aflag+1)*(coop + 1)); if(trace_ent.classname=="player") if(infront_of_ent(self,trace_ent)) trace_ent.punchangle_y=4; } else if(cycle_wrapped) { if(skill>=4) self.attack_finished=0; else self.attack_finished=time+0.5; thinktime self : 0; self.think=self.th_run; } else if(self.frame==$clober1) { self.last_attack=time; if(random()<0.5) sound(self,CHAN_VOICE,"mezzo/attack.wav",1,ATTN_NORM); } } void mezzo_sword() [++ $sword1 .. $sword13] { ai_face(); ai_charge(3); if(cycle_wrapped) { if(skill>=4) self.attack_finished=0; else self.attack_finished=time+0.3; thinktime self : 0; self.think=self.th_run; } else if(self.frame==$sword1) { self.last_attack=time; sound(self,CHAN_WEAPON,"weapons/vorpswng.wav",1,ATTN_NORM); if(random()<0.5) sound(self,CHAN_VOICE,"mezzo/attack.wav",1,ATTN_NORM); } else if(self.frame>=$sword6 && self.frame<=$sword10) { float ofs,zofs; vector dir; makevectors(self.angles); ofs=($sword10 - self.frame)*4; dir=v_right*(ofs - 8)+v_forward*(48 - fabs(16 - ofs))+'0 0 1'*(ofs - 8); dir=normalize(dir); zofs = (self.enemy.origin_z+self.enemy.view_ofs_z) - (self.origin_z+37); if(zofs>36) zofs=36; else if(zofs<-36) zofs=-36; traceline(self.origin+'0 0 37'+'0 0 1'*zofs,self.origin+'0 0 37'+dir*48+'0 0 1'*zofs,FALSE,self); if(trace_fraction==1) return; if(self.t_width<time) { MetalHitSound(trace_ent.thingtype); self.t_width=time+1; } if(trace_ent.takedamage) T_Damage(trace_ent,self,self,(2+skill)*(self.strength+1)*(self.aflag+1)*(coop + 1)); if(trace_ent.thingtype==THINGTYPE_FLESH&&self.frame==$sword9) { MeatChunks (trace_endpos,v_right*random(-100,-300)+'0 0 200', 3,trace_ent); sound(self,CHAN_AUTO,"weapons/slash.wav",1,ATTN_NORM); } SpawnPuff (trace_endpos, '0 0 0', 3,trace_ent); } } void mezzo_melee () { if(random()<0.3) self.think=mezzo_clobber; else self.think=mezzo_sword; thinktime self : 0; } void mezzo_missile () { if(vlen(self.enemy.origin-self.origin)<84&&lineofsight(self.enemy,self)) self.think=mezzo_charge; else self.think=self.th_run; thinktime self : 0; } void mezzo_die () [++ $death1 .. $death16] { if(self.shield) if(self.shield.classname=="mezzo_reflect" && self.shield.owner==self) remove(self.shield); if (self.health < -40) { chunk_death(); return; } if(self.frame==$death1) sound(self,CHAN_VOICE,"mezzo/die.wav",1,ATTN_NORM); else if(self.frame==$death12) sound(self,CHAN_BODY,"player/land.wav",1,ATTN_NORM); else if(self.frame==$death16) MakeSolidCorpse(); thinktime self : 0.1; } void mezzo_pain_seq () [++ $pain1 .. $pain7] { ai_back(1); if(cycle_wrapped) { thinktime self : 0; if(!self.flags&FL_ONGROUND) self.think=mezzo_in_air; else self.think=self.th_run; } } void mezzo_pain (entity attacker, float damage) { if(self.monster_awake) if(random(self.health)>damage*3||self.pain_finished>time)//only react to 33 percent of current health damage return; self.monster_awake=TRUE; if(self.shield) if(self.shield.classname=="mezzo_reflect" && self.shield.owner==self) remove(self.shield); if(self.health<=100) { self.th_pain=SUB_Null; if(self.health<=100) { if(random()<0.5) { self.oldthink=self.th_run; self.think=mezzo_roar; self.speed=15; self.yaw_speed=20; self.aflag=TRUE;//Berzerk! } else if(!self.flags&FL_ONGROUND) self.think=mezzo_in_air; else self.think=self.th_run; } } else { sound(self,CHAN_VOICE,"mezzo/pain.wav",1,ATTN_NORM); if(!self.enemy||!visible(self.enemy)) { if(self.enemy!=world&&self.enemy!=attacker) self.oldenemy=self.enemy; self.enemy=attacker; } self.pain_finished=time+1+self.strength; self.think=mezzo_pain_seq; } thinktime self : 0; } void mezzo_land () [++ $jump13 .. $jump22] { //SOUND? self.touch=SUB_Null; if(cycle_wrapped) { thinktime self : 0; self.think=self.th_run; } else if(self.frame==$jump13) sound(self,CHAN_BODY,"player/land.wav",1,ATTN_NORM); } void mezzo_in_air () { // dprint("in air\n"); self.frame=$jump12; if(!self.flags&FL_ONGROUND) { if(random()<0.1) { tracearea(self.origin,self.origin + '0 0 -1',self.mins,self.maxs,FALSE,self); if(trace_fraction<1&&(trace_ent.solid==SOLID_BBOX||trace_ent.solid==SOLID_SLIDEBOX)) self.flags(+)FL_ONGROUND; } } if(self.flags&FL_ONGROUND) { thinktime self : 0; self.think=mezzo_land; } else { if(self.velocity=='0 0 0') self.velocity='0 0 -60'; self.think=mezzo_in_air; if(vlen(self.velocity)>300) { if(random()<0.5) { self.dflags=TRUE;//in air self.think=mezzo_roll_forward; } } thinktime self : 0.05; } } void mezzo_jump () [++ $jump1 .. $jump11] { //SOUND? ai_face(); self.touch=impact_touch_hurt_no_push; if(self.flags&FL_ONGROUND) { thinktime self : 0; self.think=mezzo_land; } else if(self.frame==$jump11) { thinktime self : 0.05; self.think=mezzo_in_air; } } void mezzo_charge_stop () [++ $charge15 .. $charge25] { if(cycle_wrapped) { self.touch=obj_push; thinktime self : 0; self.think=self.th_run; } if(!walkmove(self.angles_y,$charge25 - self.frame,FALSE)) { if(!self.ltime) self.think=mezzo_pain_seq; else self.think=self.th_run; thinktime self : 0; } } void mezzo_charge_leap () [++ $charge9 .. $charge14] { //SOUND? if(cycle_wrapped) { thinktime self : 0; self.think=mezzo_charge_stop; } else if(self.frame==$charge9) { makevectors(self.angles); traceline(self.origin+'0 0 25',self.origin+'0 0 25'+v_forward*256,FALSE,self); //Used to make him not charge if you stepped aside, now //only checks if will fall if(!trace_ent.takedamage) { self.think=mezzo_skid; thinktime self : 0; } else { traceline(trace_endpos,trace_endpos-'0 0 300',TRUE,self); if(pointcontents(trace_endpos)!=CONTENT_EMPTY||trace_fraction==1) { self.think=mezzo_skid; thinktime self : 0; } else if(self.flags&FL_ONGROUND) { if(random()<0.5) sound(self,CHAN_VOICE,"mezzo/attack.wav",1,ATTN_NORM); self.velocity=v_forward*700+'0 0 133'; self.flags(-)FL_ONGROUND; } else { self.think=mezzo_in_air; thinktime self : 0; } } } } void mezzo_charge () [++ $charge1 .. $charge8] { if(cycle_wrapped) { thinktime self : 0; self.think=mezzo_charge_leap; } else if(self.frame==$charge1) { self.last_attack=time; self.ltime=0; self.touch=mezzo_slam; if(skill>=4) self.attack_finished=0; else self.attack_finished=time+1.25; } walkmove(self.angles_y,15,FALSE); } void mezzo_block_return () [-- $block6 .. $block1] { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); if(cycle_wrapped) { float r; if(self.shield) if(self.shield.classname=="mezzo_reflect" && self.shield.owner==self) remove(self.shield); r=vlen(self.enemy.origin-self.origin); if(infront(self.enemy)&&r<100) { thinktime self : 0; self.think=self.th_melee; } // else if(random()<0.2&&r<177) // { // thinktime self : 0; // self.think=self.th_stand; // } else { thinktime self : 0; self.think=self.th_run; } } } void mezzo_block_wait () { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); self.think=mezzo_block_wait; if(self.t_width<time) { thinktime self : 0; self.think=mezzo_block_return; } else { self.frame=$block6; ai_face(); self.think=mezzo_block_wait; thinktime self : 0.05; } if(range(self.enemy)==RANGE_MELEE) if(CheckAnyAttack()) return; if(!self.flags&FL_ONGROUND) { // dprint("what the fuck?! off ground while blocking?!\n"); if(!self.velocity_x&&!self.velocity_y) self.think=mezzo_in_air; else self.think=mezzo_roll_forward; thinktime self : 0; } if(self.shield) if(self.shield.classname=="mezzo_reflect" && self.shield.owner==self) { self.shield.oldthink=self.shield.think; self.shield.think=SUB_Remove; thinktime self.shield : 0.2; } // dprint("checking defense from block\n"); mezzo_check_defense(); if(self.think==mezzo_block_wait) if(self.shield) if(self.shield.classname=="mezzo_reflect" && self.shield.owner==self) { self.shield.think=self.shield.oldthink; thinktime self.shield : 0; } // else // dprint("wigging!\n"); } void mezzo_block () [++ $block1 .. $block6] { walkmove(self.angles_y,-1,FALSE); // dprint("blocking\n"); // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); if(cycle_wrapped) { if(self.th_pain==SUB_Null&&self.health>77) self.th_pain=mezzo_pain; self.t_width=time+1; thinktime self : 0; self.think=mezzo_block_wait; } else if(self.frame==$block1) spawn_reflect(); } void mezzo_skid () [++ $block1 .. $block6] { float skidspeed, anim_stretch; anim_stretch = 3; skidspeed=$block6 - self.frame + anim_stretch - self.level; if(walkmove(self.angles_y,skidspeed*2,FALSE)) { particle(self.origin, '0 0 20'*skidspeed, 344, skidspeed); if(random()<0.2) CreateWhiteSmoke(self.origin,'0 0 8',HX_FRAME_TIME * 2); } else { thinktime self : 0; self.think=mezzo_block_return; return; } if(cycle_wrapped) { if(skill>=4) self.attack_finished=0; else self.attack_finished=time+3; thinktime self : 0; self.think=mezzo_block_return; } else if(self.frame==$block1) { spawn_reflect(); sound(self,CHAN_AUTO,"mezzo/skid.wav",1,ATTN_NORM); } else if(self.level<anim_stretch) { self.frame-=1; self.level+=1; } else self.level=0; } void mezzo_roar () [++ $roar1 .. $roar30] { self.health+=1.1; if(self.health>self.max_health) self.max_health=self.health; if(self.frame==$roar30) { if(!self.aflag) self.th_pain=mezzo_pain; if(!self.takedamage) self.takedamage=DAMAGE_YES; self.last_attack=time+3; thinktime self : 0; self.think=self.oldthink; } else if(self.frame==$roar1) { self.monster_awake=TRUE; if(self.health<100) { self.th_pain=SUB_Null; self.takedamage=DAMAGE_NO; } sound(self,CHAN_VOICE,"mezzo/roar.wav",1,ATTN_NORM); } else if(self.frame==$roar19) thinktime self : 2; if(self.takedamage) mezzo_check_defense(); } void mezzo_run_think () { // if(self.shield.velocity!='0 0 0'&&self.shield.model!="models/null.spr") // dprint("what the?\n"); mezzo_check_defense(); /* if(!self.flags&FL_ONGROUND) { if(self.velocity=='0 0 0') self.velocity='0 0 -60'; else if(random()<0.5) self.think=mezzo_roll_forward; else self.think=mezzo_in_air; thinktime self : 0; } */ // if(!self.flags2&FL_ALIVE) // dprint("Undead Mezzoman!!!\n"); if(!self.takedamage) { // dprint("Invincible Mezzoman!!!\n"); self.takedamage=DAMAGE_YES; } if(!self.enemy.flags2&FL_ALIVE&&self.enemy!=world) { self.monster_awake=FALSE; if(visible(self.enemy)&&infront(self.enemy)) { self.oldthink=self.th_stand; self.think=mezzo_roar; } else self.think=self.th_stand; if(self.oldenemy.flags2&FL_ALIVE) { self.enemy=self.oldenemy; self.oldenemy=world; self.think=self.th_run; } else self.enemy=world; thinktime self : 0; } else if(self.enemy!=world) { if(visible(self.enemy)) { float dist; dist=vlen(self.enemy.origin-self.origin); if(dist<177&&dist>33) { if(random()<0.5&&lineofsight(self.enemy,self)) { thinktime self : 0; self.think=mezzo_charge; } else if(dist>84&&self.last_attack<time&&infront(self.enemy)) { thinktime self : 0; self.think=mezzo_skid; } } else if(!infront(self.enemy)) { if(self.last_attack<time&&random()<0.5) { if(!self.aflag) self.yaw_speed=10; self.last_attack=time+7; thinktime self : 0; self.think=mezzo_skid; } else self.yaw_speed=20; } else if(!self.aflag) self.yaw_speed=10; } else self.yaw_speed=10; ai_run(self.speed); } else { self.think=self.th_stand; thinktime self : 0; } } void mezzo_run_loop () [++ $run1 .. $run22] { mezzo_run_think(); } void mezzo_run () [++ $run6 .. $run22] { mezzo_check_defense(); self.last_attack=time+0.1;//So won't start running then skid suddenly if(!self.monster_awake) if(range(self.enemy)>RANGE_NEAR&&random()>0.3) { self.oldthink=self.th_run; self.think=mezzo_roar; thinktime self : 0; return; } else { sound(self,CHAN_VOICE,"mezzo/attack.wav",1,ATTN_NORM); self.monster_awake=TRUE; } if(cycle_wrapped) { self.think=mezzo_run_loop; thinktime self : 0; } else mezzo_run_think(); } void mezzo_walk () [++ $walk1 .. $walk30] { if(self.frame==$stand3 &&random()<0.1) mezzo_idle_sound(); mezzo_check_defense(); ai_walk(3); if(self.enemy) if(CheckAnyAttack()) return; } void()mezzo_stand; void mezzo_twirl() [++ $twirl1 .. $twirl10] { mezzo_check_defense(); if(cycle_wrapped) { self.think=mezzo_stand; thinktime self : 0; } else if(self.frame==$twirl1) { sound(self,CHAN_WEAPON,"weapons/vorpswng.wav",0.7,ATTN_NORM); if(random()<0.5) mezzo_idle_sound(); } ai_stand(); } void mezzo_stand2 () [-- $stand10 .. $stand1] { mezzo_check_defense(); if(self.level<3&&self.frame<$stand10) { self.level+=1; self.frame+=1; } else self.level=0; if(self.frame==$stand1) { if(random()<0.1||(self.monster_awake&&random()<0.5)) self.think=mezzo_twirl; else self.think=mezzo_stand; thinktime self : 0; return; } else if(self.frame==$stand10 &&random()<0.1) mezzo_idle_sound(); /* if(self.monster_awake) { float r; r=vlen(self.enemy.origin-self.origin); if(random()<0.1||r>177) { if(r>177) self.think=self.th_run; else if(enemy_infront&&enemy_vis&&r<133) self.think=mezzo_charge; else if(random()<0.5) self.think=self.th_run; else self.think=self.th_walk; thinktime self : 0; } else { if(random()<0.8&&r>100) self.attack_finished=time+0.1; ai_run(0); } } else */ ai_stand(); } void mezzo_stand () [++ $stand1 .. $stand10] { if(random()<0.5) { mezzo_check_defense(); if((!self.enemy.flags2&FL_ALIVE&&self.enemy!=world)||self.enemy==world) { self.monster_awake=FALSE; if(self.oldenemy.flags2&FL_ALIVE) { self.enemy=self.oldenemy; self.oldenemy=world; } else self.enemy=world; } } if(self.level<3&&self.frame>$stand1) { self.level+=1; self.frame-=1; } else self.level=0; if(self.frame==$stand10) { self.think=mezzo_stand2; thinktime self : 0; return; } else if(self.frame==$stand1 &&random()<0.1) mezzo_idle_sound(); if(random()<0.5) ai_stand(); } /*QUAKED monster_werejaguar (1 0.3 0) (-16 -16 0) (16 16 56) AMBUSH STUCK JUMP x DORMANT WereCat with jaguar skin "health" - default 250 "experience_value" - default 150 If they're targetted by a trigger and used, they'll atack the activator of the target If they can't see the activator, they'll roll left or right (in the direction of the activator) Their roll is 128 units long, so place the mezzoman 128 units away from where you want the roll to stop My babies!!! - MG */ //IDEA: Have mezzoman do ai_face while in air or rolling so always faces you when lands/gets up? void() monster_werejaguar = { if (deathmatch) { remove(self); return; } if(!self.th_init) { self.th_init=monster_werejaguar; self.init_org=self.origin; } if (!self.flags2 & FL_SUMMONED&&!self.flags2&FL2_RESPAWN) { precache_model2 ("models/mezzoref.spr"); precache_sound2 ("mezzo/skid.wav"); precache_sound2 ("mezzo/roar.wav"); precache_sound2 ("mezzo/reflect.wav"); precache_sound2 ("mezzo/slam.wav"); precache_sound2 ("mezzo/pain.wav"); precache_sound2 ("mezzo/die.wav"); precache_sound2 ("mezzo/growl.wav"); precache_sound2 ("mezzo/snort.wav"); precache_sound2 ("mezzo/attack.wav"); } self.solid = SOLID_SLIDEBOX; self.takedamage=DAMAGE_YES; self.thingtype=THINGTYPE_FLESH; self.movetype = MOVETYPE_STEP; self.view_ofs = '0 0 53'; self.speed=10; self.yaw_speed = 10; self.experience_value = 150; self.monsterclass = CLASS_HENCHMAN; self.mass = 10; self.mintel = 15;//Animal sense of smell makes him a good tracker self.noise="mezzo/attack.wav"; if(self.classname=="monster_weresnowleopard") { self.monsterclass = CLASS_LEADER; self.experience_value = 350; if(!self.health) self.health=475; self.scale=0.8+random(0.2); self.drawflags(+)SCALE_ORIGIN_BOTTOM; if (!self.flags2 & FL_SUMMONED&&!self.flags2&FL2_RESPAWN) precache_model4 ("models/snowleopard.mdl"); setmodel (self, "models/snowleopard.mdl"); } else if(self.classname=="monster_weretiger") { self.speed=12; self.monsterclass = CLASS_LEADER; self.experience_value = 400; if(!self.health) self.health=650; self.skin=1; self.scale=1+random(0.2); self.drawflags(+)SCALE_ORIGIN_BOTTOM; if (!self.flags2 & FL_SUMMONED&&!self.flags2&FL2_RESPAWN) { precache_model4 ("models/snowleopard.mdl"); precache_model4 ("models/h_mez2.mdl"); } self.headmodel="models/h_mez2.mdl"; setmodel (self, "models/snowleopard.mdl"); } else { if (!self.flags2 & FL_SUMMONED&&!self.flags2&FL2_RESPAWN) { precache_model2 ("models/mezzoman.mdl"); precache_model2 ("models/h_mez.mdl"); } self.headmodel="models/h_mez.mdl"; setmodel (self, "models/mezzoman.mdl"); if(self.classname=="monster_werepanther") { self.monsterclass = CLASS_LEADER; self.experience_value = 300; if(!self.health) self.health=400; self.skin=1; } else if(!self.health) self.health = 250; } if(!self.max_health) self.max_health=self.health; self.strength=self.skin; if(self.model=="models/snowleopard.mdl") self.strength=(self.strength+1)*2; self.classname="monster_mezzoman"; self.mass*=self.scale; self.th_stand=mezzo_stand; self.th_walk=mezzo_walk; self.th_run=mezzo_run; self.th_pain=mezzo_pain; self.th_melee=mezzo_melee; self.th_missile=mezzo_missile; self.th_jump=mezzo_jump; self.th_die=mezzo_die; self.spawnflags (+) JUMP; setsize (self, '-16 -16 0', '16 16 56'); self.frame=$stand1; self.init_exp_val = self.experience_value; walkmonster_start(); }; void monster_mezzoman (void) { monster_werejaguar(); } /*QUAKED monster_werepanther (1 0.3 0) (-16 -16 0) (16 16 56) AMBUSH STUCK JUMP x DORMANT WereCat with panther skin "health" - default 400 "experience_value" - default 300 If they're targetted by a trigger and used, they'll atack the activator of the target If they can't see the activator, they'll roll left or right (in the direction of the activator) Their roll is 128 units long, so place the mezzoman 128 units away from where you want the roll to stop My babies!!! - MG */ void monster_werepanther (void) { if(!self.th_init) { self.th_init=monster_werepanther; self.init_org=self.origin; } monster_werejaguar(); } /*QUAKED monster_weresnowleopard (1 0.3 0) (-16 -16 0) (16 16 56) AMBUSH STUCK JUMP x DORMANT WereCat with snow leopard skin "health" - default 475 "experience_value" - default 350 If they're targeted by a trigger and used, they'll attack the activator of the target If they can't see the activator, they'll roll left or right (in the direction of the activator) Their roll is 128 units long, so place the mezzoman 128 units away from where you want the roll to stop My babies!!! - MG */ void monster_weresnowleopard (void) { if(!self.th_init) { self.th_init=monster_weresnowleopard; self.init_org=self.origin; } monster_werejaguar(); } /*QUAKED monster_weretiger (1 0.3 0) (-16 -16 0) (16 16 56) AMBUSH STUCK JUMP x DORMANT WereCat with Siberian Tiger skin "health" - default 650 "experience_value" - default 400 Toughest and biggest catman If they're targeted by a trigger and used, they'll attack the activator of the target If they can't see the activator, they'll roll left or right (in the direction of the activator) Their roll is 128 units long, so place the mezzoman 128 units away from where you want the roll to stop My babies!!! - MG */ void monster_weretiger (void) { if(!self.th_init) { self.th_init=monster_weretiger; self.init_org=self.origin; } monster_werejaguar(); }
1
0.948057
1
0.948057
game-dev
MEDIA
0.982894
game-dev
0.92878
1
0.92878
rjmarsan/Weka-for-Android
79,229
src/weka/associations/FPGrowth.java
/* * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * FPGrowth.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand * */ package weka.associations; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.OptionHandler; import weka.core.RevisionUtils; import weka.core.SelectedTag; import weka.core.SparseInstance; import weka.core.TechnicalInformation; import weka.core.TechnicalInformationHandler; import weka.core.Utils; import weka.core.Capabilities.Capability; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; /** <!-- globalinfo-start --> * Class implementing the FP-growth algorithm for finding large item sets without candidate generation. Iteratively reduces the minimum support until it finds the required number of rules with the given minimum metric. For more information see:<br/> * <br/> * J. Han, J.Pei, Y. Yin: Mining frequent patterns without candidate generation. In: Proceedings of the 2000 ACM-SIGMID International Conference on Management of Data, 1-12, 2000. * <p/> <!-- globalinfo-end --> * <!-- technical-bibtex-start --> * BibTeX: * <pre> * &#64;inproceedings{Han2000, * author = {J. Han and J.Pei and Y. Yin}, * booktitle = {Proceedings of the 2000 ACM-SIGMID International Conference on Management of Data}, * pages = {1-12}, * title = {Mining frequent patterns without candidate generation}, * year = {2000} * } * </pre> * <p/> <!-- technical-bibtex-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -P &lt;attribute index of positive value&gt; * Set the index of the attribute value to consider as 'positive' * for binary attributes in normal dense instances. Index 2 is always * used for sparse instances. (default = 2)</pre> * * <pre> -I &lt;max items&gt; * The maximum number of items to include in large items sets (and rules). (default = -1, i.e. no limit.)</pre> * * <pre> -N &lt;require number of rules&gt; * The required number of rules. (default = 10)</pre> * * <pre> -T &lt;0=confidence | 1=lift | 2=leverage | 3=Conviction&gt; * The metric by which to rank rules. (default = confidence)</pre> * * <pre> -C &lt;minimum metric score of a rule&gt; * The minimum metric score of a rule. (default = 0.9)</pre> * * <pre> -U &lt;upper bound for minimum support&gt; * Upper bound for minimum support. (default = 1.0)</pre> * * <pre> -M &lt;lower bound for minimum support&gt; * The lower bound for the minimum support. (default = 0.1)</pre> * * <pre> -D &lt;delta for minimum support&gt; * The delta by which the minimum support is decreased in * each iteration. (default = 0.05)</pre> * * <pre> -S * Find all rules that meet the lower bound on * minimum support and the minimum metric constraint. * Turning this mode on will disable the iterative support reduction * procedure to find the specified number of rules.</pre> * * <pre> -transactions &lt;comma separated list of attribute names&gt; * Only consider transactions that contain these items (default = no restriction)</pre> * * <pre> -rules &lt;comma separated list of attribute names&gt; * Only print rules that contain these items. (default = no restriction)</pre> * * <pre> -use-or * Use OR instead of AND for must contain list(s). Use in conjunction * with -transactions and/or -rules</pre> * <!-- options-end --> * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: 7060 $ */ public class FPGrowth extends AbstractAssociator implements AssociationRulesProducer, OptionHandler, TechnicalInformationHandler { /** For serialization */ private static final long serialVersionUID = 3620717108603442911L; /** * Class for maintaining a frequent item set. */ protected static class FrequentBinaryItemSet implements Serializable, Cloneable { /** For serialization */ private static final long serialVersionUID = -6543815873565829448L; /** The list of items in the item set */ protected ArrayList<BinaryItem> m_items = new ArrayList<BinaryItem>(); /** the support of this item set **/ protected int m_support; /** * Constructor * * @param items the items that make up the frequent item set. * @param support the support of this item set. */ public FrequentBinaryItemSet(ArrayList<BinaryItem> items, int support) { m_items = items; m_support = support; Collections.sort(m_items); } /** * Add an item to this item set. * * @param i the item to add. */ public void addItem(BinaryItem i) { m_items.add(i); Collections.sort(m_items); } /** * Set the support for this item set. * * @param support the support for this item set. */ public void setSupport(int support) { m_support = support; } /** * Get the support of this item set. * * @return the support of this item set. */ public int getSupport() { return m_support; } /** * Get the items in this item set. * * @return the items in this item set. */ public Collection<BinaryItem> getItems() { return m_items; } /** * Get a particular item from this item set. * * @param index the index of the item to get. * @return the item. */ public BinaryItem getItem(int index) { return m_items.get(index); } /** * Get the number of items in this item set. * * @return the number of items in this item set. */ public int numberOfItems() { return m_items.size(); } /** * Get a textual description of this item set. * * @return a textual description of this item set. */ public String toString() { StringBuffer buff = new StringBuffer(); Iterator<BinaryItem> i = m_items.iterator(); while (i.hasNext()) { buff.append(i.next().toString() + " "); } buff.append(": " + m_support); return buff.toString(); } /** * Make a copy of this item set. * * @return a copy of this item set. */ public Object clone() { ArrayList<BinaryItem> items = new ArrayList<BinaryItem>(m_items); return new FrequentBinaryItemSet(items, m_support); } } /** * Maintains a list of frequent item sets. */ protected static class FrequentItemSets implements Serializable { /** For serialization */ private static final long serialVersionUID = 4173606872363973588L; /** The list of frequent item sets */ protected ArrayList<FrequentBinaryItemSet> m_sets = new ArrayList<FrequentBinaryItemSet>(); /** The total number of transactions in the data */ protected int m_numberOfTransactions; /** * Constructor. * * @param numTransactions the total number of transactions in the data. */ public FrequentItemSets(int numTransactions) { m_numberOfTransactions = numTransactions; } /** * Get an item set. * * @param index the index of the item set to get. * @return an item set. */ public FrequentBinaryItemSet getItemSet(int index) { return m_sets.get(index); } /** * Get an iterator that can be used to access all the item sets. * * @return an iterator. */ public Iterator<FrequentBinaryItemSet> iterator() { return m_sets.iterator(); } /** * Get the total number of transactions in the data that the item * sets were derived from. * * @return the total number of transactions in the data. */ public int getNumberOfTransactions() { return m_numberOfTransactions; } /** * Add an item set. * * @param setToAdd the item set to add. */ public void addItemSet(FrequentBinaryItemSet setToAdd) { m_sets.add(setToAdd); } /** * Sort the item sets according to the supplied comparator. * * @param comp the comparator to use. */ public void sort(Comparator<FrequentBinaryItemSet> comp) { Collections.sort(m_sets, comp); } /** * Get the number of item sets. * * @return the number of item sets. */ public int size() { return m_sets.size(); } /** * Sort the item sets. Sorts by item set length. Ties are broken by comparing * the items in the two item sets. */ public void sort() { Comparator<FrequentBinaryItemSet> compF = new Comparator<FrequentBinaryItemSet>() { public int compare(FrequentBinaryItemSet one, FrequentBinaryItemSet two) { Collection<BinaryItem> compOne = one.getItems(); Collection<BinaryItem> compTwo = two.getItems(); // if (one.getSupport() == two.getSupport()) { // if supports are equal then list shorter item sets before longer ones if (compOne.size() < compTwo.size()) { return -1; } else if (compOne.size() > compTwo.size()) { return 1; } else { // compare items Iterator<BinaryItem> twoIterator = compTwo.iterator(); for (BinaryItem oneI : compOne) { BinaryItem twoI = twoIterator.next(); int result = oneI.compareTo(twoI); if (result != 0) { return result; } } return 0; // equal } // return 0; /* } else if (one.getSupport() > two.getSupport()) { // reverse ordering (i.e. descending by support) return -1; } */ // return 1; } }; sort(compF); } /** * Get a textual description of this list of item sets. * * @param numSets the number of item sets to display. * @return a textual description of the item sets. */ public String toString(int numSets) { if (m_sets.size() == 0) { return "No frequent items sets found!"; } StringBuffer result = new StringBuffer(); result.append("" + m_sets.size() + " frequent item sets found"); if (numSets > 0) { result.append(" , displaying " + numSets); } result.append(":\n\n"); int count = 0; for (FrequentBinaryItemSet i : m_sets) { if (numSets > 0 && count > numSets) { break; } result.append(i.toString() + "\n"); count++; } return result.toString(); } } /** * This class holds the counts for projected tree nodes * and header lists. */ protected static class ShadowCounts implements Serializable { /** For serialization */ private static final long serialVersionUID = 4435433714185969155L; /** Holds the counts at different recursion levels */ private ArrayList<Integer> m_counts = new ArrayList<Integer>(); /** * Get the count at the specified recursion depth. * * @param recursionLevel the depth of the recursion. * @return the count. */ public int getCount(int recursionLevel) { if (recursionLevel >= m_counts.size()) { return 0; } else { return m_counts.get(recursionLevel); } } /** * Increase the count at a given recursion level. * * @param recursionLevel the level at which to increase the count. * @param incr the amount by which to increase the count. */ public void increaseCount(int recursionLevel, int incr) { // basically treat the list like a stack where we // can add a new element, or increment the element // at the top if (recursionLevel == m_counts.size()) { // new element m_counts.add(incr); } else if (recursionLevel == m_counts.size() - 1) { // otherwise increment the top int n = m_counts.get(recursionLevel).intValue(); m_counts.set(recursionLevel, (n + incr)); } } /** * Remove the count at the given recursion level. * * @param recursionLevel the level at which to remove the count. */ public void removeCount(int recursionLevel) { if (recursionLevel < m_counts.size()) { m_counts.remove(recursionLevel); } } } /** * A node in the FP-tree. */ protected static class FPTreeNode implements Serializable { /** For serialization */ private static final long serialVersionUID = 4396315323673737660L; /** link to another sibling at this level in the tree */ protected FPTreeNode m_levelSibling; /** link to the parent node */ protected FPTreeNode m_parent; /** item at this node */ protected BinaryItem m_item; /** ID (for graphing the tree) */ protected int m_ID; /** the children of this node */ protected Map<BinaryItem, FPTreeNode> m_children = new HashMap<BinaryItem, FPTreeNode>(); /** counts associated with projected versions of this node */ protected ShadowCounts m_projectedCounts = new ShadowCounts(); /** * Construct a new node with the given parent link and item. * * @param parent a pointer to the parent of this node. * @param item the item at this node. */ public FPTreeNode(FPTreeNode parent, BinaryItem item) { m_parent = parent; m_item = item; } /** * Insert an item set into the tree at this node. Removes the first item * from the supplied item set and makes a recursive call to insert the * remaining items. * * @param itemSet the item set to insert. * @param headerTable the header table for the tree. * @param incr the amount by which to increase counts. */ public void addItemSet(Collection<BinaryItem> itemSet, Map<BinaryItem, FPTreeRoot.Header> headerTable, int incr) { Iterator<BinaryItem> i = itemSet.iterator(); if (i.hasNext()) { BinaryItem first = i.next(); FPTreeNode aChild; if (!m_children.containsKey(first)) { // not in the tree, so add it. aChild = new FPTreeNode(this, first); m_children.put(first, aChild); // update the header if (!headerTable.containsKey(first)) { headerTable.put(first, new FPTreeRoot.Header()); } // append new node to header list headerTable.get(first).addToList(aChild); } else { // get the appropriate child node aChild = m_children.get(first); } // update counts in header table headerTable.get(first).getProjectedCounts().increaseCount(0, incr); // increase the child's count aChild.increaseProjectedCount(0, incr); // proceed recursively itemSet.remove(first); aChild.addItemSet(itemSet, headerTable, incr); } } /** * Increase the projected count at the given recursion level at this * node * * @param recursionLevel the recursion level to increase the node count * at. * @param incr the amount by which to increase the count. */ public void increaseProjectedCount(int recursionLevel, int incr) { m_projectedCounts.increaseCount(recursionLevel, incr); } /** * Remove the projected count at the given recursion level for this * node. * * @param recursionLevel the recursion level at which to remove the count. */ public void removeProjectedCount(int recursionLevel) { m_projectedCounts.removeCount(recursionLevel); } /** * Get the projected count at the given recursion level for this node. * * @param recursionLevel the recursion level at which to get the count. * @return the count. */ public int getProjectedCount(int recursionLevel) { return m_projectedCounts.getCount(recursionLevel); } /** * Get the parent node. * * @return the parent node. */ public FPTreeNode getParent() { return m_parent; } /** * Get the item at this node. * * @return the item at this node. */ public BinaryItem getItem() { return m_item; } /** * Return a textual description of this node for a given recursion * level. * * @param recursionLevel the recursion depth to use. * @return a textual description of this node. */ public String toString(int recursionLevel) { return toString("", recursionLevel); } /** * Return a textual description of this node for a given recursion * level. * * @param prefix a prefix string to prepend. * @param recursionLevel the recursion level to use. * @return a textual description of this node. */ public String toString(String prefix, int recursionLevel) { StringBuffer buffer = new StringBuffer(); buffer.append(prefix); buffer.append("| "); buffer.append(m_item.toString()); buffer.append(" ("); buffer.append(m_projectedCounts.getCount(recursionLevel)); buffer.append(")\n"); for (FPTreeNode node : m_children.values()) { buffer.append(node.toString(prefix + "| ", recursionLevel)); } return buffer.toString(); } protected int assignIDs(int lastID) { int currentLastID = lastID + 1; m_ID = currentLastID; if (m_children != null) { Collection<FPTreeNode> kids = m_children.values(); for (FPTreeNode n : kids) { currentLastID = n.assignIDs(currentLastID); } } return currentLastID; } /** * Generate a dot graph description string for the tree. * * @param text a StringBuffer to store the graph description * in. */ public void graphFPTree(StringBuffer text) { if (m_children != null) { Collection<FPTreeNode> kids = m_children.values(); for (FPTreeNode n : kids) { text.append("N" + n.m_ID); text.append(" [label=\""); text.append(n.getItem().toString() + " (" + n.getProjectedCount(0) + ")\\n"); text.append("\"]\n"); n.graphFPTree(text); text.append("N" + m_ID + "->" + "N" + n.m_ID + "\n"); } } } } /** * Root of the FPTree */ private static class FPTreeRoot extends FPTreeNode { /** For serialization */ private static final long serialVersionUID = 632150939785333297L; /** * Stores a header entry for an FPTree */ protected static class Header implements Serializable { /** For serialization */ private static final long serialVersionUID = -6583156284891368909L; /** The list of pointers into the tree structure */ protected List<FPTreeNode> m_headerList = new LinkedList<FPTreeNode>(); /** Projected header counts for this entry */ protected ShadowCounts m_projectedHeaderCounts = new ShadowCounts(); /** * Add a tree node into the list for this header entry. * * @param toAdd the node to add. */ public void addToList(FPTreeNode toAdd) { m_headerList.add(toAdd); } /** * Get the list of nodes for this header entry. * * @return the list of nodes for this header entry. */ public List<FPTreeNode> getHeaderList() { return m_headerList; } /** * Get the projected counts for this header entry. * * @return the projected counts for this header entry. */ public ShadowCounts getProjectedCounts() { return m_projectedHeaderCounts; } } /** Stores the header table as mapped Header entries */ protected Map<BinaryItem, Header> m_headerTable = new HashMap<BinaryItem, Header>(); /** * Create a new FPTreeRoot. */ public FPTreeRoot() { super(null, null); } /** * Insert an item set into the tree. * * @param itemSet the item set to insert into the tree. * @param incr the increment by which to increase counters. */ public void addItemSet(Collection<BinaryItem> itemSet, int incr) { super.addItemSet(itemSet, m_headerTable, incr); } /** * Get the header table for this tree. * * @return the header table for this tree. */ public Map<BinaryItem, Header> getHeaderTable() { return m_headerTable; } public boolean isEmpty(int recursionLevel) { for (FPTreeNode c : m_children.values()) { if (c.getProjectedCount(recursionLevel) > 0) { return false; } } return true; } /** * Get a textual description of the tree at a given recursion * (projection) level. * * @param pad the string to use as a prefix for indenting nodes. * @param recursionLevel the recursion level (projection) to use. * @return the textual description of the tree. */ public String toString(String pad, int recursionLevel) { StringBuffer result = new StringBuffer(); result.append(pad); result.append("+ ROOT\n"); for (FPTreeNode node : m_children.values()) { result.append(node.toString(pad + "| ", recursionLevel)); } return result.toString(); } /** * Get a textual description of the header table for this tree. * * @param recursionLevel the recursion level to use. * @return a textual description of the header table for this * tree at a given recursion level. */ public String printHeaderTable(int recursionLevel) { StringBuffer buffer = new StringBuffer(); for (BinaryItem item : m_headerTable.keySet()) { buffer.append(item.toString()); buffer.append(" : "); buffer.append(m_headerTable.get(item).getProjectedCounts().getCount(recursionLevel)); buffer.append("\n"); } return buffer.toString(); } public void graphHeaderTable(StringBuffer text, int maxID) { for (BinaryItem item : m_headerTable.keySet()) { Header h = m_headerTable.get(item); List<FPTreeNode> headerList = h.getHeaderList(); if (headerList.size() > 1) { text.append("N" + maxID + " [label=\"" + headerList.get(0).getItem().toString() + " (" + h.getProjectedCounts().getCount(0) + ")" + "\" shape=plaintext]\n"); text.append("N" + maxID + "->" + "N" + headerList.get(1).m_ID + "\n"); for (int i = 1; i < headerList.size() - 1; i++) { text.append("N" + headerList.get(i).m_ID + "->" + "N" + headerList.get(i+1).m_ID + "\n"); } maxID++; } } } } private static void nextSubset(boolean[] subset) { for (int i = 0; i < subset.length; i++) { if (!subset[i]) { subset[i] = true; break; } else { subset[i] = false; } } } private static Collection<Item> getPremise(FrequentBinaryItemSet fis, boolean[] subset) { boolean ok = false; for (int i = 0; i < subset.length; i++){ if (!subset[i]) { ok = true; break; } } if (!ok) { return null; } List<Item> premise = new ArrayList<Item>(); ArrayList<Item> items = new ArrayList<Item>(fis.getItems()); for (int i = 0; i < subset.length; i++) { if (subset[i]) { premise.add(items.get(i)); } } return premise; } private static Collection<Item> getConsequence(FrequentBinaryItemSet fis, boolean[] subset) { List<Item> consequence = new ArrayList<Item>(); ArrayList<Item> items = new ArrayList<Item>(fis.getItems()); for (int i = 0; i < subset.length; i++) { if (!subset[i]) { consequence.add(items.get(i)); } } return consequence; } /** * Generate all association rules, from the supplied frequet item sets, * that meet a given minimum metric threshold. Uses a brute force approach. * * @param largeItemSets the set of frequent item sets * @param metricToUse the metric to use * @param metricThreshold the threshold value that a rule must meet * @param upperBoundMinSuppAsInstances the upper bound on the support * in order to accept the rule * @param lowerBoundMinSuppAsInstances the lower bound on the support * in order to accept the rule * @param totalTransactions the total number of transactions in the data * @return a list of association rules */ public static List<AssociationRule> generateRulesBruteForce(FrequentItemSets largeItemSets, DefaultAssociationRule.METRIC_TYPE metricToUse, double metricThreshold, int upperBoundMinSuppAsInstances, int lowerBoundMinSuppAsInstances, int totalTransactions) { List<AssociationRule> rules = new ArrayList<AssociationRule>(); largeItemSets.sort(); Map<Collection<BinaryItem>, Integer> frequencyLookup = new HashMap<Collection<BinaryItem>, Integer>(); Iterator<FrequentBinaryItemSet> setI = largeItemSets.iterator(); // process each large item set while (setI.hasNext()) { FrequentBinaryItemSet fis = setI.next(); frequencyLookup.put(fis.getItems(), fis.getSupport()); if (fis.getItems().size() > 1) { // generate all the possible subsets for the premise boolean[] subset = new boolean[fis.getItems().size()]; Collection<Item> premise = null; Collection<Item> consequence = null; while ((premise = getPremise(fis, subset)) != null) { if (premise.size() > 0 && premise.size() < fis.getItems().size()) { consequence = getConsequence(fis, subset); int totalSupport = fis.getSupport(); int supportPremise = frequencyLookup.get(premise).intValue(); int supportConsequence = frequencyLookup.get(consequence).intValue(); // a candidate rule DefaultAssociationRule candidate = new DefaultAssociationRule(premise, consequence, metricToUse, supportPremise, supportConsequence, totalSupport, totalTransactions); if (candidate.getPrimaryMetricValue() > metricThreshold && candidate.getTotalSupport() >= lowerBoundMinSuppAsInstances && candidate.getTotalSupport() <= upperBoundMinSuppAsInstances) { // accept this rule rules.add(candidate); } } nextSubset(subset); } } } return rules; } public static List<AssociationRule> pruneRules(List<AssociationRule> rulesToPrune, ArrayList<Item> itemsToConsider, boolean useOr) { ArrayList<AssociationRule> result = new ArrayList<AssociationRule>(); for (AssociationRule r : rulesToPrune) { if (r.containsItems(itemsToConsider, useOr)) { result.add(r); } } return result; } /** The number of rules to find */ protected int m_numRulesToFind = 10; //protected double m_upperBoundMinSupport = 0.36; /** The upper bound on the minimum support */ protected double m_upperBoundMinSupport = 1.0; /** The lower bound on minimum support */ protected double m_lowerBoundMinSupport = 0.1; /** The amount by which to decrease the support in each iteration */ protected double m_delta = 0.05; /** The number of instances in the data */ protected int m_numInstances; /** * When processing data off of disk report progress * this frequently (number of instances). */ protected int m_offDiskReportingFrequency = 10000; /** * If true, just all rules meeting the lower bound on the minimum * support will be found. The number of rules to find will be * ignored and the iterative reduction of support will not * be done. */ protected boolean m_findAllRulesForSupportLevel = false; //protected double m_lowerBoundMinSupport = 0.0; /** The index (1 based) of binary attributes to treat as the positive value */ protected int m_positiveIndex = 2; protected DefaultAssociationRule.METRIC_TYPE m_metric = DefaultAssociationRule.METRIC_TYPE.CONFIDENCE; protected double m_metricThreshold = 0.9; /** Holds the large item sets found */ protected FrequentItemSets m_largeItemSets; /** Holds the rules */ protected List<AssociationRule> m_rules; // maximum number of items in a large item set (zero means no limit) protected int m_maxItems = -1; /** * If set, limit the transactions (instances) input to the * algorithm to those that contain these items */ protected String m_transactionsMustContain = ""; /** Use OR rather than AND when considering must contain lists */ protected boolean m_mustContainOR = false; /** If set, then only output rules containing these itmes */ protected String m_rulesMustContain = ""; /** * Returns default capabilities of the classifier. * * @return the capabilities of this classifier */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); // enable what we can handle // attributes result.enable(Capability.UNARY_ATTRIBUTES); result.enable(Capability.BINARY_ATTRIBUTES); result.enable(Capability.MISSING_VALUES); result.enable(Capability.NO_CLASS); return result; } /** * Returns a string describing this associator * * @return a description of the evaluator suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "Class implementing the FP-growth algorithm for finding" + " large item sets without candidate generation. Iteratively" + " reduces the minimum support until it finds the required" + " number of rules with the given minimum metric." + " For more information see:\n\n" + getTechnicalInformation().toString(); } /** * Returns an instance of a TechnicalInformation object, containing * detailed information about the technical background of this class, * e.g., paper reference or book this class is based on. * * @return the technical information about this class */ public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; result = new TechnicalInformation(Type.INPROCEEDINGS); result.setValue(Field.AUTHOR, "J. Han and J.Pei and Y. Yin"); result.setValue(Field.TITLE, "Mining frequent patterns without candidate generation"); result.setValue(Field.BOOKTITLE, "Proceedings of the 2000 ACM-SIGMID International" + " Conference on Management of Data"); result.setValue(Field.YEAR, "2000"); result.setValue(Field.PAGES, "1-12"); return result; } private boolean passesMustContain(Instance inst, boolean[] transactionsMustContainIndexes, int numInTransactionsMustContainList) { boolean result = false; if (inst instanceof SparseInstance) { int containsCount = 0; for (int i = 0; i < inst.numValues(); i++) { int attIndex = inst.index(i); if (m_mustContainOR) { if (transactionsMustContainIndexes[attIndex]) { // break here since the operator is OR and this // instance contains at least one of the items return true; } } else { if (transactionsMustContainIndexes[attIndex]) { containsCount++; } } } if (!m_mustContainOR) { if (containsCount == numInTransactionsMustContainList) { return true; } } } else { int containsCount = 0; for (int i = 0; i < transactionsMustContainIndexes.length; i++) { if (transactionsMustContainIndexes[i]) { if ((int)inst.value(i) == m_positiveIndex - 1) { if (m_mustContainOR) { // break here since the operator is OR and // this instance contains at least one of the // requested items return true; } else { containsCount++; } } } } if (!m_mustContainOR) { if (containsCount == numInTransactionsMustContainList) { return true; } } } return result; } private void processSingleton(Instance current, ArrayList<BinaryItem> singletons) throws Exception { if (current instanceof SparseInstance) { for (int j = 0; j < current.numValues(); j++) { int attIndex = current.index(j); singletons.get(attIndex).increaseFrequency(); } } else { for (int j = 0; j < current.numAttributes(); j++) { if (!current.isMissing(j)) { if (current.attribute(j).numValues() == 1 || current.value(j) == m_positiveIndex - 1) { singletons.get(j).increaseFrequency(); } } } } } /** * Get the singleton items in the data * * @param source the source of the data (either Instances or * an ArffLoader). * @return a list of singleton item sets * @throws Exception if the singletons can't be found for some reason */ protected ArrayList<BinaryItem> getSingletons(Object source) throws Exception { ArrayList<BinaryItem> singletons = new ArrayList<BinaryItem>(); Instances data = null; if (source instanceof Instances) { data = (Instances)source; } else if (source instanceof weka.core.converters.ArffLoader) { data = ((weka.core.converters.ArffLoader)source).getStructure(); } for (int i = 0; i < data.numAttributes(); i++) { singletons.add(new BinaryItem(data.attribute(i), m_positiveIndex - 1)); } if (source instanceof Instances) { // set the number of instances m_numInstances = data.numInstances(); for (int i = 0; i < data.numInstances(); i++) { Instance current = data.instance(i); processSingleton(current, singletons); } } else if (source instanceof weka.core.converters.ArffLoader) { weka.core.converters.ArffLoader loader = (weka.core.converters.ArffLoader)source; Instance current = null; int count = 0; while ((current = loader.getNextInstance(data)) != null) { processSingleton(current, singletons); count++; if (count % m_offDiskReportingFrequency == 0) { System.err.println("Singletons: done " + count); } } // set the number of instances m_numInstances = count; loader.reset(); } return singletons; } /** * Get the singleton items in the data * * @param data the Instances to process * @return a list of singleton item sets * @throws Exception if the singletons can't be found for some reason */ protected ArrayList<BinaryItem> getSingletons(Instances data) throws Exception { return getSingletons((Object)data); /*ArrayList<BinaryItem> singletons = new ArrayList<BinaryItem>(); for (int i = 0; i < data.numAttributes(); i++) { singletons.add(new BinaryItem(data.attribute(i), m_positiveIndex - 1)); } for (int i = 0; i < data.numInstances(); i++) { Instance current = data.instance(i); if (current instanceof SparseInstance) { for (int j = 0; j < current.numValues(); j++) { int attIndex = current.index(j); singletons.get(attIndex).increaseFrequency(); } } else { for (int j = 0; j < data.numAttributes(); j++) { if (!current.isMissing(j)) { if (current.attribute(j).numValues() == 1 || current.value(j) == m_positiveIndex - 1) { singletons.get(j).increaseFrequency(); } } } } } return singletons;*/ } /*protected ArrayList<BinaryItem> getFrequent(ArrayList<BinaryItem> items, int minSupport) { ArrayList<BinaryItem> frequent = new ArrayList<BinaryItem>(); for (BinaryItem b : items) { if (b.getFrequency() > minSupport) { frequent.add(b); } } // sort in descending order of support Collections.sort(frequent); return frequent; } */ /** * Inserts a single instance into the FPTree. * * @param current the instance to insert * @param singletons the singleton item sets * @param tree the tree to insert into * @param minSupport the minimum support threshold */ private void insertInstance(Instance current, ArrayList<BinaryItem> singletons, FPTreeRoot tree, int minSupport) { ArrayList<BinaryItem> transaction = new ArrayList<BinaryItem>(); if (current instanceof SparseInstance) { for (int j = 0; j < current.numValues(); j++) { int attIndex = current.index(j); if (singletons.get(attIndex).getFrequency() >= minSupport) { transaction.add(singletons.get(attIndex)); } } Collections.sort(transaction); tree.addItemSet(transaction, 1); } else { for (int j = 0; j < current.numAttributes(); j++) { if (!current.isMissing(j)) { if (current.attribute(j).numValues() == 1 || current.value(j) == m_positiveIndex - 1) { if (singletons.get(j).getFrequency() >= minSupport) { transaction.add(singletons.get(j)); } } } } Collections.sort(transaction); tree.addItemSet(transaction, 1); } } /** * Construct the frequent pattern tree by inserting each transaction * in the data into the tree. Only those items from each transaction that * meet the minimum support threshold are inserted. * * @param singletons the singleton item sets * @param data the Instances containing the transactions * @param minSupport the minimum support * @return the root of the tree */ protected FPTreeRoot buildFPTree(ArrayList<BinaryItem> singletons, Object dataSource, int minSupport) throws Exception { FPTreeRoot tree = new FPTreeRoot(); Instances data = null; if (dataSource instanceof Instances) { data = (Instances)dataSource; } else if (dataSource instanceof weka.core.converters.ArffLoader) { data = ((weka.core.converters.ArffLoader)dataSource).getStructure(); } if (dataSource instanceof Instances) { for (int i = 0; i < data.numInstances(); i++) { insertInstance(data.instance(i), singletons, tree, minSupport); } } else if (dataSource instanceof weka.core.converters.ArffLoader) { weka.core.converters.ArffLoader loader = (weka.core.converters.ArffLoader)dataSource; Instance current = null; int count = 0; while ((current = loader.getNextInstance(data)) != null) { insertInstance(current, singletons, tree, minSupport); count++; if (count % m_offDiskReportingFrequency == 0) { System.err.println("build tree done: " + count); } } } return tree; } /** * Construct the frequent pattern tree by inserting each transaction * in the data into the tree. Only those items from each transaction that * meet the minimum support threshold are inserted. * * @param singletons the singleton item sets * @param data the Instances containing the transactions * @param minSupport the minimum support * @return the root of the tree */ /*protected FPTreeRoot buildFPTree(ArrayList<BinaryItem> singletons, Instances data, int minSupport) { FPTreeRoot tree = new FPTreeRoot(); for (int i = 0; i < data.numInstances(); i++) { Instance current = data.instance(i); ArrayList<BinaryItem> transaction = new ArrayList<BinaryItem>(); if (current instanceof SparseInstance) { for (int j = 0; j < current.numValues(); j++) { int attIndex = current.index(j); if (singletons.get(attIndex).getFrequency() >= minSupport) { transaction.add(singletons.get(attIndex)); } } Collections.sort(transaction); tree.addItemSet(transaction, 1); } else { for (int j = 0; j < data.numAttributes(); j++) { if (!current.isMissing(j)) { if (current.attribute(j).numValues() == 1 || current.value(j) == m_positiveIndex - 1) { if (singletons.get(j).getFrequency() >= minSupport) { transaction.add(singletons.get(j)); } } } } Collections.sort(transaction); tree.addItemSet(transaction, 1); } } return tree; }*/ /** * Find large item sets in the FP-tree. * * @param tree the root of the tree to mine * @param largeItemSets holds the large item sets found * @param recursionLevel the recursion level for the current projected * counts * @param conditionalItems the current set of items that the current * (projected) tree is conditional on * @param minSupport the minimum acceptable support */ protected void mineTree(FPTreeRoot tree, FrequentItemSets largeItemSets, int recursionLevel, FrequentBinaryItemSet conditionalItems, int minSupport) { if (!tree.isEmpty(recursionLevel)) { if (m_maxItems > 0 && recursionLevel >= m_maxItems) { // don't mine any further return; } Map<BinaryItem, FPTreeRoot.Header> headerTable = tree.getHeaderTable(); Set<BinaryItem> keys = headerTable.keySet(); // System.err.println("Number of freq item sets collected " + largeItemSets.size()); Iterator<BinaryItem> i = keys.iterator(); while (i.hasNext()) { BinaryItem item = i.next(); FPTreeRoot.Header itemHeader = headerTable.get(item); // check for minimum support at this level int support = itemHeader.getProjectedCounts().getCount(recursionLevel); if (support >= minSupport) { // process header list at this recursion level for (FPTreeNode n : itemHeader.getHeaderList()) { // push count up path to root int currentCount = n.getProjectedCount(recursionLevel); if (currentCount > 0) { FPTreeNode temp = n.getParent(); while (temp != tree) { // set/increase for the node temp.increaseProjectedCount(recursionLevel + 1, currentCount); // set/increase for the header table headerTable.get(temp.getItem()). getProjectedCounts().increaseCount(recursionLevel + 1, currentCount); temp = temp.getParent(); } } } FrequentBinaryItemSet newConditional = (FrequentBinaryItemSet) conditionalItems.clone(); // this item gets added to the conditional items newConditional.addItem(item); newConditional.setSupport(support); // now add this conditional item set to the list of large item sets largeItemSets.addItemSet(newConditional); // now recursively process the new tree mineTree(tree, largeItemSets, recursionLevel + 1, newConditional, minSupport); // reverse the propagated counts for (FPTreeNode n : itemHeader.getHeaderList()) { FPTreeNode temp = n.getParent(); while (temp != tree) { temp.removeProjectedCount(recursionLevel + 1); temp = temp.getParent(); } } // reverse the propagated counts in the header list // at this recursion level for (FPTreeRoot.Header h : headerTable.values()) { h.getProjectedCounts().removeCount(recursionLevel + 1); } } } } } /** * Construct a new FPGrowth object. */ public FPGrowth() { resetOptions(); } /** * Reset all options to their default values. */ public void resetOptions() { m_delta = 0.05; m_metricThreshold = 0.9; m_numRulesToFind = 10; m_lowerBoundMinSupport = 0.1; m_upperBoundMinSupport = 1.0; // m_minSupport = -1; m_positiveIndex = 2; m_transactionsMustContain = ""; m_rulesMustContain = ""; m_mustContainOR = false; } /** * Tip text for this property suitable for displaying * in the GUI. * * @return the tip text for this property. */ public String positiveIndexTipText() { return "Set the index of binary valued attributes that is to be considered" + " the positive index. Has no effect for sparse data (in this case" + " the first index (i.e. non-zero values) is always treated as " + " positive. Also has no effect for unary valued attributes (i.e." + " when using the Weka Apriori-style format for market basket data," + " which uses missing value \"?\" to indicate" + " absence of an item."; } /** * Set the index of the attribute value to consider as positive * for binary attributes in normal dense instances. Index 1 is always * used for sparse instances. * * @param index the index to use for positive values in binary attributes. */ public void setPositiveIndex(int index) { m_positiveIndex = index; } /** * Get the index of the attribute value to consider as positive * for binary attributes in normal dense instances. Index 1 is always * used for sparse instances. * * @return the index to use for positive values in binary attributes. */ public int getPositiveIndex() { return m_positiveIndex; } /** * Set the desired number of rules to find. * * @param numR the number of rules to find. */ public void setNumRulesToFind(int numR) { m_numRulesToFind = numR; } /** * Get the number of rules to find. * * @return the number of rules to find. */ public int getNumRulesToFind() { return m_numRulesToFind; } /** * Tip text for this property suitable for displaying * in the GUI. * * @return the tip text for this property. */ public String numRulesToFindTipText() { return "The number of rules to output"; } /** * Set the metric type to use. * * @param d the metric type */ public void setMetricType(SelectedTag d) { int ordinal = d.getSelectedTag().getID(); for (DefaultAssociationRule.METRIC_TYPE m : DefaultAssociationRule.METRIC_TYPE.values()) { if (m.ordinal() == ordinal) { m_metric = m; break; } } } /** * Set the maximum number of items to include in large items sets. * * @param max the maxim number of items to include in large item sets. */ public void setMaxNumberOfItems(int max) { m_maxItems = max; } /** * Gets the maximum number of items to be included in large item sets. * * @return the maximum number of items to be included in large items sets. */ public int getMaxNumberOfItems() { return m_maxItems; } /** * Tip text for this property suitable for displaying * in the GUI. * * @return the tip text for this property. */ public String maxNumberOfItemsTipText() { return "The maximum number of items to include in frequent item sets. -1 " + "means no limit."; } /** * Get the metric type to use. * * @return the metric type to use. */ public SelectedTag getMetricType() { return new SelectedTag(m_metric.ordinal(), DefaultAssociationRule.TAGS_SELECTION); } /** * Tip text for this property suitable for displaying * in the GUI. * * @return the tip text for this property. */ public String metricTypeTipText() { return "Set the type of metric by which to rank rules. Confidence is " +"the proportion of the examples covered by the premise that are also " +"covered by the consequence(Class association rules can only be mined using confidence). Lift is confidence divided by the " +"proportion of all examples that are covered by the consequence. This " +"is a measure of the importance of the association that is independent " +"of support. Leverage is the proportion of additional examples covered " +"by both the premise and consequence above those expected if the " +"premise and consequence were independent of each other. The total " +"number of examples that this represents is presented in brackets " +"following the leverage. Conviction is " +"another measure of departure from independence."; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String minMetricTipText() { return "Minimum metric score. Consider only rules with scores higher than " +"this value."; } /** * Get the value of minConfidence. * * @return Value of minConfidence. */ public double getMinMetric() { return m_metricThreshold; } /** * Set the value of minConfidence. * * @param v Value to assign to minConfidence. */ public void setMinMetric(double v) { m_metricThreshold = v; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String transactionsMustContainTipText() { return "Limit input to FPGrowth to those transactions (instances)" + " that contain these items. Provide a comma separated" + " list of attribute names."; } /** * Set the comma separated list of items that transactions * must contain in order to be considered for large * item sets and rules. * * @param list a comma separated list of items (empty * string indicates no restriction on the transactions). */ public void setTransactionsMustContain(String list) { m_transactionsMustContain = list; } /** * Gets the comma separated list of items that * transactions must contain in order to be considered * for large item sets and rules. * * @return return the comma separated list of * items that transactions must contain. */ public String getTransactionsMustContain() { return m_transactionsMustContain; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String rulesMustContainTipText() { return "Only print rules that contain these items. Provide " + "a comma separated list of attribute names."; } /** * Set the comma separated list of items that rules * must contain in order to be output. * * @param list a comma separated list of items (empty * string indicates no restriction on the rules). */ public void setRulesMustContain(String list) { m_rulesMustContain = list; } /** * Get the comma separated list of items that * rules must contain in order to be output. * * @return the comma separated list of items * that rules must contain in order to be output. */ public String getRulesMustContain() { return m_rulesMustContain; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String useORForMustContainListTipText() { return "Use OR instead of AND for transactions/rules must contain lists."; } /** * Set whether to use OR rather than AND when considering * must contain lists. * * @param b true if OR should be used instead of AND when * considering transaction and rules must contain lists. */ public void setUseORForMustContainList(boolean b) { m_mustContainOR = b; } /** * Gets whether OR is to be used rather than AND when * considering must contain lists. * * @return true if OR is used instead of AND. */ public boolean getUseORForMustContainList() { return m_mustContainOR; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying, in the explorer/experimenter gui */ public String deltaTipText() { return "Iteratively decrease support by this factor. Reduces support " +"until min support is reached or required number of rules has been " +"generated."; } /** * Get the value of delta. * * @return Value of delta. */ public double getDelta() { return m_delta; } /** * Set the value of delta. * * @param v Value to assign to delta. */ public void setDelta(double v) { m_delta = v; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String lowerBoundMinSupportTipText() { return "Lower bound for minimum support as a fraction or number of instances."; } /** * Get the value of lowerBoundMinSupport. * * @return Value of lowerBoundMinSupport. */ public double getLowerBoundMinSupport() { return m_lowerBoundMinSupport; } /** * Set the value of lowerBoundMinSupport. * * @param v Value to assign to lowerBoundMinSupport. */ public void setLowerBoundMinSupport(double v) { m_lowerBoundMinSupport = v; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String upperBoundMinSupportTipText() { return "Upper bound for minimum support as a fraction or number of instances. " + "Start iteratively decreasing " + "minimum support from this value."; } /** * Get the value of upperBoundMinSupport. * * @return Value of upperBoundMinSupport. */ public double getUpperBoundMinSupport() { return m_upperBoundMinSupport; } /** * Set the value of upperBoundMinSupport. * * @param v Value to assign to upperBoundMinSupport. */ public void setUpperBoundMinSupport(double v) { m_upperBoundMinSupport = v; } /** * Tip text for this property suitable for displaying * in the GUI. * * @return the tip text for this property. */ public String findAllRulesForSupportLevelTipText() { return "Find all rules that meet " + "the lower bound on minimum support and the minimum metric constraint. " + "Turning this mode on will disable the iterative support reduction " + "procedure to find the specified number of rules."; } /** * If true then turn off the iterative support reduction method * of finding x rules that meet the minimum support and metric * thresholds and just return all the rules that meet the * lower bound on minimum support and the minimum metric. * * @param s true if all rules meeting the lower bound on the support * and minimum metric thresholds are to be found. */ public void setFindAllRulesForSupportLevel(boolean s) { m_findAllRulesForSupportLevel = s; } /** * Get whether all rules meeting the lower bound on min support * and the minimum metric threshold are to be found. * * @return true if all rules meeting the lower bound on min * support and the min metric threshold are to be found. */ public boolean getFindAllRulesForSupportLevel() { return m_findAllRulesForSupportLevel; } /** * Set how often to report some progress when the data is * being read incrementally off of the disk rather than * loaded into memory. * * @param freq the frequency to print progress. */ public void setOffDiskReportingFrequency(int freq) { m_offDiskReportingFrequency = freq; } /* public void setMinimumSupport(double minSupp) { m_minSupport = minSupp; } public double getMinimumSupport() { return m_minSupport; } */ /** * Gets the list of mined association rules. * * @return the list of association rules discovered during mining. * Returns null if mining hasn't been performed yet. */ public AssociationRules getAssociationRules() { List<AssociationRule> rulesToReturn = new ArrayList<AssociationRule>(); int count = 0; for (AssociationRule r : m_rules) { rulesToReturn.add(r); count++; if (!m_findAllRulesForSupportLevel && count == m_numRulesToFind) { break; } } return new AssociationRules(rulesToReturn, this); } /** * Gets a list of the names of the metrics output for * each rule. This list should be the same (in terms of * the names and order thereof) as that produced by * AssociationRule.getMetricNamesForRule(). * * @return an array of the names of the metrics available * for each rule learned by this producer. */ public String[] getRuleMetricNames() { String[] metricNames = new String[DefaultAssociationRule.TAGS_SELECTION.length]; for (int i = 0; i < DefaultAssociationRule.TAGS_SELECTION.length; i++) { metricNames[i] = DefaultAssociationRule.TAGS_SELECTION[i].getReadable(); } return metricNames; } /** * Returns true if this AssociationRulesProducer can actually * produce rules. Most implementing classes will always return * true from this method (obviously :-)). However, an implementing * class that actually acts as a wrapper around things that may * or may not implement AssociationRulesProducer will want to * return false if the thing they wrap can't produce rules. * * @return true if this producer can produce rules in its current * configuration */ public boolean canProduceRules() { return true; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration<Option> listOptions() { Vector<Option> newVector = new Vector<Option>(); String string00 = "\tSet the index of the attribute value to consider as 'positive'\n\t" + "for binary attributes in normal dense instances. Index 2 is always\n\t" + "used for sparse instances. (default = 2)"; String string0 = "\tThe maximum number of items to include " + "in large items sets (and rules). (default " + "= -1, i.e. no limit.)"; String string1 = "\tThe required number of rules. (default = " + m_numRulesToFind + ")"; String string2 = "\tThe minimum metric score of a rule. (default" + " = " + m_metricThreshold + ")"; String string3 = "\tThe metric by which to rank rules. (default" + " = confidence)"; String string4 = "\tThe lower bound for the minimum support as a fraction" + " or number of instances. (default = " + m_lowerBoundMinSupport + ")"; String string5 = "\tUpper bound for minimum support as a fraction or number of instances. " + "(default = 1.0)"; String string6 = "\tThe delta by which the minimum support is decreased in\n" + "\teach iteration as a fraction or number of instances. (default = " + m_delta + ")"; String string7 = "\tFind all rules that meet the lower bound on\n\t" + "minimum support and the minimum metric constraint.\n\t" + "Turning this mode on will disable the iterative support reduction\n\t" + "procedure to find the specified number of rules."; String string8 = "\tOnly consider transactions that contain these items (default = no restriction)"; String string9 = "\tOnly print rules that contain these items. (default = no restriction)"; String string10 = "\tUse OR instead of AND for must contain list(s). Use in conjunction" + "\n\twith -transactions and/or -rules"; newVector.add(new Option(string00, "P", 1, "-P <attribute index of positive value>")); newVector.add(new Option(string0, "I", 1, "-I <max items>")); newVector.add(new Option(string1, "N", 1, "-N <require number of rules>")); newVector.add(new Option(string3, "T", 1, "-T <0=confidence | 1=lift | " + "2=leverage | 3=Conviction>")); newVector.add(new Option(string2, "C", 1, "-C <minimum metric score of a rule>")); newVector.add(new Option(string5, "U", 1, "-U <upper bound for minimum support>")); newVector.add(new Option(string4, "M", 1, "-M <lower bound for minimum support>")); newVector.add(new Option(string6, "D", 1, "-D <delta for minimum support>")); newVector.add(new Option(string7, "S", 0, "-S")); newVector.add(new Option(string8, "transactions", 1, "-transactions <comma separated " + "list of attribute names>")); newVector.add(new Option(string9, "rules", 1, "-rules <comma separated list " + "of attribute names>")); newVector.add(new Option(string10, "use-or", 0, "-use-or")); return newVector.elements(); } /** * * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -P &lt;attribute index of positive value&gt; * Set the index of the attribute value to consider as 'positive' * for binary attributes in normal dense instances. Index 2 is always * used for sparse instances. (default = 2)</pre> * * <pre> -I &lt;max items&gt; * The maximum number of items to include in large items sets (and rules). (default = -1, i.e. no limit.)</pre> * * <pre> -N &lt;require number of rules&gt; * The required number of rules. (default = 10)</pre> * * <pre> -T &lt;0=confidence | 1=lift | 2=leverage | 3=Conviction&gt; * The metric by which to rank rules. (default = confidence)</pre> * * <pre> -C &lt;minimum metric score of a rule&gt; * The minimum metric score of a rule. (default = 0.9)</pre> * * <pre> -U &lt;upper bound for minimum support&gt; * Upper bound for minimum support. (default = 1.0)</pre> * * <pre> -M &lt;lower bound for minimum support&gt; * The lower bound for the minimum support. (default = 0.1)</pre> * * <pre> -D &lt;delta for minimum support&gt; * The delta by which the minimum support is decreased in * each iteration. (default = 0.05)</pre> * * <pre> -S * Find all rules that meet the lower bound on * minimum support and the minimum metric constraint. * Turning this mode on will disable the iterative support reduction * procedure to find the specified number of rules.</pre> * * <pre> -transactions &lt;comma separated list of attribute names&gt; * Only consider transactions that contain these items (default = no restriction)</pre> * * <pre> -rules &lt;comma separated list of attribute names&gt; * Only print rules that contain these items. (default = no restriction)</pre> * * <pre> -use-or * Use OR instead of AND for must contain list(s). Use in conjunction * with -transactions and/or -rules</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { resetOptions(); String positiveIndexString = Utils.getOption('P', options); String maxItemsString = Utils.getOption('I', options); String numRulesString = Utils.getOption('N', options); String minMetricString = Utils.getOption('C', options); String metricTypeString = Utils.getOption("T", options); String lowerBoundSupportString = Utils.getOption("M", options); String upperBoundSupportString = Utils.getOption("U", options); String deltaString = Utils.getOption("D", options); String transactionsString = Utils.getOption("transactions", options); String rulesString = Utils.getOption("rules", options); if (positiveIndexString.length() != 0) { setPositiveIndex(Integer.parseInt(positiveIndexString)); } if (maxItemsString.length() != 0) { setMaxNumberOfItems(Integer.parseInt(maxItemsString)); } if (metricTypeString.length() != 0) { setMetricType(new SelectedTag(Integer.parseInt(metricTypeString), DefaultAssociationRule.TAGS_SELECTION)); } if (numRulesString.length() != 0) { setNumRulesToFind(Integer.parseInt(numRulesString)); } if (minMetricString.length() != 0) { setMinMetric(Double.parseDouble(minMetricString)); } if (deltaString.length() != 0) { setDelta(Double.parseDouble(deltaString)); } if (lowerBoundSupportString.length() != 0) { setLowerBoundMinSupport(Double.parseDouble(lowerBoundSupportString)); } if (upperBoundSupportString.length() != 0) { setUpperBoundMinSupport(Double.parseDouble(upperBoundSupportString)); } if (transactionsString.length() != 0) { setTransactionsMustContain(transactionsString); } if (rulesString.length() > 0) { setRulesMustContain(rulesString); } setUseORForMustContainList(Utils.getFlag("use-or", options)); setFindAllRulesForSupportLevel(Utils.getFlag('S', options)); } /** * Gets the current settings of the classifier. * * @return an array of strings suitable for passing to setOptions */ public String[] getOptions() { ArrayList<String> options = new ArrayList<String>(); options.add("-P"); options.add("" + getPositiveIndex()); options.add("-I"); options.add("" + getMaxNumberOfItems()); options.add("-N"); options.add("" + getNumRulesToFind()); options.add("-T"); options.add("" + getMetricType().getSelectedTag().getID()); options.add("-C"); options.add("" + getMinMetric()); options.add("-D"); options.add("" + getDelta()); options.add("-U"); options.add("" + getUpperBoundMinSupport()); options.add("-M"); options.add("" + getLowerBoundMinSupport()); if (getFindAllRulesForSupportLevel()) { options.add("-S"); } if (getTransactionsMustContain().length() > 0) { options.add("-transactions"); options.add(getTransactionsMustContain()); } if (getRulesMustContain().length() > 0) { options.add("-rules"); options.add(getRulesMustContain()); } if (getUseORForMustContainList()) { options.add("-use-or"); } return options.toArray(new String[1]); } private Instances parseTransactionsMustContain(Instances data) { String[] split = m_transactionsMustContain.trim().split(","); boolean[] transactionsMustContainIndexes = new boolean[data.numAttributes()]; int numInTransactionsMustContainList = split.length; for (int i = 0; i < split.length; i++) { String attName = split[i].trim(); Attribute att = data.attribute(attName); if (att == null) { System.err.println("[FPGrowth] : WARNING - can't find attribute " + attName + " in the data."); numInTransactionsMustContainList--; } else { transactionsMustContainIndexes[att.index()] = true; } } if (numInTransactionsMustContainList == 0) { return data; } else { Instances newInsts = new Instances(data, 0); for (int i = 0; i < data.numInstances(); i++) { if (passesMustContain(data.instance(i), transactionsMustContainIndexes, numInTransactionsMustContainList)) { newInsts.add(data.instance(i)); } } newInsts.compactify(); return newInsts; } } private ArrayList<Item> parseRulesMustContain(Instances data) { ArrayList<Item> result = new ArrayList<Item>(); String[] split = m_rulesMustContain.trim().split(","); for (int i = 0; i < split.length; i++) { String attName = split[i].trim(); Attribute att = data.attribute(attName); if (att == null) { System.err.println("[FPGrowth] : WARNING - can't find attribute " + attName + " in the data."); } else { BinaryItem tempI = null; try { tempI = new BinaryItem(att, m_positiveIndex - 1); } catch (Exception e) { // this should never happen e.printStackTrace(); } result.add(tempI); } } return result; } /** * Method that generates all large item sets with a minimum support, and from * these all association rules with a minimum metric (i.e. confidence, * lift etc.). * * @param source the source of the data. May be an Instances object or * an ArffLoader. In the case of the latter, the two passes over the * data that FPGrowth requires will be done off of disk (i.e. only one * instance will be in memory at any one time). * @throws Exception if rules can't be built successfully */ private void buildAssociations(Object source) throws Exception { Instances data = null; Capabilities capabilities = getCapabilities(); boolean arffLoader = false; if (source instanceof weka.core.converters.ArffLoader) { data = ((weka.core.converters.ArffLoader)source).getStructure(); capabilities.setMinimumNumberInstances(0); arffLoader = true; } else { data = (Instances)source; } // can we handle the data? capabilities.testWithFail(data); // prune any instances that don't contain the requested items (if any) // can only do this if we are not reading the data incrementally if (m_transactionsMustContain.length() > 0 && (source instanceof Instances)) { data = parseTransactionsMustContain(data); getCapabilities().testWithFail(data); } ArrayList<Item> rulesMustContain = null; if (m_rulesMustContain.length() > 0) { rulesMustContain = parseRulesMustContain(data); } ArrayList<BinaryItem> singletons = getSingletons(source); int upperBoundMinSuppAsInstances = (m_upperBoundMinSupport > 1) ? (int) m_upperBoundMinSupport : (int)Math.ceil(m_upperBoundMinSupport * m_numInstances); int lowerBoundMinSuppAsInstances = (m_lowerBoundMinSupport > 1) ? (int)m_lowerBoundMinSupport : (int)Math.ceil(m_lowerBoundMinSupport * m_numInstances); double upperBoundMinSuppAsFraction = (m_upperBoundMinSupport > 1) ? m_upperBoundMinSupport / m_numInstances : m_upperBoundMinSupport; double lowerBoundMinSuppAsFraction = (m_lowerBoundMinSupport > 1) ? m_lowerBoundMinSupport / m_numInstances : m_lowerBoundMinSupport; double deltaAsFraction = (m_delta > 1) ? m_delta / m_numInstances : m_delta; //double currentSupport = upperBoundMinSuppAsFraction; double currentSupport = 1.0; if (m_findAllRulesForSupportLevel) { currentSupport = lowerBoundMinSuppAsFraction; } do { if (arffLoader) { ((weka.core.converters.ArffLoader)source).reset(); } int currentSupportAsInstances = (currentSupport > 1) ? (int)currentSupport : (int)Math.ceil(currentSupport * m_numInstances); // build the FPTree if (arffLoader) { System.err.println("Building FP-tree..."); } FPTreeRoot tree = buildFPTree(singletons, source, currentSupportAsInstances); FrequentItemSets largeItemSets = new FrequentItemSets(m_numInstances); if (arffLoader) { System.err.println("Mining tree for min supp " + currentSupport); } // mine the tree FrequentBinaryItemSet conditionalItems = new FrequentBinaryItemSet(new ArrayList<BinaryItem>(), 0); mineTree(tree, largeItemSets, 0, conditionalItems, currentSupportAsInstances); m_largeItemSets = largeItemSets; if (arffLoader) { System.err.println("Number of large item sets: " + m_largeItemSets.size()); } // save memory tree = null; m_rules = generateRulesBruteForce(m_largeItemSets, m_metric, m_metricThreshold, upperBoundMinSuppAsInstances, lowerBoundMinSuppAsInstances, m_numInstances); if (arffLoader) { System.err.println("Number of rules found " + m_rules.size()); } if (rulesMustContain != null && rulesMustContain.size() > 0) { m_rules = pruneRules(m_rules, rulesMustContain, m_mustContainOR); } if (!m_findAllRulesForSupportLevel) { currentSupport -= deltaAsFraction; if (currentSupport < lowerBoundMinSuppAsFraction) { if (currentSupport + deltaAsFraction > lowerBoundMinSuppAsFraction) { // ensure that the lower bound does get evaluated currentSupport = lowerBoundMinSuppAsFraction; } else { break; } } } else { // just break out of the loop as we are just finding all rules // with a minimum support + metric break; } } while (m_rules.size() < m_numRulesToFind); Collections.sort(m_rules); } /** * Method that generates all large item sets with a minimum support, and from * these all association rules with a minimum metric (i.e. confidence, * lift etc.). * * @param data the instances to be used for generating the associations * @throws Exception if rules can't be built successfully */ public void buildAssociations(Instances data) throws Exception { buildAssociations((Object)data); return; } /** * Output the association rules. * * @return a string representation of the model. */ public String toString() { // return m_largeItemSets.toString(m_numItemSetsToFind); if (m_rules == null) { return "FPGrowth hasn't been trained yet!"; } StringBuffer result = new StringBuffer(); int numRules = (m_rules.size() < m_numRulesToFind) ? m_rules.size() : m_numRulesToFind; if (m_rules.size() == 0) { return "No rules found!"; } else { result.append("FPGrowth found " + m_rules.size() + " rules"); if (!m_findAllRulesForSupportLevel) { result.append(" (displaying top " + numRules + ")"); } if (m_transactionsMustContain.length() > 0 || m_rulesMustContain.length() > 0) { result.append("\n"); if (m_transactionsMustContain.length() > 0) { result.append("\nUsing only transactions that contain: " + m_transactionsMustContain); } if (m_rulesMustContain.length() > 0) { result.append("\nShowing only rules that contain: " + m_rulesMustContain); } } result.append("\n\n"); } int count = 0; for (AssociationRule r : m_rules) { result.append(Utils.doubleToString((double)count+1, (int)(Math.log(numRules)/Math.log(10)+1), 0) + ". "); result.append(r + "\n"); count++; if (!m_findAllRulesForSupportLevel && count == m_numRulesToFind) { break; } } return result.toString(); } /** * Assemble a dot graph representation of the FP-tree. * * @param tree the root of the FP-tree * @return a graph representation as a String in dot format. */ public String graph(FPTreeRoot tree) { //int maxID = tree.assignIDs(-1); StringBuffer text = new StringBuffer(); text.append("digraph FPTree {\n"); text.append("N0 [label=\"ROOT\"]\n"); tree.graphFPTree(text); // tree.graphHeaderTable(text, maxID+1); text.append("}\n"); return text.toString(); } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 7060 $"); } /** * Main method. * * @param args the commandline options */ public static void main(String[] args) { try { String[] argsCopy = args.clone(); if (Utils.getFlag('h', argsCopy) || Utils.getFlag("help", argsCopy)) { runAssociator(new FPGrowth(), args); System.out.println("-disk\n\tProcess data off of disk instead of loading\n\t" + "into main memory. This is a command line only option."); return; } if (!Utils.getFlag("disk", args)) { runAssociator(new FPGrowth(), args); } else { String filename; filename = Utils.getOption('t', args); weka.core.converters.ArffLoader loader = null; if (filename.length() != 0) { loader = new weka.core.converters.ArffLoader(); loader.setFile(new java.io.File(filename)); } else { throw new Exception("No training file specified!"); } FPGrowth fpGrowth = new FPGrowth(); fpGrowth.setOptions(args); Utils.checkForRemainingOptions(args); fpGrowth.buildAssociations(loader); System.out.print(fpGrowth.toString()); } } catch (Exception ex) { ex.printStackTrace(); } } }
1
0.95293
1
0.95293
game-dev
MEDIA
0.307361
game-dev
0.559289
1
0.559289
HyperMC-Team/OpenRoxy
4,379
src/main/java/net/minecraft/inventory/SlotCrafting.java
package net.minecraft.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.stats.AchievementList; public class SlotCrafting extends Slot { private final InventoryCrafting craftMatrix; private final EntityPlayer thePlayer; private int amountCrafted; public SlotCrafting(EntityPlayer player, InventoryCrafting craftingInventory, IInventory p_i45790_3_, int slotIndex, int xPosition, int yPosition) { super(p_i45790_3_, slotIndex, xPosition, yPosition); this.thePlayer = player; this.craftMatrix = craftingInventory; } @Override public boolean isItemValid(ItemStack stack) { return false; } @Override public ItemStack decrStackSize(int amount) { if (this.getHasStack()) { this.amountCrafted += Math.min(amount, this.getStack().stackSize); } return super.decrStackSize(amount); } @Override protected void onCrafting(ItemStack stack, int amount) { this.amountCrafted += amount; this.onCrafting(stack); } @Override protected void onCrafting(ItemStack stack) { if (this.amountCrafted > 0) { stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.amountCrafted); } this.amountCrafted = 0; if (stack.getItem() == Item.getItemFromBlock(Blocks.crafting_table)) { this.thePlayer.triggerAchievement(AchievementList.buildWorkBench); } if (stack.getItem() instanceof ItemPickaxe) { this.thePlayer.triggerAchievement(AchievementList.buildPickaxe); } if (stack.getItem() == Item.getItemFromBlock(Blocks.furnace)) { this.thePlayer.triggerAchievement(AchievementList.buildFurnace); } if (stack.getItem() instanceof ItemHoe) { this.thePlayer.triggerAchievement(AchievementList.buildHoe); } if (stack.getItem() == Items.bread) { this.thePlayer.triggerAchievement(AchievementList.makeBread); } if (stack.getItem() == Items.cake) { this.thePlayer.triggerAchievement(AchievementList.bakeCake); } if (stack.getItem() instanceof ItemPickaxe && ((ItemPickaxe)stack.getItem()).getToolMaterial() != Item.ToolMaterial.WOOD) { this.thePlayer.triggerAchievement(AchievementList.buildBetterPickaxe); } if (stack.getItem() instanceof ItemSword) { this.thePlayer.triggerAchievement(AchievementList.buildSword); } if (stack.getItem() == Item.getItemFromBlock(Blocks.enchanting_table)) { this.thePlayer.triggerAchievement(AchievementList.enchantments); } if (stack.getItem() == Item.getItemFromBlock(Blocks.bookshelf)) { this.thePlayer.triggerAchievement(AchievementList.bookcase); } if (stack.getItem() == Items.golden_apple && stack.getMetadata() == 1) { this.thePlayer.triggerAchievement(AchievementList.overpowered); } } @Override public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) { this.onCrafting(stack); ItemStack[] aitemstack = CraftingManager.getInstance().func_180303_b(this.craftMatrix, playerIn.worldObj); for (int i = 0; i < aitemstack.length; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlot(i); ItemStack itemstack1 = aitemstack[i]; if (itemstack != null) { this.craftMatrix.decrStackSize(i, 1); } if (itemstack1 == null) continue; if (this.craftMatrix.getStackInSlot(i) == null) { this.craftMatrix.setInventorySlotContents(i, itemstack1); continue; } if (this.thePlayer.inventory.addItemStackToInventory(itemstack1)) continue; this.thePlayer.dropPlayerItemWithRandomChoice(itemstack1, false); } } }
1
0.938548
1
0.938548
game-dev
MEDIA
0.999531
game-dev
0.966467
1
0.966467
AionGermany/aion-germany
5,425
AL-Game-5.8/src/com/aionemu/gameserver/skillengine/effect/TransformEffect.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.skillengine.effect; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import com.aionemu.commons.database.dao.DAOManager; import com.aionemu.gameserver.dao.PlayerTransformationDAO; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.Summon; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAYER_INFO; import com.aionemu.gameserver.network.aion.serverpackets.SM_TRANSFORM; import com.aionemu.gameserver.skillengine.model.Effect; import com.aionemu.gameserver.skillengine.model.TransformType; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Sweetkr, kecimis */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TransformEffect") public abstract class TransformEffect extends EffectTemplate { @XmlAttribute protected int model; @XmlAttribute protected TransformType type = TransformType.NONE; @XmlAttribute protected int panelid; @XmlAttribute protected int itemId; @XmlAttribute protected AbnormalState state = AbnormalState.BUFF; @Override public void applyEffect(Effect effect) { effect.addToEffectedController(); if (state != null) { effect.getEffected().getEffectController().setAbnormal(state.getId()); effect.setAbnormal(state.getId()); } } @Override public void endEffect(Effect effect) { final Creature effected = effect.getEffected(); if (state != null) { effected.getEffectController().unsetAbnormal(state.getId()); } if (effected instanceof Player) { int newModel = 0; TransformType transformType = TransformType.PC; for (Effect tmp : effected.getEffectController().getAbnormalEffects()) { for (EffectTemplate template : tmp.getEffectTemplates()) { if (template instanceof TransformEffect) { if (((TransformEffect) template).getTransformId() == model) { continue; } newModel = ((TransformEffect) template).getTransformId(); transformType = ((TransformEffect) template).getTransformType(); break; } } } effected.getTransformModel().setModelId(newModel); effected.getTransformModel().setTransformType(transformType); effected.getTransformModel().setItemId(0); ((Player) effected).setTransformed(false); ((Player) effected).setTransformedModelId(0); ((Player) effected).setTransformedPanelId(0); ((Player) effected).setTransformedItemId(0); DAOManager.getDAO(PlayerTransformationDAO.class).deletePlTransfo(effected.getObjectId()); if (model == 202635) { // Makes the effected unAttackable for all PacketSendUtility.broadcastPacket(effected, new SM_PLAYER_INFO((Player) effected, false), 100); } } else if (effected instanceof Summon) { effected.getTransformModel().setModelId(0); } else if (effected instanceof Npc) { effected.getTransformModel().setModelId(effected.getObjectTemplate().getTemplateId()); } effected.getTransformModel().setPanelId(0); PacketSendUtility.broadcastPacketAndReceive(effected, new SM_TRANSFORM(effected, 0, false, 0)); super.endEffect(effect); } @Override public void startEffect(Effect effect) { // , AbnormalState effectId final Creature effected = effect.getEffected(); DAOManager.getDAO(PlayerTransformationDAO.class).deletePlTransfo(effected.getObjectId()); if (itemId == 0) { if (effected.getUsingItemId() != 0) { itemId = effected.getUsingItemId(); } } effected.getTransformModel().setModelId(model); effected.getTransformModel().setPanelId(panelid); effected.getTransformModel().setItemId(itemId); effected.getTransformModel().setTransformType(effect.getTransformType()); PacketSendUtility.broadcastPacketAndReceive(effected, new SM_TRANSFORM(effected, panelid, true, itemId, effect.getSkillId())); if (effected instanceof Player) { ((Player) effected).setTransformed(true); ((Player) effected).setTransformedModelId(model); ((Player) effected).setTransformedPanelId(panelid); ((Player) effected).setTransformedItemId(itemId); DAOManager.getDAO(PlayerTransformationDAO.class).storePlTransfo(effected.getObjectId(), panelid, itemId); PacketSendUtility.broadcastPacket(effected, new SM_PLAYER_INFO((Player) effected, true), 100); } super.startEffect(effect); } public TransformType getTransformType() { return type; } public int getTransformId() { return model; } public int getPanelId() { return panelid; } }
1
0.875209
1
0.875209
game-dev
MEDIA
0.953861
game-dev
0.977301
1
0.977301
3UR/Simpsons-Hit-Run
1,775
src/game/worldsim/redbrick/redbrickcollisionsolveragent.h
/*=========================================================================== redbrickcollisionsolveragent.h created Jan 28, 2002 by Greg Mayer Copyright (c) 2002 Radical Entertainment, Inc. All rights reserved. ===========================================================================*/ #ifndef _REDBRICKCOLLISIONSOLVERAGENT_H #define _REDBRICKCOLLISIONSOLVERAGENT_H #include <worldsim/worldcollisionsolveragent.h> #include <simcommon/tlist.hpp> #include <simcollision/collisionanalyser.hpp> #include <simcollision/collisionanalyserdata.hpp> using namespace sim; // TODO - looking for the best place to put these // a necessary part of the RedBrick interface // TBJ moved 'em to <worldsim/physicsairef.h> // //enum RedBrickPhizAITypes { redBrickPhizDefault = 0, redBrickVehicle, redBrickPhizVehicleGroundPlane, redBrickPhizStatic, redBrickPhizMoveable, redBrickPhizMoveableAnim, redBrickPhizLast }; // phizGround, phizStatic, phizMoveableAnim, phizMoveable, phizCamera, phizLast }; class RedBrickCollisionSolverAgent : public WorldCollisionSolverAgent { public: RedBrickCollisionSolverAgent(); ~RedBrickCollisionSolverAgent(); // the key method to override Solving_Answer PreCollisionEvent(Collision& inCollision, int inPass); Solving_Answer TestImpulse(rmt::Vector& mImpulse, Collision& inCollision); Solving_Answer TestCache(SimState* inSimState, int inIndex); Solving_Answer EndObjectCollision(SimState* inSimState, int inIndex); Solving_Answer CarOnCarPreTest(Collision& inCollision, int inPass); virtual void ResetCollisionFlags(); bool mBottomedOut; float mBottomedOutScale; bool mWheelSidewaysHit; float mWheelSidewaysHitScale; }; #endif // _REDBRICKCOLLISIONSOLVERAGENT_H
1
0.629277
1
0.629277
game-dev
MEDIA
0.856696
game-dev
0.912586
1
0.912586
runelite/runelite
4,725
cache/src/main/java/net/runelite/cache/Cache.java
/* * Copyright (c) 2017, Adam <Adam@sigterm.info> * 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.cache; import java.io.File; import java.io.IOException; import net.runelite.cache.fs.Store; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Cache { public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("c", "cache", true, "cache base"); options.addOption(null, "items", true, "directory to dump items to"); options.addOption(null, "npcs", true, "directory to dump npcs to"); options.addOption(null, "objects", true, "directory to dump objects to"); options.addOption(null, "sprites", true, "directory to dump sprites to"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException ex) { System.err.println("Error parsing command line options: " + ex.getMessage()); System.exit(-1); return; } String cache = cmd.getOptionValue("cache"); Store store = loadStore(cache); if (cmd.hasOption("items")) { String itemdir = cmd.getOptionValue("items"); if (itemdir == null) { System.err.println("Item directory must be specified"); return; } System.out.println("Dumping items to " + itemdir); dumpItems(store, new File(itemdir)); } else if (cmd.hasOption("npcs")) { String npcdir = cmd.getOptionValue("npcs"); if (npcdir == null) { System.err.println("NPC directory must be specified"); return; } System.out.println("Dumping npcs to " + npcdir); dumpNpcs(store, new File(npcdir)); } else if (cmd.hasOption("objects")) { String objectdir = cmd.getOptionValue("objects"); if (objectdir == null) { System.err.println("Object directory must be specified"); return; } System.out.println("Dumping objects to " + objectdir); dumpObjects(store, new File(objectdir)); } else if (cmd.hasOption("sprites")) { String spritedir = cmd.getOptionValue("sprites"); if (spritedir == null) { System.err.println("Sprite directory must be specified"); return; } System.out.println("Dumping sprites to " + spritedir); dumpSprites(store, new File(spritedir)); } else { System.err.println("Nothing to do"); } } private static Store loadStore(String cache) throws IOException { Store store = new Store(new File(cache)); store.load(); return store; } private static void dumpItems(Store store, File itemdir) throws IOException { ItemManager dumper = new ItemManager(store); dumper.load(); dumper.export(itemdir); dumper.java(itemdir); } private static void dumpNpcs(Store store, File npcdir) throws IOException { NpcManager dumper = new NpcManager(store); dumper.load(); dumper.dump(npcdir); dumper.java(npcdir); } private static void dumpObjects(Store store, File objectdir) throws IOException { ObjectManager dumper = new ObjectManager(store); dumper.load(); dumper.dump(objectdir); dumper.java(objectdir); } private static void dumpSprites(Store store, File spritedir) throws IOException { SpriteManager dumper = new SpriteManager(store); dumper.load(); dumper.export(spritedir); } }
1
0.950218
1
0.950218
game-dev
MEDIA
0.600337
game-dev
0.891267
1
0.891267
BG-Software-LLC/SuperiorSkyblock2
3,852
src/main/java/com/bgsoftware/superiorskyblock/commands/player/CmdDemote.java
package com.bgsoftware.superiorskyblock.commands.player; import com.bgsoftware.superiorskyblock.SuperiorSkyblockPlugin; import com.bgsoftware.superiorskyblock.api.island.Island; import com.bgsoftware.superiorskyblock.api.island.IslandPrivilege; import com.bgsoftware.superiorskyblock.api.island.PlayerRole; import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer; import com.bgsoftware.superiorskyblock.commands.CommandTabCompletes; import com.bgsoftware.superiorskyblock.commands.IPermissibleCommand; import com.bgsoftware.superiorskyblock.commands.arguments.CommandArguments; import com.bgsoftware.superiorskyblock.core.events.plugin.PluginEventsFactory; import com.bgsoftware.superiorskyblock.core.messages.Message; import com.bgsoftware.superiorskyblock.island.privilege.IslandPrivileges; import java.util.Collections; import java.util.List; public class CmdDemote implements IPermissibleCommand { @Override public List<String> getAliases() { return Collections.singletonList("demote"); } @Override public String getPermission() { return "superior.island.demote"; } @Override public String getUsage(java.util.Locale locale) { return "demote <" + Message.COMMAND_ARGUMENT_PLAYER_NAME.getMessage(locale) + ">"; } @Override public String getDescription(java.util.Locale locale) { return Message.COMMAND_DESCRIPTION_DEMOTE.getMessage(locale); } @Override public int getMinArgs() { return 2; } @Override public int getMaxArgs() { return 2; } @Override public boolean canBeExecutedByConsole() { return false; } @Override public IslandPrivilege getPrivilege() { return IslandPrivileges.DEMOTE_MEMBERS; } @Override public Message getPermissionLackMessage() { return Message.NO_DEMOTE_PERMISSION; } @Override public void execute(SuperiorSkyblockPlugin plugin, SuperiorPlayer superiorPlayer, Island island, String[] args) { SuperiorPlayer targetPlayer = CommandArguments.getPlayer(plugin, superiorPlayer, args[1]); if (targetPlayer == null) return; if (!island.isMember(targetPlayer)) { Message.PLAYER_NOT_INSIDE_ISLAND.send(superiorPlayer); return; } if (!targetPlayer.getPlayerRole().isLessThan(superiorPlayer.getPlayerRole())) { Message.DEMOTE_PLAYERS_WITH_LOWER_ROLE.send(superiorPlayer); return; } PlayerRole previousRole = targetPlayer.getPlayerRole(); int roleLimit; do { previousRole = previousRole.getPreviousRole(); roleLimit = previousRole == null ? -1 : island.getRoleLimit(previousRole); } while (previousRole != null && !previousRole.isFirstRole() && roleLimit >= 0 && roleLimit >= island.getIslandMembers(previousRole).size()); if (previousRole == null) { Message.LAST_ROLE_DEMOTE.send(superiorPlayer); return; } if (!PluginEventsFactory.callPlayerChangeRoleEvent(targetPlayer, previousRole)) return; targetPlayer.setPlayerRole(previousRole); Message.DEMOTED_MEMBER.send(superiorPlayer, targetPlayer.getName(), targetPlayer.getPlayerRole()); Message.GOT_DEMOTED.send(targetPlayer, targetPlayer.getPlayerRole()); } @Override public List<String> tabComplete(SuperiorSkyblockPlugin plugin, SuperiorPlayer superiorPlayer, Island island, String[] args) { return args.length == 2 ? CommandTabCompletes.getIslandMembers(island, args[1], islandMember -> islandMember.getPlayerRole().isLessThan(superiorPlayer.getPlayerRole()) && islandMember.getPlayerRole().getPreviousRole() != null) : Collections.emptyList(); } }
1
0.80982
1
0.80982
game-dev
MEDIA
0.797287
game-dev
0.601933
1
0.601933
LeoMinecraftModding/eternal-starlight
2,240
common/src/main/java/cn/leolezury/eternalstarlight/common/mixin/ItemEntityMixin.java
package cn.leolezury.eternalstarlight.common.mixin; import cn.leolezury.eternalstarlight.common.registry.ESItems; import cn.leolezury.eternalstarlight.common.util.ESTags; import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.UUID; @Mixin(ItemEntity.class) public abstract class ItemEntityMixin { @Shadow public abstract ItemStack getItem(); @Shadow @Nullable private UUID target; @Shadow private int pickupDelay; @Shadow private int age; @Inject(method = "tick", at = @At("HEAD")) public void tick(CallbackInfo ci) { ItemEntity itemEntity = ((ItemEntity) (Object) this); // max age is 6000 if (age < 3000 && getItem().get(DataComponents.FOOD) != null && (itemEntity.level().getBlockState(itemEntity.blockPosition()).is(ESTags.Blocks.TOOTH_OF_HUNGER_BLOCKS) || itemEntity.level().getBlockState(itemEntity.blockPosition().below()).is(ESTags.Blocks.TOOTH_OF_HUNGER_BLOCKS))) { age = 3000; } } @Inject(method = "playerTouch", at = @At("HEAD"), cancellable = true) public void playerTouch(Player player, CallbackInfo ci) { ItemEntity itemEntity = ((ItemEntity) (Object) this); if (itemEntity.level().isClientSide) return; if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && getItem().is(ESItems.MANA_CRYSTAL_SHARD.get())) { ci.cancel(); player.take(itemEntity, getItem().getCount()); itemEntity.discard(); Inventory inventory = player.getInventory(); for (int i = 0; i < inventory.getContainerSize(); i++) { ItemStack stack = inventory.getItem(i); if (stack.is(ESTags.Items.MANA_CRYSTALS) && stack.isDamaged()) { stack.setDamageValue(Math.max(stack.getDamageValue() - getItem().getCount(), 0)); return; } } } } }
1
0.906337
1
0.906337
game-dev
MEDIA
0.994931
game-dev
0.974392
1
0.974392
Erick194/DOOM64-RE
15,996
doom64/p_move.c
#include "doomdef.h" #include "p_local.h" /*================== */ /* */ /* out */ /* */ /*================== */ extern mobj_t *tmthing; // 800A56B0 extern fixed_t tmx, tmy; // 800A56B4, 800A56B8 extern boolean checkposonly; // 800A56C8 /*================== */ /* */ /* in */ /* */ /*================== */ boolean trymove2; // 800A5D80 /* Result from P_TryMove2 */ boolean floatok; // 800A5D84 /* if true, move would be ok if within tmfloorz - tmceilingz */ fixed_t tmfloorz; // 800A5D88 /* Current floor z for P_TryMove2 */ fixed_t tmceilingz; // 800A5D8C /* Current ceiling z for P_TryMove2 */ mobj_t *movething; // 800A5D98 /* Either a skull/missile target or a special pickup */ line_t *blockline; // 800A5D9C /* Might be a door that can be opened */ fixed_t oldx, oldy; // 800A5DA0, 800A5DA4 fixed_t tmbbox[4]; // int tmflags; // 800A5DB8 fixed_t tmdropoffz; // 800A5D90 /* Lowest point contacted */ subsector_t *newsubsec; // 800A5D94 /* Dest subsector */ //PSX NEW line_t *thingspec[8]; // 800A5DE0 int numthingspec; // 800A5DE0 /* =================== = = P_TryMove2 = = Attempt to move to a new position, crossing special lines unless MF_TELEPORT = is set = =================== */ void P_TryMove2(void) // 80019980 { int side; int oldside; line_t *line; trymove2 = false; // until proven otherwise floatok = false; oldx = tmthing->x; oldy = tmthing->y; PM_CheckPosition(); if (checkposonly) { checkposonly = false; return; } if (!trymove2) return; if (!(tmthing->flags & MF_NOCLIP)) { trymove2 = false; if (tmceilingz - tmfloorz < tmthing->height) return; // doesn't fit floatok = true; if ( !(tmthing->flags&MF_TELEPORT) && tmceilingz - tmthing->z < tmthing->height) return; // mobj must lower itself to fit if ( !(tmthing->flags&MF_TELEPORT) && tmfloorz - tmthing->z > 24*FRACUNIT ) return; // too big a step up if ( !(tmthing->flags&(MF_DROPOFF|MF_FLOAT)) && tmfloorz - tmdropoffz > 24*FRACUNIT ) return; // don't stand over a dropoff } // // the move is ok, so link the thing into its new position // P_UnsetThingPosition(tmthing); tmthing->floorz = tmfloorz; tmthing->ceilingz = tmceilingz; tmthing->x = tmx; tmthing->y = tmy; P_SetThingPosition(tmthing); if (!(tmthing->flags & (MF_NOCLIP | MF_TELEPORT))) { while (numthingspec > 0) { numthingspec--; line = thingspec[numthingspec]; side = P_PointOnLineSide(tmthing->x, tmthing->y, line); oldside = P_PointOnLineSide(oldx, oldy, line); if (side != oldside) { if (!(line->flags & ML_TRIGGERFRONT) || (side)) { P_UseSpecialLine(line, tmthing); } } } } trymove2 = true; return; } /* ================== = = P_PointOnLineSide = = Returns 0 or 1 ================== */ int P_PointOnLineSide (fixed_t x, fixed_t y, line_t *line) // 80019C24 { fixed_t dx,dy; fixed_t left, right; if (!line->dx) { if (x <= line->v1->x) return line->dy > 0; return line->dy < 0; } if (!line->dy) { if (y <= line->v1->y) return line->dx < 0; return line->dx > 0; } dx = (x - line->v1->x); dy = (y - line->v1->y); left = (line->dy>>16) * (dx>>16); right = (dy>>16) * (line->dx>>16); if (right < left) return 0; /* front side */ return 1; /* back side */ } #if 0 static boolean PM_CrossCheck(line_t *ld) { if (PM_BoxCrossLine (ld)) { if (!PIT_CheckLine(ld)) { return true; } } return false; } /* ================== = = PM_PointOnLineSide = Exclusive Psx Doom = = Returns 0 or 1 = ================== */ int PM_PointOnLineSide(fixed_t x, fixed_t y, line_t *line)//L8001EB8C() { fixed_t dx, dy; fixed_t left, right; dx = (x - line->v1->x); dy = (y - line->v1->y); left = (line->dy >> 16) * (dx >> 16); right = (dy >> 16) *(line->dx >> 16); if (right < left) return 0; /* front side */ return 1; /* back side */ } #endif /* =============================================================================== THING POSITION SETTING =============================================================================== */ /* =================== = = P_UnsetThingPosition = = Unlinks a thing from block map and sectors = =================== */ void P_UnsetThingPosition (mobj_t *thing)//L8001C768() { int blockx, blocky; if (!(thing->flags & MF_NOSECTOR)) { /* inert things don't need to be in blockmap */ /* unlink from subsector */ if (thing->snext) thing->snext->sprev = thing->sprev; if (thing->sprev) thing->sprev->snext = thing->snext; else thing->subsector->sector->thinglist = thing->snext; } if (!(thing->flags & MF_NOBLOCKMAP)) { /* inert things don't need to be in blockmap */ /* unlink from block map */ if (thing->bnext) thing->bnext->bprev = thing->bprev; if (thing->bprev) thing->bprev->bnext = thing->bnext; else { blockx = (thing->x - bmaporgx)>>MAPBLOCKSHIFT; blocky = (thing->y - bmaporgy)>>MAPBLOCKSHIFT; // Prevent buffer overflow if the map object is out of bounds. // This is part of the fix for the famous 'linedef deletion' bug. // From PsyDoom (StationDoom) by BodbDearg #if FIX_LINEDEFS_DELETION == 1 if (blockx>=0 && blockx <bmapwidth && blocky>=0 && blocky <bmapheight) { blocklinks[blocky*bmapwidth+blockx] = thing->bnext; } #else blocklinks[blocky*bmapwidth+blockx] = thing->bnext; #endif } } } /* =================== = = P_SetThingPosition = = Links a thing into both a block and a subsector based on it's x y = Sets thing->subsector properly = =================== */ void P_SetThingPosition (mobj_t *thing) // 80019E20 { subsector_t *ss; sector_t *sec; int blockx, blocky; mobj_t **link; /* */ /* link into subsector */ /* */ ss = R_PointInSubsector (thing->x,thing->y); thing->subsector = ss; if(!(thing->flags & MF_NOSECTOR)) { /* invisible things don't go into the sector links */ sec = ss->sector; thing->sprev = NULL; thing->snext = sec->thinglist; if(sec->thinglist) sec->thinglist->sprev = thing; sec->thinglist = thing; } /* */ /* link into blockmap */ /* */ if(!(thing->flags & MF_NOBLOCKMAP)) { /* inert things don't need to be in blockmap */ blockx = (thing->x - bmaporgx)>>MAPBLOCKSHIFT; blocky = (thing->y - bmaporgy)>>MAPBLOCKSHIFT; if(blockx >= 0 && blockx < bmapwidth && blocky >= 0 && blocky < bmapheight) { link = &blocklinks[blocky*bmapwidth+blockx]; thing->bprev = NULL; thing->bnext = *link; if (*link) (*link)->bprev = thing; *link = thing; } else { /* thing is off the map */ thing->bnext = thing->bprev = NULL; } } } /* ================== = = PM_CheckPosition = = This is purely informative, nothing is modified (except things picked up) in: tmthing a mobj_t (can be valid or invalid) tmx,tmy a position to be checked (doesn't need relate to the mobj_t->x,y) out: newsubsec floorz ceilingz tmdropoffz the lowest point contacted (monsters won't move to a dropoff) movething ================== */ void PM_CheckPosition (void) // 80019F50 { int xl,xh,yl,yh,bx,by; tmflags = tmthing->flags; tmbbox[BOXTOP] = tmy + tmthing->radius; tmbbox[BOXBOTTOM] = tmy - tmthing->radius; tmbbox[BOXRIGHT] = tmx + tmthing->radius; tmbbox[BOXLEFT] = tmx - tmthing->radius; newsubsec = R_PointInSubsector(tmx,tmy); // // the base floor / ceiling is from the subsector that contains the // point. Any contacted lines the step closer together will adjust them // tmfloorz = tmdropoffz = newsubsec->sector->floorheight; tmceilingz = newsubsec->sector->ceilingheight; ++validcount; numthingspec = 0;//PSX movething = NULL; blockline = NULL; if (tmflags & MF_NOCLIP) { trymove2 = true; return; } // // check things first, possibly picking things up // the bounding box is extended by MAXRADIUS because mobj_ts are grouped // into mapblocks based on their origin point, and can overlap into adjacent // blocks by up to MAXRADIUS units // // [D64] no use MAXRADIUS // xl = (tmbbox[BOXLEFT] - bmaporgx/* - MAXRADIUS*/)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx/* + MAXRADIUS*/)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy/* - MAXRADIUS*/)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy/* + MAXRADIUS*/)>>MAPBLOCKSHIFT; if (xl<0) xl = 0; if (yl<0) yl = 0; if (xh>= bmapwidth) xh = bmapwidth -1; if (yh>= bmapheight) yh = bmapheight -1; for (bx = xl; bx <= xh; bx++) { for (by = yl; by <= yh; by++) { if (!PM_BlockThingsIterator(bx, by)) { trymove2 = false; return; } } } // // check lines // xl = (tmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; if (xl<0) xl = 0; if (yl<0) yl = 0; if (xh>= bmapwidth) xh = bmapwidth -1; if (yh>= bmapheight) yh = bmapheight -1; for (bx = xl; bx <= xh; bx++) { for (by = yl; by <= yh; by++) { if (!PM_BlockLinesIterator(bx, by)) { trymove2 = false; return; } } } trymove2 = true; return; } //============================================================================= /* ================= = = PM_BoxCrossLine = ================= */ boolean PM_BoxCrossLine (line_t *ld) // 8001A280 { boolean side1, side2; if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP] ) return false; switch(ld->slopetype) { case ST_HORIZONTAL: side1 = (ld->bbox[BOXTOP] < tmbbox[BOXTOP]); side2 = (ld->bbox[BOXTOP] < tmbbox[BOXBOTTOM]); break; case ST_VERTICAL: side1 = (ld->bbox[BOXLEFT] < tmbbox[BOXRIGHT]); side2 = (ld->bbox[BOXLEFT] < tmbbox[BOXLEFT]); break; case ST_POSITIVE: side1 = P_PointOnLineSide(tmbbox[BOXLEFT], tmbbox[BOXTOP], ld); side2 = P_PointOnLineSide(tmbbox[BOXRIGHT], tmbbox[BOXBOTTOM], ld); break; case ST_NEGATIVE: side1 = P_PointOnLineSide(tmbbox[BOXRIGHT], tmbbox[BOXTOP], ld); side2 = P_PointOnLineSide(tmbbox[BOXLEFT], tmbbox[BOXBOTTOM], ld); break; default: break; } return (0 < (side1 ^ side2)); } //============================================================================= /* ================== = = PIT_CheckLine = = Adjusts tmfloorz and tmceilingz as lines are contacted ================== */ boolean PIT_CheckLine (line_t *ld) // 8001A3DC { fixed_t pm_opentop, pm_openbottom; fixed_t pm_lowfloor; sector_t *front, *back; // a line has been hit /* = = The moving thing's destination position will cross the given line. = If this should not be allowed, return false. */ if (!ld->backsector) return false; // one sided line if (!(tmthing->flags & MF_MISSILE) ) { if ( ld->flags & ML_BLOCKING ) return false; // explicitly blocking everything if ( !tmthing->player && ld->flags & ML_BLOCKMONSTERS ) return false; // block monsters only } front = ld->frontsector; back = ld->backsector; if (front->ceilingheight == front->floorheight || back->ceilingheight == back->floorheight) { blockline = ld; return false; // probably a closed door } if (front->ceilingheight < back->ceilingheight) pm_opentop = front->ceilingheight; else pm_opentop = back->ceilingheight; if (front->floorheight > back->floorheight) { pm_openbottom = front->floorheight; pm_lowfloor = back->floorheight; } else { pm_openbottom = back->floorheight; pm_lowfloor = front->floorheight; } // adjust floor / ceiling heights if (pm_opentop < tmceilingz) tmceilingz = pm_opentop; if (pm_openbottom > tmfloorz) tmfloorz = pm_openbottom; if (pm_lowfloor < tmdropoffz) tmdropoffz = pm_lowfloor; // if contacted a special line, add it to the list if(ld->special & MLU_CROSS) { //New Psx Doom if (numthingspec < MAXTHINGSPEC) { thingspec[numthingspec] = ld; numthingspec++; } } return true; } /* ================== = = PIT_CheckThing = ================== */ boolean PIT_CheckThing(mobj_t *thing) // 8001A560 { fixed_t blockdist; fixed_t x, y; fixed_t rx, ry; if (thing == tmthing) return true; // don't clip against self if (!(thing->flags & (MF_SOLID|MF_SPECIAL|MF_SHOOTABLE) )) return true; blockdist = thing->radius + tmthing->radius; /*delta = thing->x - tmx; if (delta < 0) delta = -delta; if (delta >= blockdist) return true; // didn't hit it delta = thing->y - tmy; if (delta < 0) delta = -delta; if (delta >= blockdist) return true; // didn't hit it if (thing == tmthing) return true; // don't clip against self*/ // [d64]: different logic versus Jaguar Doom x = abs(thing->x - tmx); y = abs(thing->y - tmy); rx = blockdist - x; ry = blockdist - x; if(!(x < y)) { if(((rx - y) + (y >> 1)) <= 0) return true; // didn't hit it } else { if(((ry - y) + (x >> 1)) <= 0) return true; // didn't hit it } // // check for skulls slamming into things // if (tmthing->flags & MF_SKULLFLY) { movething = thing; return false; // stop moving } // // missiles can hit other things // if (tmthing->flags & MF_MISSILE) { // see if it went over / under if (tmthing->z > thing->z + thing->height) return true; // overhead if (tmthing->z+tmthing->height < thing->z) return true; // underneath if (tmthing->target->type == thing->type) // don't hit same species as originator { if (thing == tmthing->target) return true; if (thing->type != MT_PLAYER) // let players missile other players return false; // explode, but do no damage } if (! (thing->flags & MF_SHOOTABLE) ) return !(thing->flags & MF_SOLID); // didn't do any damage // damage / explode movething = thing; return false; // don't traverse any more } // // check for special pickup // if ((thing->flags&MF_SPECIAL) && (tmflags&MF_PICKUP) ) { movething = thing; return true; } return !(thing->flags & MF_SOLID); } /* =============================================================================== BLOCK MAP ITERATORS For each line/thing in the given mapblock, call the passed function. If the function returns false, exit with false without checking anything else. =============================================================================== */ /* ================== = = PM_BlockLinesIterator = Exclusive Psx Doom / Doom 64 = = The validcount flags are used to avoid checking lines = that are marked in multiple mapblocks, so increment validcount before = the first call to PM_BlockLinesIterator, then make one or more calls to it = ================== */ boolean PM_BlockLinesIterator(int x, int y) // 8001A710 { int offset; short *list; line_t *ld; offset = (y*bmapwidth)+x; offset = *(blockmap + offset); for (list = blockmaplump + offset; *list != -1; list++) { ld = &lines[*list]; if (ld->validcount == validcount) continue; /* line has already been checked */ ld->validcount = validcount; if (PM_BoxCrossLine(ld)) { if (!PIT_CheckLine(ld)) return false; } } return true; /* everything was checked */ } /* ================== = = PM_BlockThingsIterator = Exclusive Psx Doom / Doom 64 = ================== */ boolean PM_BlockThingsIterator(int x, int y) // 8001A810 { mobj_t *mobj; for (mobj = blocklinks[y * bmapwidth + x]; mobj; mobj = mobj->bnext) { if (!PIT_CheckThing(mobj)) return false; } return true; }
1
0.984705
1
0.984705
game-dev
MEDIA
0.691515
game-dev
0.998473
1
0.998473
OSRSB/OsrsBot
17,787
src/main/java/net/runelite/rsb/methods/Mouse.java
package net.runelite.rsb.methods; import net.runelite.rsb.internal.MouseHandler; import net.runelite.api.Point; /** * Mouse related operations. */ public class Mouse extends MethodProvider { private int mouseSpeed = MouseHandler.DEFAULT_MOUSE_SPEED; private int minReaction = 50; private int maxReaction = 350; Mouse(final MethodContext ctx) { super(ctx); } /** * Configure reaction speed * @param min min mouse 'reaction' speed, -1 will be ignored * @param max max mouse 'reaction' speed, -1 will be ignored */ public void setReactionSpeed(int min, int max) { if (max != -1) { minReaction = min; } if (max != -1) { maxReaction = max; } } /** * Author - Enfilade Moves the mouse a random distance between 1 and * maxDistance from the current position of the mouse by generating a random * vector and then multiplying it by a random number between 1 and * maxDistance. The maximum distance is cut short if the mouse would go off * screen in the direction it chose. * * @param maxDistance The maximum distance the cursor will move (exclusive) */ public void moveRandomly(final int maxDistance) { moveRandomly(1, maxDistance); } /** * Author - Enfilade Moves the mouse a random distance between minDistance * and maxDistance from the current position of the mouse by generating * random vector and then multiplying it by a random number between * minDistance and maxDistance. The maximum distance is cut short if the * mouse would go off screen in the direction it chose. * * @param minDistance The minimum distance the cursor will move * @param maxDistance The maximum distance the cursor will move (exclusive) */ public void moveRandomly(final int minDistance, final int maxDistance) { /* Generate a random vector for the direction the mouse will move in */ double xvec = Math.random(); if (random(0, 2) == 1) { xvec = -xvec; } double yvec = Math.sqrt(1 - xvec * xvec); if (random(0, 2) == 1) { yvec = -yvec; } /* Start the maximum distance at maxDistance */ double distance = maxDistance; /* Get the current location of the cursor */ Point p = getLocation(); /* Calculate the x coordinate if the mouse moved the maximum distance */ int maxX = (int) Math.round(xvec * distance + p.getX()); /* * If the maximum x is offscreen, subtract that distance/xvec from the * maximum distance so the maximum distance will give a valid X * coordinate */ distance -= Math.abs((maxX - Math.max(0, Math.min(methods.game.getWidth(), maxX))) / xvec); /* Do the same thing with the Y coordinate */ int maxY = (int) Math.round(yvec * distance + p.getY()); distance -= Math.abs((maxY - Math.max(0, Math.min(methods.game.getHeight(), maxY))) / yvec); /* * If the maximum distance in the generated direction is too small, * don't move the mouse at all */ if (distance < minDistance) { return; } /* * With the calculated maximum distance, pick a random distance to move * the mouse between maxDistance and the calculated maximum distance */ distance = random(minDistance, (int) distance); /* Generate the point to move the mouse to and move it there */ move((int) (xvec * distance) + p.getX(), (int) (yvec * distance) + p.getY()); } /** * Moves the mouse off the screen in a random direction. */ public void moveOffScreen() { if (isPresent()) { switch (random(0, 4)) { case 0: // up move(random(-10, methods.game.getWidth() + 10), random(-100, -10)); break; case 1: // down move(random(-10, methods.game.getWidth() + 10), methods.game.getHeight() + random(10, 100)); break; case 2: // left move(random(-100, -10), random(-10, methods.game.getHeight() + 10)); break; case 3: // right move(random(10, 100) + methods.game.getWidth(), random(-10, methods.game.getHeight() + 10)); break; } } } /** * Drag the mouse from the current position to a certain other position. * * @param x The x coordinate to drag to. * @param y The y coordinate to drag to. */ public void drag(final int x, final int y) { methods.inputManager.dragMouse(x, y); } /** * Drag the mouse from the current position to a certain other position. * * @param p The point to drag to. * @see #drag(int, int) */ public void drag(final Point p) { drag(p.getX(), p.getY()); } /** * Clicks the mouse at its current location. * * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. */ public void click(final boolean leftClick) { click(leftClick, MouseHandler.DEFAULT_MAX_MOVE_AFTER); } public synchronized void click(final boolean leftClick, final int moveAfterDist) { methods.inputManager.clickMouse(leftClick); if (moveAfterDist > 0) { sleep(random(minReaction, maxReaction)); Point pos = getLocation(); move(pos.getX() - moveAfterDist, pos.getY() - moveAfterDist, moveAfterDist * 2, moveAfterDist * 2); } } /** * Moves the mouse to a given location then clicks. * * @param x x coordinate * @param y y coordinate * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. */ public void click(final int x, final int y, final boolean leftClick) { click(x, y, 0, 0, leftClick); } /** * Moves the mouse to a given location with given randomness then clicks. * * @param x x coordinate * @param y y coordinate * @param randX x randomness (added to x) * @param randY y randomness (added to y) * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. * @see #move(int, int, int, int) */ public synchronized void click(final int x, final int y, final int randX, final int randY, final boolean leftClick) { move(x, y, randX, randY); sleep(random(minReaction, maxReaction)); click(leftClick, MouseHandler.DEFAULT_MAX_MOVE_AFTER); } /** * Moves the mouse to a given location with given randomness then clicks, * then moves a random distance up to <code>afterOffset</code>. * * @param x x coordinate * @param y y coordinate * @param randX x randomness (added to x) * @param randY y randomness (added to y) * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. * @param moveAfterDist The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ public synchronized void click(final int x, final int y, final int randX, final int randY, final boolean leftClick, final int moveAfterDist) { move(x, y, randX, randY); sleep(random(minReaction, maxReaction)); click(leftClick, moveAfterDist); } /** * Moves the mouse to a given location then clicks. * * @param p The point to click. * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. */ public void click(final Point p, final boolean leftClick) { click(p.getX(), p.getY(), leftClick); } public void click(final Point p, final int x, final int y, final boolean leftClick) { click(p.getX(), p.getY(), x, y, leftClick); } /** * Moves the mouse to a given location with given randomness then clicks, * then moves a random distance up to <code>afterOffset</code>. * * @param p The destination Point. * @param x x coordinate * @param y y coordinate * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. * @param moveAfterDist The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ public void click(final Point p, final int x, final int y, final boolean leftClick, final int moveAfterDist) { click(p.getX(), p.getY(), x, y, leftClick, moveAfterDist); } /** * Clicks without any delay before clicking for times when accuracy is required * * @param leftClick <code>true</code> to left-click, <code>false</code>to right-click. */ public synchronized void clickImmediately(boolean leftClick) { click(leftClick, MouseHandler.DEFAULT_MAX_MOVE_AFTER); } /** * Moves the mouse slightly depending on where it currently is and clicks. */ public void clickSlightly() { Point p = new Point( (int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90)), (int) (getLocation() .getY() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90))); if (p.getX() < 1 || p.getY() < 1 || p.getX() > 761 || p.getY() > 499) { clickSlightly(); return; } click(p, true); } /** * Gets the mouse speed. * * @return the current mouse speed. * @see #setSpeed(int) */ public int getSpeed() { return mouseSpeed; } /** * Changes the mouse speed * * @param speed The speed to move the mouse at. 4-10 is advised, 1 being the * fastest. * @see #getSpeed() */ public void setSpeed(final int speed) { mouseSpeed = speed; } /** * Moves mouse to location (x,y) at default speed. * * @param x x coordinate * @param y y coordinate * @see #move(int, int, int, int) * @see #setSpeed(int) */ public void move(final int x, final int y) { move(x, y, 0, 0); } /** * Moves the mouse to the specified point and then by a randomized offset at default speed. * * @param x The x destination. * @param y The y destination. * @param afterOffset The maximum distance in pixels to move on both axes shortly * after moving to the destination. * @see #move(int, int, int, int, int, int) */ public void move(final int x, final int y, final int afterOffset) { move(getSpeed(), x, y, 0, 0, afterOffset); } /** * Moves the mouse to the specified point with a randomized variation at default speed. * * @param x The x destination. * @param y The y destination. * @param randX x-axis randomness (added to x). * @param randY y-axis randomness (added to y). * @see #move(int, int, int, int, int, int) * @see #setSpeed(int) */ public void move(final int x, final int y, final int randX, final int randY) { move(getSpeed(), x, y, randX, randY, 0); } /** * Moves the mouse to the specified point at a certain speed. * * @param speed The lower, the faster. * @param x The x destination. * @param y The y destination. * @param randX x-axis randomness (added to x). * @param randY y-axis randomness (added to y). * @see #move(int, int, int, int, int, int) */ public void move(final int speed, final int x, final int y, final int randX, final int randY) { move(speed, x, y, randX, randY, 0); } /** * Moves the mouse to the specified point at a certain speed with variance in the x and y, then moves a * random distance up to <code>afterOffset</code>. * * @param speed The lower, the faster. * @param x The x destination. * @param y The y destination. * @param randX X-axis randomness (added to x). * @param randY X-axis randomness (added to y). * @param afterOffset The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ public synchronized void move(final int speed, final int x, final int y, final int randX, final int randY, final int afterOffset) { if (x != -1 || y != -1) { methods.inputManager.moveMouse(speed, x, y, randX, randY); if (afterOffset > 0) { sleep(random(minReaction, maxReaction)); Point pos = getLocation(); move(pos.getX() - afterOffset, pos.getY() - afterOffset, afterOffset * 2, afterOffset * 2); } } } /** * Moves the mouse to the specified point at a certain speed * * @param speed The lower, the faster. * @param p The x and y destination. */ public void move(final int speed, final Point p) { move(speed, p.getX(), p.getY(), 0, 0, 0); } /** * Moves the mouse to the specified point * * @param p The x and y destination. */ public void move(final Point p) { move(p.getX(), p.getY(), 0, 0); } /** * Moves the mouse to the specified point then adds random distance up to <code>afterOffset</code>. * @param p The x and y destination. * @param afterOffset The maximum distance in pixels to move on both axes shortly * after moving to the destination. * */ public void move(final Point p, final int afterOffset) { move(getSpeed(), p.getX(), p.getY(), 0, 0, afterOffset); } /** * Moves the mouse to the specified point then adds random distance within to randX and randY * @param p The x and y destination. * @param randX X-axis randomness (added to x). * @param randY X-axis randomness (added to y). */ public void move(final Point p, final int randX, final int randY) { move(p.getX(), p.getY(), randX, randY); } /** * Moves the mouse to the specified point at a certain speed with variance in the x and y, then moves a * random distance up to <code>afterOffset</code>. * * @param p The x and y destination. * @param randX X-axis randomness (added to x). * @param randY X-axis randomness (added to y). * @param afterOffset The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ public void move(final Point p, final int randX, final int randY, final int afterOffset) { move(getSpeed(), p.getX(), p.getY(), randX, randY, afterOffset); } /** * Scrolls the mouse wheel by i amount of clicks * * @param i The number of clicks. Positive is scroll down, negative is scroll up. */ public void scroll(int i) { methods.inputManager.moveMouseWheel(i); } /** * Hops mouse to the specified coordinate. * * @param x The x coordinate. * @param y The y coordinate */ public synchronized void hop(final int x, final int y) { methods.inputManager.hopMouse(x, y); } /** * Hops mouse to the specified point. * * @param p The coordinate point. * @see #hop(Point) */ public void hop(final Point p) { hop(p.getX(), p.getY()); } /** * Hops mouse to the certain coordinate. * * @param x The x coordinate. * @param y The y coordinate. * @param randX The x coordinate randomization. * @param randY The y coordinate randomization. * @see #hop(int, int) */ public void hop(final int x, final int y, final int randX, final int randY) { hop(x + random(-randX, randX), y + random(-randX, randY)); } /** * Hops mouse to the certain point. * * @param p The coordinate point. * @param randX The x coordinate randomization. * @param randY The y coordinate randomization. * @see #hop(int, int, int, int) */ public void hop(final Point p, final int randX, final int randY) { hop(p.getX(), p.getY(), randX, randY); } /** * Moves the mouse slightly depending on where it currently is. */ public void moveSlightly() { Point p = new Point( (int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90)), (int) (getLocation() .getY() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90))); if (p.getX() < 1 || p.getY() < 1 || p.getX() > 761 || p.getY() > 499) { moveSlightly(); return; } move(p); } /** * @param maxDistance The maximum distance outwards. * @return A random x value between the current client location and the max * distance outwards. */ public int getRandomX(final int maxDistance) { Point p = getLocation(); if (p.getX() < 0 || maxDistance <= 0) { return -1; } if (random(0, 2) == 0) { return p.getX() - random(0, Math.min(p.getX(), maxDistance)); } else { int dist = methods.game.getWidth() - p.getX(); return p.getX() + random(1, dist < maxDistance && dist > 0 ? dist : maxDistance); } } /** * @param maxDistance The maximum distance outwards. * @return A random y value between the current client location and the max * distance outwards. */ public int getRandomY(final int maxDistance) { Point p = getLocation(); if (p.getY() < 0 || maxDistance <= 0) { return -1; } if (random(0, 2) == 0) { return p.getY() - random(0, Math.min(p.getY(), maxDistance)); } else { int dist = methods.game.getHeight() - p.getY(); return p.getY() + random(1, dist < maxDistance && dist > 0 ? dist : maxDistance); } } /** * The location of the bot's mouse; or Point(-1, -1) if off screen. * * @return A <code>Point</code> containing the bot's mouse's x and y coordinates. */ public Point getLocation() { return new Point(methods.virtualMouse.getClientX(), methods.virtualMouse.getClientY()); } /** * @return The <code>Point</code> at which the bot's mouse was last clicked. */ public Point getPressLocation() { return new Point(methods.virtualMouse.getClientPressX(), methods.virtualMouse.getClientPressY()); } /** * @return The system time when the bot's mouse was last pressed. */ public long getPressTime() { return methods.virtualMouse.getClientPressTime(); } /** * @return <code>true</code> if the bot's mouse is present. */ public boolean isPresent() { return methods.virtualMouse.isClientPresent(); } /** * @return <code>true</code> if the bot's mouse is pressed. */ public boolean isPressed() { return methods.virtualMouse.isClientPressed(); } }
1
0.784764
1
0.784764
game-dev
MEDIA
0.444168
game-dev
0.912049
1
0.912049
jcmkk3/trochilidae
5,774
berylline/berylline.yml
meta: engine: 4.0.0 name: berylline version: 0.4 author: jcmkk3 url: https://github.com/jcmkk3/trochilidae presets: # These presets provide different layout options # Select a preset in the `units` section below # Note: The appropriate switch footprint will still need to be set in the `pcb` section defaults: capx: 17 # Key cap size horizontal capy: 16 # Key cap size vertical kx: 18.5 # Key spacing horizontal ky: 17.5 # Key spacing vertical pinky_splay: 5 # Degrees of splay between pinky and ring columns pinky_adj: -3 # Adjustment to compensate for splay spacing ring_splay: 3 ring_adj: -8 middle_splay: 0 middle_adj: 0 thumb_offsetx: 0.25kx choc_spaced: $extends: presets.defaults choc_min_spaced: $extends: presets.defaults capx: 14.5 capy: 14.5 kx: 15.5 ky: 15.5 middle_splay: 3 middle_adj: -5 thumb_offsetx: 1/3kx mx_spaced: $extends: presets.defaults capx: 18 capy: 18 kx: 19 ky: 19 pinky_adj: -4 ring_adj: -10 mx_min_spaced: $extends: presets.defaults capx: 15.5 capy: 15.5 kx: 16.5 ky: 16.5 middle_splay: 3 middle_adj: -5 thumb_offsetx: 1/3kx units: $extends: presets.choc_spaced # Defaults/Constants # ==================== $default_height: 0 # Points invisible by default unless height/width explicitly set $default_width: 0 promicro_x: 33 promicro_y: 18 sf: 15 points: # Keys/Switches # ============= zones.matrix: anchor.shift: [150, -180] rotate: pinky_splay + ring_splay + middle_splay key: width: capx height: capy spread: kx padding: ky rows: bottom: home: top: columns: pinky: rows.bottom.skip: true ring.key: stagger: 2/3ky splay: -pinky_splay origin: [0, pinky_adj] middle.key: stagger: 0.25ky splay: -ring_splay origin: [0, ring_adj] index.key: stagger: -0.25ky splay: -middle_splay origin: [0, middle_adj] inner: key.stagger: -0.5ky rows.bottom.skip: true zones.thumb: anchor: ref: matrix_index_bottom shift: [thumb_offsetx, -22] key.$extends: points.zones.matrix.key columns: tucky: reachy.key.stagger: -0.25ky # Outline Extents # =============== zones.outline_top_left: anchor: - ref: matrix_middle_top shift: [0.5sf, 0.5sf] affect: y - ref: matrix_pinky_top affect: x shift: [-0.5sf, 0.5sf] zones.outline_top_right: anchor: - ref: outline_top_left - ref: thumb_reachy affect: x shift: [0.5sf, -0.5sf] zones.outline_bottom_left: anchor: - ref: outline_top_left - ref: thumb_reachy affect: y shift: [0.5sf, -0.5sf] zones.outline_bottom_right: anchor: - ref: outline_top_right - ref: outline_bottom_left affect: y # Components # ========== zones.mcu: anchor: ref: outline_bottom_left shift: [0.5promicro_x + 3, 0.5promicro_y + 3] key: width: promicro_x height: promicro_y zones.battery_connector: anchor: ref: matrix_index_bottom affect: xy shift: [-kx, -0.5ky] key: height: 1.5 width: 6 zones.reset: anchor: - ref: mcu shift: [0, 0.5promicro_y + 4] affect: y - ref: outline_bottom_left shift: [2.5, 0] affect: x key: height: 6 width: 3 zones.mounting_hole_top: anchor: - ref: matrix_pinky_top affect: y shift: [0, 0.5ky + 4.5] - ref: matrix_ring_top affect: x shift: [-0.5kx - 2.5, 0] key: height: 2 width: 2 zones.mounting_hole_bottom: anchor: - ref: matrix_inner_home affect: y shift: [0, -0.5ky - 2.5] - ref: matrix_index_bottom affect: x shift: [0.5kx + 2.5, 0] key.$extends: points.zones.mounting_hole_top.key outlines: panel: - what: polygon fillet: 3 points: - ref: outline_top_left - ref: outline_top_right - ref: outline_bottom_right - ref: outline_bottom_left _mcu: - what: rectangle where: mcu size: [promicro_x, promicro_y] _mounting_holes: - what: circle where: /mounting_hole_.*/ radius: 1 _keycaps: - what: rectangle where: - /matrix_.*/ - /thumb_.*/ size: [capx, capy] bound: false key_demo: - panel - ^_mcu - ^_mounting_holes - ^_keycaps pcbs.berylline: outlines.main: outline: panel footprints: - what: choc where: - /matrix_.*/ - /thumb_.*/ params: from: GND to: "{{name}}" reverse: true keycaps: true - what: promicro where: mcu adjust.shift: [1.5, 0] # Compensate for midpoint being off-center params: orientation: up P21: matrix_pinky_top P20: matrix_pinky_home P19: matrix_ring_top P18: matrix_ring_home P15: matrix_ring_bottom P14: matrix_middle_top P16: matrix_middle_home P10: matrix_middle_bottom P3: matrix_index_top P4: matrix_index_home P5: matrix_index_bottom P6: matrix_inner_top P7: matrix_inner_home P8: thumb_reachy P9: thumb_tucky - what: jstph where: battery_connector params: pos: RAW neg: GND - what: via where: /mounting_hole_.*/ params.net: "" - what: button where: reset adjust.rotate: 90 params: from: RST to: GND
1
0.981982
1
0.981982
game-dev
MEDIA
0.273764
game-dev
0.747285
1
0.747285
EmptyBottleInc/DFU-Tanguy-Multiplayer
2,767
Packages/com.unity.postprocessing/PostProcessing/Editor/Effects/BloomEditor.cs
using UnityEngine.Rendering.PostProcessing; namespace UnityEditor.Rendering.PostProcessing { [PostProcessEditor(typeof(Bloom))] internal sealed class BloomEditor : PostProcessEffectEditor<Bloom> { SerializedParameterOverride m_Intensity; SerializedParameterOverride m_Threshold; SerializedParameterOverride m_SoftKnee; SerializedParameterOverride m_Clamp; SerializedParameterOverride m_Diffusion; SerializedParameterOverride m_AnamorphicRatio; SerializedParameterOverride m_Color; SerializedParameterOverride m_FastMode; SerializedParameterOverride m_DirtTexture; SerializedParameterOverride m_DirtIntensity; public override void OnEnable() { m_Intensity = FindParameterOverride(x => x.intensity); m_Threshold = FindParameterOverride(x => x.threshold); m_SoftKnee = FindParameterOverride(x => x.softKnee); m_Clamp = FindParameterOverride(x => x.clamp); m_Diffusion = FindParameterOverride(x => x.diffusion); m_AnamorphicRatio = FindParameterOverride(x => x.anamorphicRatio); m_Color = FindParameterOverride(x => x.color); m_FastMode = FindParameterOverride(x => x.fastMode); m_DirtTexture = FindParameterOverride(x => x.dirtTexture); m_DirtIntensity = FindParameterOverride(x => x.dirtIntensity); } public override void OnInspectorGUI() { EditorUtilities.DrawHeaderLabel("Bloom"); PropertyField(m_Intensity); PropertyField(m_Threshold); PropertyField(m_SoftKnee); PropertyField(m_Clamp); PropertyField(m_Diffusion); PropertyField(m_AnamorphicRatio); PropertyField(m_Color); PropertyField(m_FastMode); if (m_FastMode.overrideState.boolValue && !m_FastMode.value.boolValue && EditorUtilities.isTargetingConsolesOrMobiles) EditorGUILayout.HelpBox("For performance reasons it is recommended to use Fast Mode on mobile and console platforms.", MessageType.Warning); EditorGUILayout.Space(); EditorUtilities.DrawHeaderLabel("Dirtiness"); PropertyField(m_DirtTexture); PropertyField(m_DirtIntensity); if (RuntimeUtilities.isVREnabled) { if ((m_DirtIntensity.overrideState.boolValue && m_DirtIntensity.value.floatValue > 0f) || (m_DirtTexture.overrideState.boolValue && m_DirtTexture.value.objectReferenceValue != null)) EditorGUILayout.HelpBox("Using a dirt texture in VR is not recommended.", MessageType.Warning); } } } }
1
0.966648
1
0.966648
game-dev
MEDIA
0.626398
game-dev,graphics-rendering
0.990605
1
0.990605
LandSandBoat/server
1,082
scripts/actions/mobskills/unblest_jambiya.lua
----------------------------------- -- Unblest Jambiya -- Family: Qutrub -- Description: Steals HP from targets in an area of effect. -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: AoE 15' -- Notes: Used only by certain NM's when their primary sword isn't broken. ----------------------------------- ---@type TMobSkill local mobskillObject = {} mobskillObject.onMobSkillCheck = function(target, mob, skill) if mob:getAnimationSub() == 0 then return 0 else return 1 end end mobskillObject.onMobWeaponSkill = function(target, mob, skill) local damage = mob:getWeaponDmg() * 3 damage = xi.mobskills.mobMagicalMove(mob, target, skill, damage, xi.element.DARK, 1.3, xi.mobskills.magicalTpBonus.MAB_BONUS, 1) damage = xi.mobskills.mobFinalAdjustments(damage, mob, skill, target, xi.attackType.MAGICAL, xi.damageType.DARK, xi.mobskills.shadowBehavior.WIPE_SHADOWS) skill:setMsg(xi.mobskills.mobPhysicalDrainMove(mob, target, skill, xi.mobskills.drainType.HP, damage)) return damage end return mobskillObject
1
0.841697
1
0.841697
game-dev
MEDIA
0.933587
game-dev
0.714177
1
0.714177
gearvrf/GearVRf-Demos
6,435
gvr-keyboard/app/src/main/java/org/gearvrf/keyboard/spinner/Spinner.java
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gearvrf.keyboard.spinner; import android.util.Log; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.gearvrf.GVRCameraRig; import org.gearvrf.GVRContext; import org.gearvrf.GVRPicker; import org.gearvrf.GVRSceneObject; import org.gearvrf.animation.GVRAnimation; import org.gearvrf.animation.GVROnFinish; import org.gearvrf.animation.GVROpacityAnimation; import org.gearvrf.keyboard.model.CharList; import org.gearvrf.keyboard.textField.TextFieldItem; import org.gearvrf.keyboard.util.Util; public class Spinner extends GVRSceneObject { private static final float Z_DISTANCE = 3 * 0.15f; private static final float ANIMATION_TIME = .1f; private SpinnerSkeleton spinnerSkeleton; private SpinnerRoulette spinnerRoulette; private boolean active; private boolean isShuttingDown; public boolean isActive() { return active; } public Spinner(GVRContext gvrContext, int initialCharacterPosition, int mode) { super(gvrContext); spinnerRoulette = new SpinnerRoulette(gvrContext, initialCharacterPosition, mode); spinnerSkeleton = new SpinnerSkeleton(gvrContext); addChildObject(spinnerRoulette); addChildObject(spinnerSkeleton); } public SpinnerSkeleton getSpinnerSkeleton() { return spinnerSkeleton; } public SpinnerRoulette getSpinnerRoulette() { return spinnerRoulette; } public synchronized void off() { spinnerRoulette.setSoudOn(false); isShuttingDown = true; spinnerRoulette.stopAnimations(); for (int i = 0; i < spinnerRoulette.getSpinnerAdapter().getSpinnerItems().size(); i++) { new GVROpacityAnimation(spinnerRoulette.getSpinnerAdapter().getSpinnerItems().get(i), ANIMATION_TIME, 0).start( this.getGVRContext().getAnimationEngine()); } new GVROpacityAnimation(spinnerSkeleton.getSpinnerBox(), ANIMATION_TIME, 0).start(this .getGVRContext().getAnimationEngine()); new GVROpacityAnimation(spinnerSkeleton.getSpinnerShadow(), ANIMATION_TIME, 0).start( this.getGVRContext().getAnimationEngine()).setOnFinish( new GVROnFinish() { @Override public void finished(GVRAnimation arg0) { active = false; spinnerRoulette.cleanRotation(); isShuttingDown = false; } }); } public boolean isShuttingDown() { return isShuttingDown; } public void setShuttingDown(boolean isShuttingDown) { this.isShuttingDown = isShuttingDown; } public synchronized void on(int initialCharacterPosition, int mode, int position) { spinnerRoulette.setSoudOn(true); spinnerRoulette.setInitialCharacterPosition(initialCharacterPosition); spinnerRoulette.setPosition(position); spinnerRoulette.getSpinnerAdapter().setCharacterList( CharList.getInstance(getGVRContext()).getListCircular(mode)); spinnerRoulette.setDefaultCharactersInSpinner(); new GVROpacityAnimation(spinnerSkeleton.getSpinnerBox(), ANIMATION_TIME, 1).start(this .getGVRContext().getAnimationEngine()); new GVROpacityAnimation(spinnerSkeleton.getSpinnerShadow(), ANIMATION_TIME, 1).start(this .getGVRContext().getAnimationEngine()); for (int i = 0; i < spinnerRoulette.getSpinnerAdapter().getSpinnerItems().size(); i++) { new GVROpacityAnimation(spinnerRoulette.getSpinnerAdapter().getSpinnerItems().get(i), ANIMATION_TIME, 1).start( this.getGVRContext().getAnimationEngine()); active = true; } } public boolean isHitArea(GVRSceneObject sceneObject) { if (sceneObject.getCollider().hashCode() == spinnerSkeleton.getSpinnerBox().getCollider().hashCode()) { return false; } return true; } public void move(TextFieldItem currentChar) { float x = currentChar.getTransform().getPositionX(); float y = currentChar.getTransform().getPositionY(); float z = currentChar.getTransform().getPositionZ() + Z_DISTANCE; getTransform().setPosition(x, y, z); lookAt(currentChar); } private void lookAt(GVRSceneObject currentChar) { GVRCameraRig camera = this.getGVRContext().getMainScene().getMainCameraRig(); Vector3D vectorCamera = new Vector3D(camera.getTransform().getPositionX(), camera .getTransform().getPositionY(), camera.getTransform() .getPositionZ()); Vector3D vectorKeyboard = new Vector3D(this.getParent().getParent().getTransform() .getPositionX(), this.getParent().getParent() .getTransform().getPositionY(), this.getParent().getParent().getTransform() .getPositionZ()); float newX = currentChar.getTransform().getPositionX() + currentChar.getParent().getTransform().getPositionX(); float newY = 0; float newZ = (float) Vector3D.distance(vectorKeyboard, vectorCamera); Log.d("lookatspinner", "newX " + newX); Log.d("lookatspinner", "newY " + newY); Log.d("lookatspinner", "newZ " + newZ); Vector3D emulatedSpinner = new Vector3D(newX, newY, newZ * -1); Vector3D emulateCam = new Vector3D(0, 0, 0); float angle = Util.getYRotationAngle(emulatedSpinner, emulateCam); Log.d("lookatspinner", "angle " + angle); // angle =(float) (angle*1.1); Log.d("lookatspinner", "angle new" + angle); getTransform().setRotationByAxis(angle, 0, 1, 0); } }
1
0.776095
1
0.776095
game-dev
MEDIA
0.256375
game-dev
0.911121
1
0.911121
Shestak/ShestakUI
10,129
ShestakUI/Modules/Blizzard/ClassColorNames.lua
if IsAddOnLoaded("yClassColor") then return end ---------------------------------------------------------------------------------------- -- Class color guild/friends/etc list(yClassColor by Yleaf) ---------------------------------------------------------------------------------------- local GUILD_INDEX_MAX = 12 local SMOOTH = {1, 0, 0, 1, 1, 0, 0, 1, 0} local BC = {} for k, v in pairs(LOCALIZED_CLASS_NAMES_MALE) do BC[v] = k end for k, v in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do BC[v] = k end local RAID_CLASS_COLORS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS local WHITE_HEX = "|cffffffff" local function Hex(r, g, b) if type(r) == "table" then if (r.r) then r, g, b = r.r, r.g, r.b else r, g, b = unpack(r) end end if not r or not g or not b then r, g, b = 1, 1, 1 end return format("|cff%02x%02x%02x", r * 255, g * 255, b * 255) end local function ColorGradient(perc, ...) if perc >= 1 then local r, g, b = select(select("#", ...) - 2, ...) return r, g, b elseif perc <= 0 then local r, g, b = ... return r, g, b end local num = select("#", ...) / 3 local segment, relperc = math.modf(perc * (num - 1)) local r1, g1, b1, r2, g2, b2 = select((segment * 3) + 1, ...) return r1 + (r2 - r1) * relperc, g1 + (g2 - g1) * relperc, b1 + (b2 - b1) * relperc end local guildRankColor = setmetatable({}, { __index = function(t, i) if i then local c = Hex(ColorGradient(i / GUILD_INDEX_MAX, unpack(SMOOTH))) if c then t[i] = c return c else t[i] = t[0] end end end }) guildRankColor[0] = WHITE_HEX local diffColor = setmetatable({}, { __index = function(t, i) local c = i and GetQuestDifficultyColor(i) t[i] = c and Hex(c) or t[0] return t[i] end }) diffColor[0] = WHITE_HEX local classColor = setmetatable({}, { __index = function(t, i) local c = i and RAID_CLASS_COLORS[BC[i] or i] if c then t[i] = Hex(c) return t[i] else return WHITE_HEX end end }) local WHITE = {1, 1, 1} local classColorRaw = setmetatable({}, { __index = function(t, i) local c = i and RAID_CLASS_COLORS[BC[i] or i] if not c then return WHITE end t[i] = c return c end }) if CUSTOM_CLASS_COLORS then CUSTOM_CLASS_COLORS:RegisterCallback(function() wipe(classColorRaw) wipe(classColor) end) end -- WhoList local function whoFrame(self) local playerZone = GetRealZoneText() local playerGuild = GetGuildInfo("player") local playerRace = UnitRace("player") for i = 1, self.ScrollTarget:GetNumChildren() do local button = select(i, self.ScrollTarget:GetChildren()) local nameText = button.Name local levelText = button.Level local variableText = button.Variable local info = C_FriendList.GetWhoInfo(button.index) if info then local guild, level, race, zone, class = info.fullGuildName, info.level, info.raceStr, info.area, info.filename if zone == playerZone then zone = "|cff00ff00"..zone end if guild == playerGuild then guild = "|cff00ff00"..guild end if race == playerRace then race = "|cff00ff00"..race end local columnTable = {zone, guild, race} local c = classColorRaw[class] nameText:SetTextColor(c.r, c.g, c.b) levelText:SetText(diffColor[level]..level) variableText:SetText(columnTable[UIDropDownMenu_GetSelectedID(_G.WhoFrameDropDown)]) end end end hooksecurefunc(_G.WhoFrame.ScrollBox, "Update", whoFrame) -- LFRBrowseList hooksecurefunc("LFRBrowseFrameListButton_SetData", function(button, index) local name, level, _, className, _, _, _, class = SearchLFGGetResults(index) if index and class and name and level then button.name:SetText(classColor[class]..name) button.class:SetText(classColor[class]..className) button.level:SetText(diffColor[level]..level) button.level:SetWidth(30) end end) -- PVPMatchResults hooksecurefunc(PVPCellNameMixin, "Populate", function(self, rowData) local name = rowData.name local className = rowData.className or "" local n, r = strsplit("-", name, 2) n = classColor[className]..n.."|r" if name == UnitName("player") then n = ">>> "..n.." <<<" end if r then local color local faction = rowData.faction local inArena = IsActiveBattlefieldArena() if inArena then if faction == 1 then color = "|cffffd100" else color = "|cff19ff19" end else if faction == 1 then color = "|cff00adf0" else color = "|cffff1919" end end r = color..r.."|r" n = n.."|cffffffff - |r"..r end local text = self.text text:SetText(n) end) local _VIEW local function viewChanged(view) _VIEW = view end -- GuildList local function update() _VIEW = _VIEW or GetCVar("guildRosterView") local playerArea = GetRealZoneText() local buttons = GuildRosterContainer.buttons for _, button in ipairs(buttons) do if button:IsShown() and button.online and button.guildIndex then if _VIEW == "tradeskill" then local _, _, _, headerName, _, _, _, playerName, _, _, _, zone, _, classFileName, isMobile = GetGuildTradeSkillInfo(button.guildIndex) if not headerName and playerName then local c = classColorRaw[classFileName] button.string1:SetTextColor(c.r, c.g, c.b) if not isMobile and zone == playerArea then button.string2:SetText("|cff00ff00"..zone) elseif isMobile then button.string2:SetText("|cffa5a5a5"..REMOTE_CHAT) end end else local name, rank, rankIndex, level, _, zone, _, _, _, isAway, classFileName, _, _, isMobile = GetGuildRosterInfo(button.guildIndex) name = string.gsub(name, "-.*", "") local displayedName = classColor[classFileName]..name if isMobile then if isAway == 1 then displayedName = "|TInterface\\ChatFrame\\UI-ChatIcon-ArmoryChat-AwayMobile:14:14:0:0:16:16:0:16:0:16|t"..displayedName.." |cffE7E716"..L_CHAT_AFK.."|r" elseif isAway == 2 then displayedName = "|TInterface\\ChatFrame\\UI-ChatIcon-ArmoryChat-BusyMobile:14:14:0:0:16:16:0:16:0:16|t"..displayedName.." |cffff0000"..L_CHAT_DND.."|r" else displayedName = ChatFrame_GetMobileEmbeddedTexture(0.3, 1, 0.3)..displayedName end else if isAway == 1 then displayedName = displayedName.." |cffE7E716"..L_CHAT_AFK.."|r" elseif isAway == 2 then displayedName = displayedName.." |cffff0000"..L_CHAT_DND.."|r" else displayedName = displayedName end end if _VIEW == "playerStatus" then button.string1:SetText(diffColor[level]..level) button.string2:SetText(displayedName) if not isMobile and zone == playerArea then button.string3:SetText("|cff4cff4c"..zone) elseif isMobile then button.string3:SetText("|cffa5a5a5"..REMOTE_CHAT) end elseif _VIEW == "guildStatus" then button.string1:SetText(displayedName) if rankIndex and rank then button.string2:SetText(guildRankColor[rankIndex]..rank) end elseif _VIEW == "achievement" then button.string1:SetText(diffColor[level]..level) if classFileName and name then button.string2:SetText(displayedName) end elseif _VIEW == "reputation" then button.string1:SetText(diffColor[level]..level) button.string2:SetText(displayedName) end end end end end local loaded = false hooksecurefunc("GuildFrame_LoadUI", function() if loaded then return else loaded = true hooksecurefunc("GuildRoster_SetView", viewChanged) hooksecurefunc("GuildRoster_Update", update) hooksecurefunc(GuildRosterContainer, "update", update) end end) -- CommunitiesFrame local function RefreshList(self) local playerArea = GetRealZoneText() local memberInfo = self:GetMemberInfo() if memberInfo then if memberInfo.presence == Enum.ClubMemberPresence.Offline then return end if memberInfo.zone and memberInfo.zone == playerArea then self.Zone:SetText("|cff4cff4c"..memberInfo.zone) end if memberInfo.level then self.Level:SetText(diffColor[memberInfo.level]..memberInfo.level) end if memberInfo.guildRankOrder and memberInfo.guildRank then self.Rank:SetText(guildRankColor[memberInfo.guildRankOrder]..memberInfo.guildRank) end end end local loaded = false hooksecurefunc("Communities_LoadUI", function() if loaded then return else loaded = true hooksecurefunc(CommunitiesMemberListEntryMixin, "RefreshExpandedColumns", RefreshList) end end) -- FriendsList local FRIENDS_LEVEL_TEMPLATE = FRIENDS_LEVEL_TEMPLATE:gsub("%%d", "%%s") FRIENDS_LEVEL_TEMPLATE = FRIENDS_LEVEL_TEMPLATE:gsub("%$d", "%$s") local function friendsFrame(self) local playerArea = GetRealZoneText() for i = 1, self.ScrollTarget:GetNumChildren() do local nameText, infoText local button = select(i, self.ScrollTarget:GetChildren()) if button:IsShown() then if button.buttonType == FRIENDS_BUTTON_TYPE_WOW then local info = C_FriendList.GetFriendInfoByIndex(button.id) if info.connected then nameText = classColor[info.className]..info.name.."|r, "..format(FRIENDS_LEVEL_TEMPLATE, diffColor[info.level]..info.level.."|r", info.className) if info.area == playerArea then infoText = format("|cff00ff00%s|r", info.area) end end elseif button.buttonType == FRIENDS_BUTTON_TYPE_BNET then local accountInfo = C_BattleNet.GetFriendAccountInfo(button.id) if accountInfo.gameAccountInfo.isOnline and accountInfo.gameAccountInfo.clientProgram == BNET_CLIENT_WOW then local accountName = accountInfo.accountName local characterName = accountInfo.gameAccountInfo.characterName local class = accountInfo.gameAccountInfo.className local areaName = accountInfo.gameAccountInfo.areaName if accountName and characterName and class then nameText = format(BATTLENET_NAME_FORMAT, accountName, "").." "..FRIENDS_WOW_NAME_COLOR_CODE.."("..classColor[class]..classColor[class]..characterName..FRIENDS_WOW_NAME_COLOR_CODE..")" if areaName == playerArea then infoText = format("|cff00ff00%s|r", areaName) end end end end end if nameText then button.name:SetText(nameText) end if infoText then button.info:SetText(infoText) end end end hooksecurefunc(FriendsListFrame.ScrollBox, "Update", friendsFrame)
1
0.913638
1
0.913638
game-dev
MEDIA
0.859967
game-dev
0.972533
1
0.972533
unresolved3169/Altay-Old
6,652
src/pocketmine/entity/object/ExperienceOrb.php
<?php /* * _ _ * /\ | | | * / \ | | |_ __ _ _ _ * / /\ \ | | __/ _` | | | | * / ____ \| | || (_| | |_| | * /_/ \_|_|\__\__,_|\__, | * __/ | * |___/ * * 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 3 of the License, or * (at your option) any later version. * * @author TuranicTeam * @link https://github.com/TuranicTeam/Altay * */ declare(strict_types=1); namespace pocketmine\entity\object; use pocketmine\entity\Entity; use pocketmine\entity\Human; use pocketmine\nbt\tag\ShortTag; use pocketmine\nbt\tag\IntTag; use pocketmine\Player; class ExperienceOrb extends Entity{ public const NETWORK_ID = self::XP_ORB; public const TAG_VALUE_PC = "Value"; //short public const TAG_VALUE_PE = "experience value"; //int (WTF?) /** * Max distance an orb will follow a player across. */ public const MAX_TARGET_DISTANCE = 8.0; /** * Split sizes used for dropping experience orbs. */ public const ORB_SPLIT_SIZES = [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1]; //This is indexed biggest to smallest so that we can return as soon as we found the biggest value. /** * Returns the largest size of normal XP orb that will be spawned for the specified amount of XP. Used to split XP * up into multiple orbs when an amount of XP is dropped. * * @param int $amount * * @return int */ public static function getMaxOrbSize(int $amount) : int{ foreach(self::ORB_SPLIT_SIZES as $split){ if($amount >= $split){ return $split; } } return 1; } /** * Splits the specified amount of XP into an array of acceptable XP orb sizes. * * @param int $amount * * @return int[] */ public static function splitIntoOrbSizes(int $amount) : array{ $result = []; while($amount > 0){ $size = self::getMaxOrbSize($amount); $result[] = $size; $amount -= $size; } return $result; } public $height = 0.25; public $width = 0.25; public $gravity = 0.04; public $drag = 0.02; /** * @var int * Ticker used for determining interval in which to look for new target players. */ protected $lookForTargetTime = 0; /** * @var int|null * Runtime entity ID of the player this XP orb is targeting. */ protected $targetPlayerRuntimeId = null; protected function initEntity() : void{ parent::initEntity(); $this->age = $this->namedtag->getShort("Age", 0); $value = 0; if($this->namedtag->hasTag(self::TAG_VALUE_PC, ShortTag::class)){ //PC $value = $this->namedtag->getShort(self::TAG_VALUE_PC); }elseif($this->namedtag->hasTag(self::TAG_VALUE_PE, IntTag::class)){ //PE save format $value = $this->namedtag->getInt(self::TAG_VALUE_PE); } $this->setXpValue($value); } public function saveNBT() : void{ parent::saveNBT(); $this->namedtag->setShort("Age", $this->age); $this->namedtag->setShort(self::TAG_VALUE_PC, $this->getXpValue()); $this->namedtag->setInt(self::TAG_VALUE_PE, $this->getXpValue()); } public function getXpValue() : int{ return $this->propertyManager->getInt(self::DATA_EXPERIENCE_VALUE) ?? 0; } public function setXpValue(int $amount) : void{ if($amount <= 0){ throw new \InvalidArgumentException("XP amount must be greater than 0, got $amount"); } $this->propertyManager->setInt(self::DATA_EXPERIENCE_VALUE, $amount); } public function hasTargetPlayer() : bool{ return $this->targetPlayerRuntimeId !== null; } public function getTargetPlayer() : ?Human{ if($this->targetPlayerRuntimeId === null){ return null; } $entity = $this->server->findEntity($this->targetPlayerRuntimeId, $this->level); if($entity instanceof Human){ return $entity; } return null; } public function setTargetPlayer(?Human $player) : void{ $this->targetPlayerRuntimeId = $player ? $player->getId() : null; } public function entityBaseTick(int $tickDiff = 1) : bool{ $hasUpdate = parent::entityBaseTick($tickDiff); if($this->age > 6000){ $this->flagForDespawn(); return true; } $currentTarget = $this->getTargetPlayer(); if($currentTarget !== null and (!$currentTarget->isAlive() or $currentTarget->distanceSquared($this) > self::MAX_TARGET_DISTANCE ** 2)){ $currentTarget = null; } if($this->lookForTargetTime >= 20){ if($currentTarget === null){ $this->setTargetPlayer(null); $newTarget = $this->level->getNearestEntity($this, self::MAX_TARGET_DISTANCE, Human::class); if($newTarget instanceof Human and !($newTarget instanceof Player and $newTarget->isSpectator())){ $currentTarget = $newTarget; } } $this->lookForTargetTime = 0; }else{ $this->lookForTargetTime += $tickDiff; } $this->setTargetPlayer($currentTarget); if($currentTarget !== null){ $vector = $currentTarget->subtract($this)->add(0, $currentTarget->getEyeHeight() / 2, 0)->divide(self::MAX_TARGET_DISTANCE); $distance = $vector->length(); $oneMinusDistance = (1 - $distance) ** 2; if($oneMinusDistance > 0){ $this->motion->x += $vector->x / $distance * $oneMinusDistance * 0.2; $this->motion->y += $vector->y / $distance * $oneMinusDistance * 0.2; $this->motion->z += $vector->z / $distance * $oneMinusDistance * 0.2; } if($currentTarget->canPickupXp() and $this->boundingBox->intersectsWith($currentTarget->getBoundingBox())){ $this->flagForDespawn(); $currentTarget->onPickupXp($this->getXpValue()); } } return $hasUpdate; } protected function tryChangeMovement() : void{ $this->checkObstruction($this->x, $this->y, $this->z); parent::tryChangeMovement(); } public function canBeCollidedWith(): bool{ return false; } }
1
0.610194
1
0.610194
game-dev
MEDIA
0.902769
game-dev
0.939251
1
0.939251
Baptistemontan/leptos_i18n
1,080
examples/ssr/workspace/client/src/app.rs
use crate::i18n::*; use leptos::prelude::*; #[component] #[allow(non_snake_case)] pub fn App() -> impl IntoView { leptos_meta::provide_meta_context(); view! { <I18nContextProvider> <SwitchLang /> <Counter /> </I18nContextProvider> } } #[component] #[allow(non_snake_case)] pub fn SwitchLang() -> impl IntoView { let i18n = use_i18n(); let on_switch = move |_| { let new_lang = match i18n.get_locale() { Locale::en => Locale::fr, Locale::fr => Locale::en, }; i18n.set_locale(new_lang); }; view! { <button on:click=on_switch>{t!(i18n, click_to_change_lang)}</button> } } #[component] #[allow(non_snake_case)] fn Counter() -> impl IntoView { let i18n = use_i18n(); let (counter, set_counter) = signal(0); let inc = move |_| set_counter.update(|count| *count += 1); let count = move || counter.get(); view! { <p>{t!(i18n, click_count, count)}</p> <button on:click=inc>{t!(i18n, click_to_inc)}</button> } }
1
0.916834
1
0.916834
game-dev
MEDIA
0.218626
game-dev
0.821652
1
0.821652
GPUOpen-Tools/compressonator
31,016
cmp_compressonatorlib/dxtc/codec_dxtc_alpha.cpp
//=============================================================================== // Copyright (c) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. // Copyright (c) 2004-2006 ATI Technologies Inc. //=============================================================================== // // 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. // // // File Name: Codec_DXTC.cpp // Description: implementation of the CCodec_DXTC class // ////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "codec_dxtc.h" #include "compressonatorxcodec.h" #include "dxtc_v11_compress.h" #include "common_def.h" #ifdef _WIN32 #pragma warning(disable : 4201) #endif CodecError CCodec_DXTC::CompressAlphaBlock(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { BYTE nEndpoints[2][2]; BYTE nIndices[2][BLOCK_SIZE_4X4]; float fError8 = CompBlock1X(alphaBlock, BLOCK_SIZE_4X4, nEndpoints[0], nIndices[0], 8, false, m_bUseSSE2, 8, 0, true); float fError6 = (fError8 == 0.f) ? FLT_MAX : CompBlock1X(alphaBlock, BLOCK_SIZE_4X4, nEndpoints[1], nIndices[1], 6, true, m_bUseSSE2, 8, 0, true); if (fError8 <= fError6) EncodeAlphaBlock(compressedBlock, nEndpoints[0], nIndices[0]); else EncodeAlphaBlock(compressedBlock, nEndpoints[1], nIndices[1]); return CE_OK; } // //========================== CMP_CORE Code =================================== // #define CMP_QUALITY2 0.601f // #ifndef MAX_ERROR // #define MAX_ERROR 128000.f // #endif // #ifndef GBL_SCH_STEP // #define GBL_SCH_STEP_MXS 0.018f // #define GBL_SCH_EXT_MXS 0.1f // #define LCL_SCH_STEP_MXS 0.6f // #define GBL_SCH_STEP_MXQ 0.0175f // #define GBL_SCH_EXT_MXQ 0.154f // #define LCL_SCH_STEP_MXQ 0.45f // // #define GBL_SCH_STEP GBL_SCH_STEP_MXS // #define GBL_SCH_EXT GBL_SCH_EXT_MXS // #define LCL_SCH_STEP LCL_SCH_STEP_MXS // #endif // // #define SCH_STPS 3 // number of search steps to make at each end of interval // static CMP_CONSTANT CGU_FLOAT sMvF[] = {0.f, -1.f, 1.f, -2.f, 2.f, -3.f, 3.f, -4.f, 4.f, -5.f, 5.f, -6.f, 6.f, -7.f, 7.f, -8.f, 8.f}; // #define MAX_POINTS 16 // #define NUM_ENDPOINTS 2 // #define CMP_ALPHA_RAMP 8 // // // static CGU_INT QSortFCmp(const void* Elem1, const void* Elem2) // { // CGU_INT ret = 0; // // if (*(CGU_FLOAT*)Elem1 < *(CGU_FLOAT*)Elem2) // ret = -1; // else if (*(CGU_FLOAT*)Elem1 > *(CGU_FLOAT*)Elem2) // ret = 1; // return ret; // } // // static CGU_FLOAT cmp_getRampError(CGU_FLOAT _Blk[BLOCK_SIZE_4X4], // CGU_FLOAT _Rpt[BLOCK_SIZE_4X4], // CGU_FLOAT _maxerror, // CGU_FLOAT _min_ex, // CGU_FLOAT _max_ex, // CGU_INT _NmbrClrs) // { // Max 16 // CGU_INT i; // CGU_FLOAT error = 0; // const CGU_FLOAT step = (_max_ex - _min_ex) / 7; // (CGU_FLOAT)(dwNumPoints - 1); // const CGU_FLOAT step_h = step * 0.5f; // const CGU_FLOAT rstep = 1.0f / step; // // for (i = 0; i < _NmbrClrs; i++) // { // CGU_FLOAT v; // // Work out which value in the block this select // CGU_FLOAT del; // // if ((del = _Blk[i] - _min_ex) <= 0) // v = _min_ex; // else if (_Blk[i] - _max_ex >= 0) // v = _max_ex; // else // v = (floor((del + step_h) * rstep) * step) + _min_ex; // // // And accumulate the error // CGU_FLOAT del2 = (_Blk[i] - v); // error += del2 * del2 * _Rpt[i]; // // // if we've already lost to the previous step bail out // if (_maxerror < error) // { // error = _maxerror; // break; // } // } // return error; // } // // // static CGU_FLOAT cmp_linearBlockRefine(CGU_FLOAT _Blk[BLOCK_SIZE_4X4], // CGU_FLOAT _Rpt[BLOCK_SIZE_4X4], // CGU_FLOAT _MaxError, // CMP_INOUT CGU_FLOAT CMP_PTRINOUT _min_ex, // CMP_INOUT CGU_FLOAT CMP_PTRINOUT _max_ex, // CGU_FLOAT _m_step, // CGU_FLOAT _min_bnd, // CGU_FLOAT _max_bnd, // CGU_INT _NmbrClrs) // { // // Start out assuming our endpoints are the min and max values we've // // determined // // // Attempt a (simple) progressive refinement step to reduce noise in the // // output image by trying to find a better overall match for the endpoints. // // CGU_FLOAT maxerror = _MaxError; // CGU_FLOAT min_ex = CMP_PTRINOUT _min_ex; // CGU_FLOAT max_ex = CMP_PTRINOUT _max_ex; // // CGU_INT mode, bestmode; // // do // { // CGU_FLOAT cr_min0 = min_ex; // CGU_FLOAT cr_max0 = max_ex; // for (bestmode = -1, mode = 0; mode < SCH_STPS * SCH_STPS; mode++) // { // // check each move (see sStep for direction) // CGU_FLOAT cr_min = min_ex + _m_step * sMvF[mode / SCH_STPS]; // CGU_FLOAT cr_max = max_ex + _m_step * sMvF[mode % SCH_STPS]; // // cr_min = max(cr_min, _min_bnd); // cr_max = min(cr_max, _max_bnd); // // CGU_FLOAT error; // error = cmp_getRampError(_Blk, _Rpt, maxerror, cr_min, cr_max, _NmbrClrs); // // if (error < maxerror) // { // maxerror = error; // bestmode = mode; // cr_min0 = cr_min; // cr_max0 = cr_max; // } // } // // if (bestmode != -1) // { // // make move (see sStep for direction) // min_ex = cr_min0; // max_ex = cr_max0; // } // } while (bestmode != -1); // // CMP_PTRINOUT _min_ex = min_ex; // CMP_PTRINOUT _max_ex = max_ex; // // return maxerror; // } // // static CGU_Vec2i cmp_getLinearEndPoints(CGU_FLOAT _Blk[BLOCK_SIZE_4X4], CMP_IN CGU_FLOAT fquality, CMP_IN CGU_BOOL isSigned) // { // CGU_UINT32 i; // CGU_Vec2i cmpMinMax; // // CGU_FLOAT scalePts = 1.0f; //isSigned ? 128.0f : 255.0f; // CGU_FLOAT scaleOffset = isSigned ? 0.25f : 0.5f; // // //================================================================ // // Bounding Box // // lowest quality calculation to get min and max value to use // //================================================================ // if (fquality < CMP_QUALITY2) // { // cmpMinMax.x = _Blk[0]; // cmpMinMax.y = _Blk[0]; // for (i = 1; i < BLOCK_SIZE_4X4; ++i) // { // cmpMinMax.x = min(cmpMinMax.x, _Blk[i]); // cmpMinMax.y = max(cmpMinMax.y, _Blk[i]); // } // return cmpMinMax; // } // // //================================================================ // // Do more calculations to get the best min and max values to use // //================================================================ // CGU_FLOAT Ramp[2]; // // // Result defaults for SNORM or UNORM // Ramp[0] = isSigned ? -1.0f : 0.0f; // Ramp[1] = 1.0f; // // CGU_FLOAT afUniqueValues[BLOCK_SIZE_4X4]; // CGU_FLOAT afValueRepeats[BLOCK_SIZE_4X4]; // for (i = 0; i < BLOCK_SIZE_4X4; i++) // afUniqueValues[i] = afValueRepeats[i] = 0.f; // // // For each unique value we compute the number of it appearances. // CGU_FLOAT fBlk[BLOCK_SIZE_4X4]; // // memcpy(fBlk, _Blk, BLOCK_SIZE_4X4 * sizeof(CGU_FLOAT)); // qsort((void*)fBlk, (size_t)BLOCK_SIZE_4X4, sizeof(CGU_FLOAT), QSortFCmp); // // CGU_FLOAT new_p = -2.0f; // // CGU_UINT32 dwUniqueValues = 0; // afUniqueValues[0] = 0.0f; // CGU_BOOL requiresCalculation = true; // // { // // Ramp not fixed // for (i = 0; i < BLOCK_SIZE_4X4; i++) // { // if (new_p != fBlk[i]) // { // afUniqueValues[dwUniqueValues] = new_p = fBlk[i]; // afValueRepeats[dwUniqueValues] = 1.f; // dwUniqueValues++; // } // else if (dwUniqueValues) // afValueRepeats[dwUniqueValues - 1] += 1.f; // } // // // if number of unique colors is less or eq 2, we've done // if (dwUniqueValues <= 2) // { // Ramp[0] = floor(afUniqueValues[0] * scalePts + scaleOffset); // if (dwUniqueValues == 1) // Ramp[1] = Ramp[0] + 1.f; // else // Ramp[1] = floor(afUniqueValues[1] * scalePts + scaleOffset); // requiresCalculation = false; // } // } // Ramp not fixed // // if (requiresCalculation) // { // CGU_FLOAT min_ex = afUniqueValues[0]; // CGU_FLOAT max_ex = afUniqueValues[dwUniqueValues - 1]; // CGU_FLOAT min_bnd = 0, max_bnd = 1.; // CGU_FLOAT min_r = min_ex, max_r = max_ex; // CGU_FLOAT gbl_l = 0, gbl_r = 0; // CGU_FLOAT cntr = (min_r + max_r) / 2; // // CGU_FLOAT gbl_err = MAX_ERROR; // // Trying to avoid unnecessary calculations. Heuristics: after some analisis // // it appears that in integer case, if the input interval not more then 48 // // we won't get much better // bool wantsSearch = !((max_ex - min_ex) <= (48.f / scalePts)); // // if (wantsSearch) // { // // Search. // // 1. take the vicinities of both low and high bound of the input // // interval. // // 2. setup some search step // // 3. find the new low and high bound which provides an (sub) optimal // // (infinite precision) clusterization. // CGU_FLOAT gbl_llb = (min_bnd > min_r - GBL_SCH_EXT) ? min_bnd : min_r - GBL_SCH_EXT; // CGU_FLOAT gbl_rrb = (max_bnd < max_r + GBL_SCH_EXT) ? max_bnd : max_r + GBL_SCH_EXT; // CGU_FLOAT gbl_lrb = (cntr < min_r + GBL_SCH_EXT) ? cntr : min_r + GBL_SCH_EXT; // CGU_FLOAT gbl_rlb = (cntr > max_r - GBL_SCH_EXT) ? cntr : max_r - GBL_SCH_EXT; // // for (CGU_FLOAT step_l = gbl_llb; step_l < gbl_lrb; step_l += GBL_SCH_STEP) // { // for (CGU_FLOAT step_r = gbl_rrb; gbl_rlb <= step_r; step_r -= GBL_SCH_STEP) // { // CGU_FLOAT sch_err; // // an sse version is avaiable // sch_err = cmp_getRampError(afUniqueValues, afValueRepeats, gbl_err, step_l, step_r, dwUniqueValues); // if (sch_err < gbl_err) // { // gbl_err = sch_err; // gbl_l = step_l; // gbl_r = step_r; // } // } // } // // min_r = gbl_l; // max_r = gbl_r; // } // want search // // // This is a refinement call. The function tries to make several small // // stretches or squashes to minimize quantization error. // CGU_FLOAT m_step = LCL_SCH_STEP / scalePts; // cmp_linearBlockRefine(afUniqueValues, afValueRepeats, gbl_err, CMP_REFINOUT min_r, CMP_REFINOUT max_r, m_step, min_bnd, max_bnd, dwUniqueValues); // // min_ex = min_r; // max_ex = max_r; // max_ex *= scalePts; // min_ex *= scalePts; // // Ramp[0] = floor(min_ex + scaleOffset); // Ramp[1] = floor(max_ex + scaleOffset); // } // // // Ensure that the two endpoints are not the same // // This is legal but serves no need & can break some optimizations in the compressor // if (Ramp[0] == Ramp[1]) // { // if (Ramp[1] < scalePts) // Ramp[1] = Ramp[1] + .1f; // else if (Ramp[1] > 0.0f) // Ramp[1] = Ramp[1] - .1f; // } // // cmpMinMax.x = Ramp[0]; // cmpMinMax.y = Ramp[1]; // // return cmpMinMax; // } static CGU_INT8 cmp_SNormFloatToSInt(CGU_FLOAT fsnorm) { if (isnan(fsnorm)) fsnorm = 0; else if (fsnorm > 1) fsnorm = 1; // Clamp to 1 else if (fsnorm < -1) fsnorm = -1; // Clamp to -1 fsnorm = fsnorm * 127U; // shift round up or down if (fsnorm >= 0) fsnorm += .5f; else fsnorm -= .5f; CGU_INT8 res = static_cast<CGU_INT8>(fsnorm); return (res); } static CGU_Vec2f cmp_OptimizeEndPoints(CGU_FLOAT* pPoints, CGU_INT8 cSteps, CGU_BOOL isSigned) { CGU_Vec2f fendpoints; CGU_FLOAT MAX_VALUE = 1.0f; CGU_FLOAT MIN_VALUE = isSigned ? -1.0f : 0.0f; // Find Min and Max points, as starting point CGU_FLOAT fX = MAX_VALUE; CGU_FLOAT fY = MIN_VALUE; if (8 == cSteps) { for (CGU_INT8 iPoint = 0; iPoint < BLOCK_SIZE_4X4; iPoint++) { if (pPoints[iPoint] < fX) fX = pPoints[iPoint]; if (pPoints[iPoint] > fY) fY = pPoints[iPoint]; } } else { for (CGU_INT8 iPoint = 0; iPoint < BLOCK_SIZE_4X4; iPoint++) { if (pPoints[iPoint] < fX && pPoints[iPoint] > MIN_VALUE) fX = pPoints[iPoint]; if (pPoints[iPoint] > fY && pPoints[iPoint] < MAX_VALUE) fY = pPoints[iPoint]; } if (fX == fY) { fY = MAX_VALUE; } } //=================== // Use Newton Method //=================== CGU_FLOAT cStepsDiv = static_cast<CGU_FLOAT>(cSteps - 1); CGU_FLOAT pSteps[8]; CGU_FLOAT fc; CGU_FLOAT fd; for (CGU_UINT8 iIteration = 0; iIteration < 8; iIteration++) { // reach minimum threashold break if ((fY - fX) < (1.0f / 256.0f)) break; CGU_FLOAT fScale = cStepsDiv / (fY - fX); // Calculate new steps for (CGU_INT8 iStep = 0; iStep < cSteps; iStep++) { fc = (cStepsDiv - (CGU_FLOAT)iStep) / cStepsDiv; fd = (CGU_FLOAT)iStep / cStepsDiv; pSteps[iStep] = fc * fX + fd * fY; } if (6 == cSteps) { pSteps[6] = MIN_VALUE; pSteps[7] = MAX_VALUE; } // Evaluate function, and derivatives CGU_FLOAT dX = 0.0f; CGU_FLOAT dY = 0.0f; CGU_FLOAT d2X = 0.0f; CGU_FLOAT d2Y = 0.0f; for (CGU_UINT8 iPoint = 0; iPoint < BLOCK_SIZE_4X4; iPoint++) { float fDot = (pPoints[iPoint] - fX) * fScale; CGU_INT8 iStep; if (fDot <= 0.0f) { iStep = ((6 == cSteps) && (pPoints[iPoint] <= (fX + MIN_VALUE) * 0.5f)) ? 6u : 0u; } else if (fDot >= cStepsDiv) { iStep = ((6 == cSteps) && (pPoints[iPoint] >= (fY + MAX_VALUE) * 0.5f)) ? 7u : (cSteps - 1); } else { iStep = CGU_INT8(fDot + 0.5f); } // steps to improve quality if (iStep < cSteps) { fc = (cStepsDiv - (CGU_FLOAT)iStep) / cStepsDiv; fd = (CGU_FLOAT)iStep / cStepsDiv; CGU_FLOAT fDiff = pSteps[iStep] - pPoints[iPoint]; dX += fc * fDiff; d2X += fc * fc; dY += fd * fDiff; d2Y += fd * fd; } } // Move endpoints if (d2X > 0.0f) fX -= dX / d2X; if (d2Y > 0.0f) fY -= dY / d2Y; if (fX > fY) { float f = fX; fX = fY; fY = f; } if ((dX * dX < (1.0f / 64.0f)) && (dY * dY < (1.0f / 64.0f))) break; } fendpoints.x = (fX < MIN_VALUE) ? MIN_VALUE : (fX > MAX_VALUE) ? MAX_VALUE : fX; fendpoints.y = (fY < MIN_VALUE) ? MIN_VALUE : (fY > MAX_VALUE) ? MAX_VALUE : fY; return fendpoints; } static CGU_Vec2i CMP_FindEndpointsAlphaBlockSnorm(CGU_FLOAT alphaBlockSnorm[]) { //================================================================ // Bounding Box // lowest quality calculation to get min and max value to use //================================================================ CGU_Vec2f cmpMinMax; cmpMinMax.x = alphaBlockSnorm[0]; cmpMinMax.y = alphaBlockSnorm[0]; for (CGU_UINT8 i = 0; i < BLOCK_SIZE_4X4; ++i) { if (alphaBlockSnorm[i] < cmpMinMax.x) { cmpMinMax.x = alphaBlockSnorm[i]; } else if (alphaBlockSnorm[i] > cmpMinMax.y) { cmpMinMax.y = alphaBlockSnorm[i]; } } CGU_Vec2i endpoints; CGU_Vec2f fendpoints; // Are we done for lowest quality setting! // CGU_FLOAT fquality = 1.0f; // // if (fquality < CMP_QUALITY2) { // endpoints.x = (CGU_INT8)(cmpMinMax.x); // endpoints.y = (CGU_INT8)(cmpMinMax.y); // return endpoints; // } //================================================================ // Do more calculations to get the best min and max values to use //================================================================ if ((-1.0f == cmpMinMax.x || 1.0f == cmpMinMax.y)) { fendpoints = cmp_OptimizeEndPoints(alphaBlockSnorm, 6, true); endpoints.x = cmp_SNormFloatToSInt(fendpoints.x); endpoints.y = cmp_SNormFloatToSInt(fendpoints.y); } else { fendpoints = cmp_OptimizeEndPoints(alphaBlockSnorm, 8, true); endpoints.x = cmp_SNormFloatToSInt(fendpoints.y); endpoints.y = cmp_SNormFloatToSInt(fendpoints.x); } return endpoints; } //============================================================================= CodecError CCodec_DXTC::CompressAlphaBlockSNorm(CMP_FLOAT alphaBlockSnorm[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { union { CMP_DWORD compressedBlock[2]; struct { int8_t red_0; int8_t red_1; uint8_t indices[6]; }; uint64_t data; } BC4_Snorm_block; BC4_Snorm_block.data = 0LL; CGU_Vec2i reds; reds = CMP_FindEndpointsAlphaBlockSnorm(alphaBlockSnorm); BC4_Snorm_block.red_0 = reds.x & 0xFF; BC4_Snorm_block.red_1 = reds.y & 0xFF; // check low end boundaries if (BC4_Snorm_block.red_0 == -128) BC4_Snorm_block.red_0 = -127; if (BC4_Snorm_block.red_1 == -128) BC4_Snorm_block.red_1 = -127; // Normalize signed int -128..127 to float -1..1 CGU_Vec2f alphaMinMax; alphaMinMax.x = CGU_FLOAT(BC4_Snorm_block.red_0) / 127.0f; alphaMinMax.y = CGU_FLOAT(BC4_Snorm_block.red_1) / 127.0f; BC4_Snorm_block.data = cmp_getBlockPackedIndicesSNorm(alphaMinMax, alphaBlockSnorm, BC4_Snorm_block.data); compressedBlock[0] = BC4_Snorm_block.compressedBlock[0]; compressedBlock[1] = BC4_Snorm_block.compressedBlock[1]; return CE_OK; } CodecError CCodec_DXTC::CompressAlphaBlock_Fast(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { #ifdef _WIN64 CompressAlphaBlock(alphaBlock, compressedBlock); #else // !_WIN64 DXTCV11CompressAlphaBlock(alphaBlock, compressedBlock); #endif return CE_OK; } CodecError CCodec_DXTC::CompressAlphaBlock(CODECFLOAT alphaBlock[BLOCK_SIZE_4X4X4], CMP_DWORD compressedBlock[2]) { BYTE nEndpoints[2][2]; BYTE nIndices[2][BLOCK_SIZE_4X4]; float fError8 = CompBlock1X(alphaBlock, BLOCK_SIZE_4X4, nEndpoints[0], nIndices[0], 8, false, m_bUseSSE2, 8, 0, true); float fError6 = (fError8 == 0.f) ? FLT_MAX : CompBlock1X(alphaBlock, BLOCK_SIZE_4X4, nEndpoints[1], nIndices[1], 6, true, m_bUseSSE2, 8, 0, true); if (fError8 <= fError6) EncodeAlphaBlock(compressedBlock, nEndpoints[0], nIndices[0]); else EncodeAlphaBlock(compressedBlock, nEndpoints[1], nIndices[1]); return CE_OK; } void CCodec_DXTC::EncodeAlphaBlock(CMP_DWORD compressedBlock[2], BYTE nEndpoints[2], BYTE nIndices[BLOCK_SIZE_4X4]) { compressedBlock[0] = ((int)nEndpoints[0]) | (((int)nEndpoints[1]) << 8); compressedBlock[1] = 0; for (int i = 0; i < BLOCK_SIZE_4X4; i++) { if (i < 5) compressedBlock[0] |= (nIndices[i] & 0x7) << (16 + (i * 3)); else if (i > 5) compressedBlock[1] |= (nIndices[i] & 0x7) << (2 + (i - 6) * 3); else { compressedBlock[0] |= (nIndices[i] & 0x1) << 31; compressedBlock[1] |= (nIndices[i] & 0x6) >> 1; } } } // // This function decompresses a block // void CCodec_DXTC::DecompressAlphaBlock(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { CMP_BYTE alpha[8]; GetCompressedAlphaRamp(alpha, compressedBlock); for (int i = 0; i < BLOCK_SIZE_4X4; i++) { CMP_DWORD index; if (i < 5) index = (compressedBlock[0] & (0x7 << (16 + (i * 3)))) >> (16 + (i * 3)); else if (i > 5) index = (compressedBlock[1] & (0x7 << (2 + (i - 6) * 3))) >> (2 + (i - 6) * 3); else { index = (compressedBlock[0] & 0x80000000) >> 31; index |= (compressedBlock[1] & 0x3) << 1; } alphaBlock[i] = alpha[index]; } } // // This function decompresses a signed block // void CCodec_DXTC::DecompressAlphaBlockInt8(CMP_SBYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { CMP_SBYTE alpha[8]; GetCompressedAlphaRampS(alpha, compressedBlock); for (int i = 0; i < BLOCK_SIZE_4X4; i++) { CMP_DWORD index; if (i < 5) index = (compressedBlock[0] & (0x7 << (16 + (i * 3)))) >> (16 + (i * 3)); else if (i > 5) index = (compressedBlock[1] & (0x7 << (2 + (i - 6) * 3))) >> (2 + (i - 6) * 3); else { index = (compressedBlock[0] & 0x80000000) >> 31; index |= (compressedBlock[1] & 0x3) << 1; } alphaBlock[i] = alpha[index]; } } void CCodec_DXTC::DecompressAlphaBlock(CODECFLOAT alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { CODECFLOAT alpha[8]; GetCompressedAlphaRamp(alpha, compressedBlock); for (int i = 0; i < BLOCK_SIZE_4X4; i++) { CMP_DWORD index; if (i < 5) index = (compressedBlock[0] & (0x7 << (16 + (i * 3)))) >> (16 + (i * 3)); else if (i > 5) index = (compressedBlock[1] & (0x7 << (2 + (i - 6) * 3))) >> (2 + (i - 6) * 3); else { index = (compressedBlock[0] & 0x80000000) >> 31; index |= (compressedBlock[1] & 0x3) << 1; } alphaBlock[i] = alpha[index]; } } #define EXPLICIT_ALPHA_PIXEL_MASK 0xf #define EXPLICIT_ALPHA_PIXEL_BPP 4 CodecError CCodec_DXTC::CompressExplicitAlphaBlock(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { DXTCV11CompressExplicitAlphaBlock(alphaBlock, compressedBlock); return CE_OK; } CodecError CCodec_DXTC::CompressExplicitAlphaBlock_Fast(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { // Should remove or update this: DXTCV11CompressExplicitAlphaBlockMMX(alphaBlock, compressedBlock); CompressExplicitAlphaBlock(alphaBlock, compressedBlock); return CE_OK; } CodecError CCodec_DXTC::CompressExplicitAlphaBlock(CODECFLOAT alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { compressedBlock[0] = compressedBlock[1] = 0; for (int i = 0; i < 16; i++) { int nBlock = i < 8 ? 0 : 1; CMP_BYTE cAlpha = CONVERT_FLOAT_TO_BYTE(alphaBlock[i]); cAlpha = (CMP_BYTE)((cAlpha + ((cAlpha >> EXPLICIT_ALPHA_PIXEL_BPP) < 0x8 ? 7 : 8) - (cAlpha >> EXPLICIT_ALPHA_PIXEL_BPP)) >> EXPLICIT_ALPHA_PIXEL_BPP); if (cAlpha > EXPLICIT_ALPHA_PIXEL_MASK) cAlpha = EXPLICIT_ALPHA_PIXEL_MASK; compressedBlock[nBlock] |= (cAlpha << ((i % 8) * EXPLICIT_ALPHA_PIXEL_BPP)); } return CE_OK; } // // This function decompresses an explicit alpha block (DXT3) // void CCodec_DXTC::DecompressExplicitAlphaBlock(CMP_BYTE alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { for (int i = 0; i < 16; i++) { int nBlock = i < 8 ? 0 : 1; CMP_BYTE cAlpha = (CMP_BYTE)((compressedBlock[nBlock] >> ((i % 8) * EXPLICIT_ALPHA_PIXEL_BPP)) & EXPLICIT_ALPHA_PIXEL_MASK); alphaBlock[i] = (CMP_BYTE)((cAlpha << EXPLICIT_ALPHA_PIXEL_BPP) | cAlpha); } } void CCodec_DXTC::DecompressExplicitAlphaBlock(CODECFLOAT alphaBlock[BLOCK_SIZE_4X4], CMP_DWORD compressedBlock[2]) { for (int i = 0; i < 16; i++) { int nBlock = i < 8 ? 0 : 1; CMP_BYTE cAlpha = (CMP_BYTE)((compressedBlock[nBlock] >> ((i % 8) * EXPLICIT_ALPHA_PIXEL_BPP)) & EXPLICIT_ALPHA_PIXEL_MASK); alphaBlock[i] = CONVERT_BYTE_TO_FLOAT((cAlpha << EXPLICIT_ALPHA_PIXEL_BPP) | cAlpha); } } void CCodec_DXTC::GetCompressedAlphaRamp(CMP_BYTE alpha[8], CMP_DWORD compressedBlock[2]) { alpha[0] = (CMP_BYTE)(compressedBlock[0] & 0xff); alpha[1] = (CMP_BYTE)((compressedBlock[0] >> 8) & 0xff); if (alpha[0] > alpha[1]) { // 8-alpha block: derive the other six alphas. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = static_cast<CMP_BYTE>((6 * alpha[0] + 1 * alpha[1] + 3) / 7); // bit code 010 alpha[3] = static_cast<CMP_BYTE>((5 * alpha[0] + 2 * alpha[1] + 3) / 7); // bit code 011 alpha[4] = static_cast<CMP_BYTE>((4 * alpha[0] + 3 * alpha[1] + 3) / 7); // bit code 100 alpha[5] = static_cast<CMP_BYTE>((3 * alpha[0] + 4 * alpha[1] + 3) / 7); // bit code 101 alpha[6] = static_cast<CMP_BYTE>((2 * alpha[0] + 5 * alpha[1] + 3) / 7); // bit code 110 alpha[7] = static_cast<CMP_BYTE>((1 * alpha[0] + 6 * alpha[1] + 3) / 7); // bit code 111 } else { // 6-alpha block. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = static_cast<CMP_BYTE>((4 * alpha[0] + 1 * alpha[1] + 2) / 5); // Bit code 010 alpha[3] = static_cast<CMP_BYTE>((3 * alpha[0] + 2 * alpha[1] + 2) / 5); // Bit code 011 alpha[4] = static_cast<CMP_BYTE>((2 * alpha[0] + 3 * alpha[1] + 2) / 5); // Bit code 100 alpha[5] = static_cast<CMP_BYTE>((1 * alpha[0] + 4 * alpha[1] + 2) / 5); // Bit code 101 alpha[6] = 0; // Bit code 110 alpha[7] = 255; // Bit code 111 } } void CCodec_DXTC::GetCompressedAlphaRamp(CODECFLOAT alpha[8], CMP_DWORD compressedBlock[2]) { alpha[0] = CONVERT_BYTE_TO_FLOAT(compressedBlock[0] & 0xff); alpha[1] = CONVERT_BYTE_TO_FLOAT((compressedBlock[0] >> 8) & 0xff); if (alpha[0] > alpha[1]) { // 8-alpha block: derive the other six alphas. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = (6 * alpha[0] + 1 * alpha[1]) / 7; // bit code 010 alpha[3] = (5 * alpha[0] + 2 * alpha[1]) / 7; // bit code 011 alpha[4] = (4 * alpha[0] + 3 * alpha[1]) / 7; // bit code 100 alpha[5] = (3 * alpha[0] + 4 * alpha[1]) / 7; // bit code 101 alpha[6] = (2 * alpha[0] + 5 * alpha[1]) / 7; // bit code 110 alpha[7] = (1 * alpha[0] + 6 * alpha[1]) / 7; // bit code 111 } else { // 6-alpha block. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = (4 * alpha[0] + 1 * alpha[1]) / 5; // Bit code 010 alpha[3] = (3 * alpha[0] + 2 * alpha[1]) / 5; // Bit code 011 alpha[4] = (2 * alpha[0] + 3 * alpha[1]) / 5; // Bit code 100 alpha[5] = (1 * alpha[0] + 4 * alpha[1]) / 5; // Bit code 101 alpha[6] = 0; // Bit code 110 alpha[7] = 1.0f; // Bit code 111 } } void CCodec_DXTC::GetCompressedAlphaRampS(CMP_SBYTE alpha[8], CMP_DWORD compressedBlock[2]) { alpha[0] = (CMP_SBYTE)(compressedBlock[0] & 0xff); alpha[1] = (CMP_SBYTE)((compressedBlock[0] >> 8) & 0xff); if (alpha[0] > alpha[1]) { // 8-alpha block: derive the other six alphas. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = static_cast<CMP_SBYTE>((6 * alpha[0] + 1 * alpha[1] + 3) / 7); // bit code 010 alpha[3] = static_cast<CMP_SBYTE>((5 * alpha[0] + 2 * alpha[1] + 3) / 7); // bit code 011 alpha[4] = static_cast<CMP_SBYTE>((4 * alpha[0] + 3 * alpha[1] + 3) / 7); // bit code 100 alpha[5] = static_cast<CMP_SBYTE>((3 * alpha[0] + 4 * alpha[1] + 3) / 7); // bit code 101 alpha[6] = static_cast<CMP_SBYTE>((2 * alpha[0] + 5 * alpha[1] + 3) / 7); // bit code 110 alpha[7] = static_cast<CMP_SBYTE>((1 * alpha[0] + 6 * alpha[1] + 3) / 7); // bit code 111 } else { // 6-alpha block. // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated. alpha[2] = static_cast<CMP_SBYTE>((4 * alpha[0] + 1 * alpha[1] + 2) / 5); // Bit code 010 alpha[3] = static_cast<CMP_SBYTE>((3 * alpha[0] + 2 * alpha[1] + 2) / 5); // Bit code 011 alpha[4] = static_cast<CMP_SBYTE>((2 * alpha[0] + 3 * alpha[1] + 2) / 5); // Bit code 100 alpha[5] = static_cast<CMP_SBYTE>((1 * alpha[0] + 4 * alpha[1] + 2) / 5); // Bit code 101 alpha[6] = -127; // Bit code 110 alpha[7] = 127; // Bit code 111 } }
1
0.955105
1
0.955105
game-dev
MEDIA
0.280667
game-dev
0.872912
1
0.872912
KettleFoundation/Kettle
4,953
src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java
package org.bukkit.craftbukkit.inventory; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import net.minecraft.nbt.NBTTagCompound; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import java.util.HashMap; import java.util.Map; @DelegateDeserialization(SerializableMeta.class) class CraftMetaEnchantedBook extends CraftMetaItem implements EnchantmentStorageMeta { static final ItemMetaKey STORED_ENCHANTMENTS = new ItemMetaKey("StoredEnchantments", "stored-enchants"); private Map<Enchantment, Integer> enchantments; CraftMetaEnchantedBook(CraftMetaItem meta) { super(meta); if (!(meta instanceof CraftMetaEnchantedBook)) { return; } CraftMetaEnchantedBook that = (CraftMetaEnchantedBook) meta; if (that.hasEnchants()) { this.enchantments = new HashMap<Enchantment, Integer>(that.enchantments); } } CraftMetaEnchantedBook(NBTTagCompound tag) { super(tag); if (!tag.hasKey(STORED_ENCHANTMENTS.NBT)) { return; } enchantments = buildEnchantments(tag, STORED_ENCHANTMENTS); } CraftMetaEnchantedBook(Map<String, Object> map) { super(map); enchantments = buildEnchantments(map, STORED_ENCHANTMENTS); } @Override void applyToItem(NBTTagCompound itemTag) { super.applyToItem(itemTag); applyEnchantments(enchantments, itemTag, STORED_ENCHANTMENTS); } @Override boolean applicableTo(Material type) { switch (type) { case ENCHANTED_BOOK: return true; default: return false; } } @Override boolean isEmpty() { return super.isEmpty() && isEnchantedEmpty(); } @Override boolean equalsCommon(CraftMetaItem meta) { if (!super.equalsCommon(meta)) { return false; } if (meta instanceof CraftMetaEnchantedBook) { CraftMetaEnchantedBook that = (CraftMetaEnchantedBook) meta; return (hasStoredEnchants() ? that.hasStoredEnchants() && this.enchantments.equals(that.enchantments) : !that.hasStoredEnchants()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { return super.notUncommon(meta) && (meta instanceof CraftMetaEnchantedBook || isEnchantedEmpty()); } @Override int applyHash() { final int original; int hash = original = super.applyHash(); if (hasStoredEnchants()) { hash = 61 * hash + enchantments.hashCode(); } return original != hash ? CraftMetaEnchantedBook.class.hashCode() ^ hash : hash; } @Override public CraftMetaEnchantedBook clone() { CraftMetaEnchantedBook meta = (CraftMetaEnchantedBook) super.clone(); if (this.enchantments != null) { meta.enchantments = new HashMap<Enchantment, Integer>(this.enchantments); } return meta; } @Override Builder<String, Object> serialize(Builder<String, Object> builder) { super.serialize(builder); serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS); return builder; } boolean isEnchantedEmpty() { return !hasStoredEnchants(); } public boolean hasStoredEnchant(Enchantment ench) { return hasStoredEnchants() && enchantments.containsKey(ench); } public int getStoredEnchantLevel(Enchantment ench) { Integer level = hasStoredEnchants() ? enchantments.get(ench) : null; if (level == null) { return 0; } return level; } public Map<Enchantment, Integer> getStoredEnchants() { return hasStoredEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.<Enchantment, Integer>of(); } public boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { if (enchantments == null) { enchantments = new HashMap<Enchantment, Integer>(4); } if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { Integer old = enchantments.put(ench, level); return old == null || old != level; } return false; } public boolean removeStoredEnchant(Enchantment ench) { return hasStoredEnchants() && enchantments.remove(ench) != null; } public boolean hasStoredEnchants() { return !(enchantments == null || enchantments.isEmpty()); } public boolean hasConflictingStoredEnchant(Enchantment ench) { return checkConflictingEnchants(enchantments, ench); } }
1
0.856634
1
0.856634
game-dev
MEDIA
0.954175
game-dev
0.872576
1
0.872576
CobaltWolf/Bluedog-Design-Bureau
2,502
Gamedata/Bluedog_DB/Parts/Gemini/bluedog_BigG_CylindricalSM_EquipmentModule.cfg
PART { name = bluedog_BigG_CylindricalSM_EquipmentModule module = Part author = CobaltWolf MODEL { model = Bluedog_DB/Parts/Gemini/bluedog_BigG_CylindricalSM_EquipmentModule } rescaleFactor = 1 node_stack_top = 0.0, 0.79257, 0.0, 0.0, 1.0, 0.0 node_stack_bottom = 0.0, -0.77812, 0.0, 0.0, -1.0, 0.0 TechRequired = specializedControl entryCost = 2800 cost = 1615 category = FuelTank subcategory = 0 title = Leo-B1G-CCR "Raphael-R" Equipment Module manufacturer = Bluedog Design Bureau description = Equipment module for the cylindrical B1G service module. Contains the main supply of monopropellant, mounting points for the RCS thrusters, and a crew access tube to connect the capsule to the Pressurized Cargo Module. real_title = Big Gemini Cylindrical Equipment Module real_description = Equipment module for the cylindrical Big G service module. Contains the main supply of monopropellant, mounting points for the RCS thrusters, and a crew access tube to connect the capsule to the Pressurized Cargo Module. real_manufacturer = Douglas Aircraft attachRules = 1,0,1,1,0 mass = 0.38 dragModelType = default maximum_drag = 0.2 minimum_drag = 0.3 angularDrag = 2 crashTolerance = 6 breakingForce = 72 breakingTorque = 72 maxTemp = 2000 // = 2900 bulkheadProfiles = size2 tags = ?gemina gemini leo retro structural big b1g 2.5 techtag = gemini RESOURCE { name = MonoPropellant amount = 500 maxAmount = 500 } MODULE { name = ModuleB9PartSwitch moduleID = meshSwitchAdapter switcherDescription = Adapter switcherDescriptionPlural = Adapters affectDragCubes = True affectFARVoxels = True SUBTYPE{ name = Big G } SUBTYPE { name = 2.5m transform = EndAdapter_2p5m NODE { name = bottom position = 0.0, -0.90364, 0.0 } } } MODULE { name = ModuleColorChanger shaderProperty = _EmissiveColor animRate = 0.8 animState = false useRate = true toggleInEditor = true toggleInFlight = true toggleInFlight = true unfocusedRange = 5 toggleName = Toggle Lights eventOnName = Lights On eventOffName = Lights Off toggleAction = True defaultActionGroup = Light includedRenderers = pSphere4, pSphere5, pSphere4 1, pSphere5 1, pSphere4 2, pSphere5 2, pSphere4 3, pSphere5 3 redCurve { key = 0 0 0 3 key = 1 1 0 0 } greenCurve { key = 0 0 0 1 key = 1 1 1 0 } blueCurve { key = 0 0 0 0 key = 1 0.7 1.5 0 } alphaCurve { key = 0 1 } } }
1
0.639034
1
0.639034
game-dev
MEDIA
0.459944
game-dev
0.654774
1
0.654774
UserUnknownFactor/GARbro2
7,722
Legacy/Formats/I/Inspire/ArcIDA.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text; using GameRes.Compression; // [971205][Azlocks] Isle Mystique // [991001][Inspire] days innocent // [000707][inspire] ambience namespace GameRes.Formats.Inspire { internal class IdaEntry : PackedEntry { public uint Flags; public uint Key; } [Export(typeof(ArchiveFormat))] public class IdaOpener : ArchiveFormat { public override string Tag { get { return "IDA"; } } public override string Description { get { return "Inspire resource archive"; } } public override uint Signature { get { return 0x464158; } } // 'XAF' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public IdaOpener () { Extensions = new[] { "ida", "mha" }; } public override ArcFile TryOpen (ArcView file) { int version = file.View.ReadInt32 (4); if (version > 0x011400) return null; using (var index = file.CreateStream()) { var dir = new List<Entry>(); bool has_packed = false; long index_pos = 8; do { index.Position = index_pos; uint entry_length = index.ReadUInt32(); if (0 == entry_length) break; uint offset = index.ReadUInt32(); uint size = index.ReadUInt32(); index.Seek (8, SeekOrigin.Current); uint flags = index.ReadUInt32(); uint key = index.ReadUInt32(); index.Seek (0x10, SeekOrigin.Current); var name = DeserializeString (index); index_pos += entry_length; var entry = FormatCatalog.Instance.Create<IdaEntry> (name); entry.Offset = offset; entry.Size = entry.UnpackedSize = size; if (offset > file.MaxOffset || offset < index_pos) return null; entry.IsPacked = (flags & 0x14) != 0; entry.Flags = flags; entry.Key = key; has_packed = has_packed || entry.IsPacked; dir.Add (entry); } while (index_pos < dir[0].Offset); if (0 == dir.Count) return null; if (has_packed) // set proper sizes { long last_offset = file.MaxOffset; for (int i = dir.Count - 1; i >= 0; --i) { dir[i].Size = (uint)(last_offset - dir[i].Offset); last_offset = dir[i].Offset; } } return new ArcFile (file, this, dir); } } public override Stream OpenEntry (ArcFile arc, Entry entry) { var ient = entry as IdaEntry; if (null == ient || 0 == ient.Flags) return base.OpenEntry (arc, entry); Stream input = arc.File.CreateStream (entry.Offset, entry.Size); if (0 != (ient.Flags & 0xB)) input = DecryptEntry (input, ient); if (0 != (ient.Flags & 4)) input = new PackedStream<RleDecompressor> (input); if (0 != (ient.Flags & 0x10)) input = new ZLibStream (input, CompressionMode.Decompress); return input; } Stream DecryptEntry (Stream input, IdaEntry entry) { int input_size = (int)entry.Size; var data = new byte[input_size]; using (input) input_size = input.Read (data, 0, input_size); byte key = (byte)entry.Key; for (int i = 0; i < input_size; ++i) { byte v = data[i]; if (0 != (entry.Flags & 8)) v += key; if (0 != (entry.Flags & 2)) v ^= key; if (0 != (entry.Flags & 1)) v ^= 0xFF; data[i] = v; key = v; } return new BinMemoryStream (data, 0, input_size, entry.Name); } string DeserializeString (IBinaryStream input) { int length = DeserializeLength (input); if (0 == length) return ""; if (length != -1) return input.ReadCString (length); length = DeserializeLength (input) * 2; var chars = input.ReadBytes (length); return Encoding.Unicode.GetString (chars, 0, length); } int DeserializeLength (IBinaryStream input) { int length = input.ReadUInt8(); if (length < 0xFF) return length; length = input.ReadUInt16(); if (0xFFFE == length) length = -1; else if (0xFFFF == length) length = input.ReadInt32(); return length; } } internal class RleDecompressor : Decompressor { IBinaryStream m_input; public override void Initialize (Stream input) { m_input = BinaryStream.FromStream (input, ""); } protected override IEnumerator<int> Unpack () { int output_size = m_input.ReadInt32(); int processed = 0; while (processed < output_size) { int ctl = m_input.ReadByte(); if (-1 == ctl) yield break; int count = 0; if (0 == (ctl & 0x80)) { count = ctl & 0x3F; } else if (0 == (ctl & 3)) { count = m_input.ReadUInt8(); } else if (1 == (ctl & 3)) { count = m_input.ReadUInt16(); } else if (3 == (ctl & 3)) { count = m_input.ReadInt32(); } processed += count; if (0 != (ctl & 0x40)) { byte v = m_input.ReadUInt8(); while (count --> 0) { m_buffer[m_pos++] = v; if (0 == --m_length) yield return m_pos; } } else { while (count > 0) { int avail = Math.Min (count, m_length); int read = m_input.Read (m_buffer, m_pos, avail); if (0 == read) yield break; count -= read; m_pos += read; m_length -= read; if (0 == m_length) yield return m_pos; } } } } bool m_disposed = false; protected override void Dispose (bool disposing) { if (!m_disposed) { if (m_input != null) m_input.Dispose(); m_disposed = true; base.Dispose (disposing); } } } }
1
0.922896
1
0.922896
game-dev
MEDIA
0.337002
game-dev
0.99272
1
0.99272
mcs-sdk/mcs
26,122
MCS_Importer/Importer/DarwinPrototypeImporter.cs
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; using System.IO; using System.Text.RegularExpressions; using System.ComponentModel; using System.Linq; using MCS.CONSTANTS; using MCS.COSTUMING; using MCS.UTILITIES; using MCS.CORESERVICES; using MCS; using MCS.CONTENTLIBRARY; using M3D_DLL; using MCS.Item; using MCS.Utility.Schematic; using MCS.Utility.Schematic.Enumeration; namespace M3DIMPORT { class DarwinPrototypeImporter : AssetPostprocessor { // various absolute strings private const string ROOT_FOLDER = "Assets/MCS"; private const string INJECTION_FOLDER = "/InjectionMasks"; private const string RESOURCES_FOLDER = "Assets/MCS/Resources"; private const string PREFAB_FOLDER = "Assets/MCS/Prefabs"; private const string RESOURCES_PREFAB_FOLDER = "Assets/MCS/Resources/Prefabs"; private const string GENERATED_MATERIALS_FOLDER = "Assets/MCS/Generated Materials"; private const string RESOURCES_MATERIALS_FOLDER = "Assets/MCS/Resources/Materials"; protected static Dictionary<string, AssetSchematic> schematicLookup = new Dictionary<string, AssetSchematic>(); public override int GetPostprocessOrder() { return 4; } /// <summary> /// AssetPostprocessor event raised before models are procesed. /// </summary> void OnPreprocessModel () { // ensure that the root folder is existant if (AssetDatabase.IsValidFolder (ROOT_FOLDER) == false) AssetDatabase.CreateFolder ("Assets", "MCS"); // ensure that the resources folder is existant if (AssetDatabase.IsValidFolder (RESOURCES_FOLDER) == false) AssetDatabase.CreateFolder (ROOT_FOLDER, "Resources"); if (assetPath.Contains(ROOT_FOLDER)) { if (assetPath.EndsWith(".fbx") || assetPath.EndsWith(".obj")) { ModelImporter mi = (ModelImporter)assetImporter; mi.importMaterials = false; } } } public static string ConvertRelativeToAbsolute(string path, string basePath) { string finalPath = path.Replace("./", basePath + "/"); return finalPath; } //we replace the default handler so the asset is properly serialized, otherwise it will not be b/c the Texture2D is not serialized if loaded dynamically (byte[] vs using a unity asset) public static Texture2D GetTextureFromPathEditor(string path, string basePath) { string finalPath = MCS_Utilities.Paths.ConvertRelativeToAbsolute(basePath,path); Texture2D tmp = AssetDatabase.LoadAssetAtPath<Texture2D>(finalPath); if(tmp == null) { UnityEngine.Debug.LogWarning("Failed to load texture at: " + finalPath); } return tmp; } public static Material GetMaterialFromGUIDEditor(string guid, string basePath) { AssetSchematic schematic = new AssetSchematic(); if (schematicLookup.TryGetValue(guid, out schematic)) { try { if (schematic != null && schematic.origin_and_description != null && schematic.origin_and_description.mcs_id != null && schematic.origin_and_description.mcs_id.Equals(guid)) { string matPath = MCS_Utilities.Paths.ConvertRelativeToAbsolute(basePath, schematic.stream_and_path.generated_path); //fix for maya matPath = matPath.Replace(":", "_"); Material m = AssetDatabase.LoadAssetAtPath<Material>(matPath); return m; } } catch (Exception e) { UnityEngine.Debug.LogException(e); } } else { string[] paths = Directory.GetFiles(basePath, "*.mon", SearchOption.AllDirectories); foreach (string path in paths) { try { schematic = AssetSchematic.CreateFromJSON(File.ReadAllText(path)); if (schematic != null && schematic.origin_and_description != null && schematic.origin_and_description.mcs_id != null && schematic.origin_and_description.mcs_id.Equals(guid)) { string monDir = MCS_Utilities.Paths.ConvertFileToDir(path); string matPath = MCS_Utilities.Paths.ConvertRelativeToAbsolute(monDir, schematic.stream_and_path.generated_path); Material m = AssetDatabase.LoadAssetAtPath<Material>(matPath); return m; } } catch (Exception e) { UnityEngine.Debug.LogException(e); } } } UnityEngine.Debug.LogWarning("Failed to locate material for GUID: " + guid); return null; } static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { ContentLibrarySO content_so = (ContentLibrarySO)Resources.Load ("ContentLibrarySO"); bool created = false; //set to true if we find a new asset we weren't tracking before, used to clear out our depenedency psuedo graph and prevent loops bool newAssetImported = false; HashSet<string> pathsToReimport = new HashSet<string>(); if (content_so == null) { created = true; content_so = ScriptableObject.CreateInstance<ContentLibrarySO>(); } foreach (var str in importedAssets) { //UnityEngine.Debug.Log("importing: " + str); if (!content_so.importerSeenPaths.Contains(str)) { content_so.importerSeenPaths.Add(str); newAssetImported = true; } if (str.Contains(".mr")) { // Only process install files here. morph files will be handled separately. if (!(str.Contains(".morph.mr") || str.Contains(".morphs.mr"))) { Debug.Log("Found MR File. "); MCS_Utilities.MCSResource resource = new MCS_Utilities.MCSResource(); resource.Read(str, false); foreach(string key in resource.header.Keys) { string outputDir = String.Empty; if (key.Contains(".morph") || key.Contains(".bin")) outputDir = System.IO.Path.Combine(Application.streamingAssetsPath, key); else outputDir = Path.Combine(Path.Combine(Path.GetDirectoryName(str), Path.GetFileNameWithoutExtension(str)), key); //Debug.Log("Output File :" + outputDir); resource.UnpackResource(key, outputDir); } AssetDatabase.Refresh(); } } if (str.Contains (".mon")) { schematicLookup.Clear(); int tmpPos = str.LastIndexOf('/'); string dirMon = Path.GetDirectoryName(str);// str.Substring(0, tmpPos); AssetSchematic[] schematics; AssetDependency ad = null; AssetDependencyImporter adi = null; bool skipAsset = false; if (!content_so.importerDependencies.TryGetValue(str,out ad)) { MonDeserializer monDes = new MonDeserializer (); schematics = monDes.DeserializeMonFile (str); adi = new AssetDependencyImporter(); adi.srcPath = str; adi.schematics = schematics; adi.DetermineAllDependencies(); content_so.importerDependencies.Add(str,adi); } else { adi = (AssetDependencyImporter)ad; schematics = adi.schematics; } if (!adi.HasAllDependencies()) { adi.attempts++; pathsToReimport.Add(str); skipAsset = true; } AssetCreator ac = new AssetCreator(); if (!TryToImportMaterialsFromSchematics(str, dirMon, schematics)) { //we have missing materials continue; } if (skipAsset) { continue; } //clean up the variables before re-using them. //look at the first schematic to determine the "MAIN" function, this is legacy, eventually assetschematicimporter will handle this instead AssetSchematic mon = schematics[0]; ac = new AssetCreator(); mon.stream_and_path.root_path = str; switch (mon.type_and_function.primary_function) { case PrimaryFunction.material: break; default: //handle an FBX (clothing, hair, figure, etc) string fbxFilePath = str.Replace(".mon", ".fbx"); if (File.Exists(fbxFilePath)) { //use a custom texture and material locator AssetSchematicImporter assetSchematicImporter = new AssetSchematicImporter(null, null, GetTextureFromPathEditor, GetMaterialFromGUIDEditor); assetSchematicImporter.basePath = dirMon; GameObject fbxGO = AssetDatabase.LoadAssetAtPath<GameObject>(fbxFilePath); if (fbxGO == null) { UnityEngine.Debug.LogError("Missing required FBX: " + fbxFilePath); //monDes.ResaveMonFile(str); break; } if (fbxGO != null) { List<AssetSchematic> schematicsList = new List<AssetSchematic>(); foreach (AssetSchematic schematic in schematics) { schematicsList.Add(schematic); } GameObject outputGO = assetSchematicImporter.CreateGameObjectFromExistinGameObject(fbxGO, schematicLookup, schematicsList); //one note, components like Animator and LODGroup will be STRIPPED as they are not included in the component whitelist from CreateGameObjectFromExistinGameObject if (ImportUtilities.RemapMorphsIfRequired(outputGO)) { content_so.refreshOnComplete = true; } //AssetDatabase.Refresh(); string prefabFilePath = str.Replace(".mon", ".prefab"); GameObject prefabObj; if (!File.Exists(prefabFilePath)) { //UnityEngine.Debug.Log("File does not exist: " + prefabFilePath); prefabObj = PrefabUtility.CreatePrefab(prefabFilePath, outputGO, ReplacePrefabOptions.Default); //force a completely new and clean prefab, do not allow old values to transfer over } else { prefabObj = AssetDatabase.LoadAssetAtPath<GameObject>(prefabFilePath); //UnityEngine.Debug.Log("Result of load: " + (prefabObj == null ? "null" : "not null")); if (prefabObj != null) { prefabObj = PrefabUtility.ReplacePrefab(outputGO, prefabObj, ReplacePrefabOptions.ConnectToPrefab); //UnityEngine.Debug.Log("Update of load: " + (prefabObj == null ? "null" : "not null")); } else { //replace it, there is something wrong with it's state UnityEngine.Debug.LogWarning("Replacing prefab that is in unworkable state: " + prefabFilePath); prefabObj = PrefabUtility.CreatePrefab(prefabFilePath, outputGO, ReplacePrefabOptions.Default); //force a completely new and clean prefab, do not allow old values to transfer over } } //These components automatically come back, we'll FORCE them to be destroyed b/c we don't need them try { Animator animator = prefabObj.GetComponent<Animator>(); LODGroup lodGroup = prefabObj.GetComponent<LODGroup>(); if (animator != null) { GameObject.DestroyImmediate(animator, true); } if (lodGroup != null) { GameObject.DestroyImmediate(lodGroup, true); } PrefabUtility.RecordPrefabInstancePropertyModifications(prefabObj); if (Application.isPlaying) { GameObject.Destroy(outputGO); } else { GameObject.DestroyImmediate(outputGO, false); } } catch (Exception e) { UnityEngine.Debug.Log("Caught an exception during import component update"); UnityEngine.Debug.LogException(e); } } } break; } } } foreach (var str in deletedAssets) { if(str.Contains ("MCS") && str.Contains (".fbx")) { AssetSchematic mon = content_so.AssetSchematicList.Where(x => x.stream_and_path.source_path == str).SingleOrDefault (); if (mon != null) { AssetDatabase.DeleteAsset(mon.stream_and_path.generated_path); mon.stream_and_path.generated_path = ""; mon.stream_and_path.source_path = ""; if (mon.stream_and_path.root_path == "") { content_so.DeleteItem(mon); } } } else if (str.Contains ("MCS") && str.Contains (".prefab")) { AssetSchematic mon = content_so.AssetSchematicList.Where(x => x.stream_and_path.generated_path == str).SingleOrDefault (); if (mon != null) { if (AssetDatabase.LoadAssetAtPath (mon.stream_and_path.generated_path,typeof(GameObject)) == null) { mon.stream_and_path.generated_path = ""; } } } else if (str.Contains ("MCS") && str.Contains (".mon")) { AssetSchematic mon = content_so.AssetSchematicList.Where(x => x.stream_and_path.root_path == str).SingleOrDefault (); if (mon != null && mon.stream_and_path != null) { mon.stream_and_path.root_path = ""; if (mon.stream_and_path.source_path == "") { content_so.DeleteItem(mon); } } } else if (str.Contains ("MCS") && str.Contains (".mat")) { AssetSchematic mon = content_so.AssetSchematicList.Where(x => x.stream_and_path.generated_path == str).SingleOrDefault (); if (mon != null && mon.stream_and_path.generated_path != null && AssetDatabase.LoadAssetAtPath (mon.stream_and_path.generated_path,typeof(Material)) == null) { mon.stream_and_path.generated_path = ""; } } } for (var i=0; i<movedAssets.Length; i++) { //Debug.Log("Moved Asset: " + movedAssets[i] + " from: " + movedFromAssetPaths[i]); } if (created) { if (AssetDatabase.IsValidFolder (ROOT_FOLDER) == false) { AssetDatabase.CreateFolder ("Assets", "MCS"); } if (AssetDatabase.IsValidFolder (RESOURCES_FOLDER) == false) { AssetDatabase.CreateFolder (ROOT_FOLDER, "Resources"); } if (AssetDatabase.IsValidFolder (RESOURCES_PREFAB_FOLDER) == false) { AssetDatabase.CreateFolder (RESOURCES_FOLDER, "Prefabs"); } if (AssetDatabase.IsValidFolder (RESOURCES_MATERIALS_FOLDER) == false) { AssetDatabase.CreateFolder (RESOURCES_FOLDER, "Materials"); } AssetDatabase.CreateAsset(content_so,RESOURCES_FOLDER + "/ContentLibrarySO.asset"); } bool recursed = false; if (newAssetImported) { foreach(string path in pathsToReimport) { //UnityEngine.Debug.Log("Reimporting unmet dependency asset: " + path); AssetDatabase.ImportAsset(path,ImportAssetOptions.ForceSynchronousImport); AssetDependencyImporter adi = (AssetDependencyImporter)content_so.importerDependencies[path]; if (adi != null) { foreach(string dependencyPath in adi.unmetDependencies) { if(dependencyPath.StartsWith("Material: ")) { continue; } if (content_so.importerSeenPaths.Contains(dependencyPath)) { continue; } AssetDatabase.ImportAsset(dependencyPath, ImportAssetOptions.ForceSynchronousImport); recursed = true; } } } } else { //nothing has changed, so stop //UnityEngine.Debug.Log("Flushing dependencies graph"); foreach(string key in content_so.importerDependencies.Keys) { AssetDependencyImporter adi = (AssetDependencyImporter)content_so.importerDependencies[key]; if (adi.unmetDependencies.Count > 0) { UnityEngine.Debug.LogError("Missing dependencies for: " + key); foreach(string dp in adi.unmetDependencies) { UnityEngine.Debug.Log("Unmet: " + dp); } } } content_so.ClearDependencies(); } if(!recursed && content_so.refreshOnComplete) { content_so.refreshOnComplete = false; //This causes an error with the prefab, but does work //AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); //This does not work //AssetDatabase.ImportAsset("Assets/StreamingAssets"); } EditorUtility.SetDirty (content_so); } public static bool TryToImportMaterialsFromSchematics(string str, string dirMon, AssetSchematic[] schematics) { bool materialCreationStatus = true; AssetCreator ac = new AssetCreator(); //let's look for any materials in the mon file, if we find any create and import them now before we move on for (int i = 0; i < schematics.Length && materialCreationStatus; i++) { AssetSchematic mon = schematics[i]; if (mon.origin_and_description != null && !String.IsNullOrEmpty(mon.origin_and_description.mcs_id)) { schematicLookup[mon.origin_and_description.mcs_id] = mon; } if (mon.type_and_function.artisttools_function == ArtistToolsFunction.material || mon.type_and_function.primary_function == PrimaryFunction.material) { try { Dictionary<string, Texture2D> textureDict = new Dictionary<string, Texture2D>(); bool textureLoadStatus = TextureLoader.GetTextures(mon, dirMon, out textureDict); if (textureLoadStatus == false) { //UnityEngine.Debug.LogError("Failed to find textures for material: " + str); continue; } Material mat = ac.CreateMorphMaterial(mon, textureDict); if (mon.stream_and_path.generated_path == "" || mon.stream_and_path.generated_path == null) { //mon.stream_and_path.generated_path = GENERATED_MATERIALS_FOLDER + "/" + mon.origin_and_description.name + ".mat"; string newDir = dirMon + "/Materials"; if (!Directory.Exists(newDir)) { Directory.CreateDirectory(newDir); } mon.stream_and_path.generated_path = "Materials/" + mon.origin_and_description.name + ".mat"; } int pos = mon.stream_and_path.generated_path.LastIndexOf('/'); string directoryPath = mon.stream_and_path.generated_path.Substring(0, pos); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } //does a material already exist, if so, replace over it string dstPath = MCS_Utilities.Paths.ConvertRelativeToAbsolute(dirMon, mon.stream_and_path.generated_path); //Convert incompatible maya ":" to "_" dstPath = dstPath.Replace(":", "_"); //UnityEngine.Debug.Log("dstPath: " + dstPath); if (!File.Exists(dstPath)) { AssetDatabase.CreateAsset(mat, dstPath); } else { Material oldMat = AssetDatabase.LoadAssetAtPath<Material>(dstPath); if (oldMat == null) { //UnityEngine.Debug.LogError("Unable to update material because we can't load it: " + dstPath); } else { oldMat.CopyPropertiesFromMaterial(mat); } } } catch(Exception e) { Debug.LogWarning("Material creation failed. " + e.Message); materialCreationStatus = false; } } } return materialCreationStatus; } public HierarchyRank GetHierarchyRank(GameObject go, string[] names, object[] values){ HierarchyRank rank = HierarchyRank.unknown; for (int i = 0; i < names.Length; i++) { //our placeholder values - make sure you dont use a previous parsed bad value!!! string name = names [i]; string string_value; switch(name){ case "hierarchy_rank": Debug.Log ("RANK"); string_value = values [i].ToString (); rank = MCS.Utilities.EnumHelper.ParseEnum<HierarchyRank> (string_value); break; } } return rank; } public void ConfigureSkeleton(GameObject go, string[] names, object[] values){ CSBoneService bs = go.GetComponent<CSBoneService> (); if (bs == null) bs = go.AddComponent<CSBoneService> (); } } }
1
0.991262
1
0.991262
game-dev
MEDIA
0.843967
game-dev
0.985368
1
0.985368
chaldea-center/chaldea
16,125
lib/app/modules/faker/mission/mission_receive.dart
import 'package:flutter/gestures.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:chaldea/app/app.dart'; import 'package:chaldea/app/descriptors/mission_conds.dart'; import 'package:chaldea/app/modules/common/builders.dart'; import 'package:chaldea/app/modules/common/filter_group.dart'; import 'package:chaldea/app/modules/master_mission/master_mission.dart'; import 'package:chaldea/generated/l10n.dart'; import 'package:chaldea/models/models.dart'; import 'package:chaldea/packages/platform/platform.dart'; import 'package:chaldea/utils/utils.dart'; import 'package:chaldea/widgets/widgets.dart'; import '../state.dart'; class UserEventMissionReceivePage extends StatefulWidget { final FakerRuntime runtime; const UserEventMissionReceivePage({super.key, required this.runtime}); @override State<UserEventMissionReceivePage> createState() => _UserEventMissionReceivePageState(); } class _UserEventMissionReceivePageState extends State<UserEventMissionReceivePage> { late final runtime = widget.runtime; late final userEventMissions = runtime.mstData.userEventMission; final thisYear = DateTime.now().year; List<MasterMission> mms = []; // late final mms = runtime.gameData.masterMissions.values.toList(); MasterMission? _mm; Set<int> selectedMissions = {}; List<int> giftObjectIds = []; final havingGifts = FilterGroupData<int>(); final notHavingGifts = FilterGroupData<int>(); final progressFilter = FilterGroupData<MissionProgressType>(); late final scrollController = ScrollController(); @override void initState() { super.initState(); initData(); } Future<void> initData() async { mms = runtime.gameData.timerData.masterMissions.toList(); final now = DateTime.now().timestamp; mms.retainWhere((mm) { if (const [MissionType.event, MissionType.random].contains(mm.type)) return false; if (mm.startedAt > now || mm.closedAt < now) return false; if (mm.type == MissionType.daily) { if (mm.endedAt < now - kSecsPerDay * 40) return false; } return true; }); for (final event in runtime.gameData.timerData.events) { if (!(event.startedAt <= now && event.endedAt > now && event.missions.isNotEmpty)) continue; List<EventMission> eventMissions = [], randomMissions = []; for (final mission in event.missions) { if (mission.type == MissionType.random) { if (runtime.mstData.userEventRandomMission[mission.id]?.isInProgress == true) { randomMissions.add(mission); } } else { eventMissions.add(mission); } } if (eventMissions.isNotEmpty) { mms.add( MasterMission( id: event.id, startedAt: event.startedAt, endedAt: event.endedAt, closedAt: event.endedAt, missions: eventMissions, script: {MstMasterMission.kMissionIconDetailText: event.lShortName.l.setMaxLines(1)}, ), ); } if (randomMissions.isNotEmpty) { mms.add( MasterMission( id: event.id * 100 + 1, startedAt: event.startedAt, endedAt: event.endedAt, closedAt: event.endedAt, missions: randomMissions, script: { MstMasterMission.kMissionIconDetailText: '[${S.current.random_mission}] ${event.lShortName.l.setMaxLines(1)}', }, ), ); } } // mms.removeWhere((mm) => mm.type == MissionType.daily && mm.endedAt - mm.startedAt > kSecsPerDay * 40); mms.sortByList((e) => [e.endedAt, e.closedAt, e.id]); if (mms.isNotEmpty) { onSelectMM( mms.firstWhere( (mm) => mm.missions.any((e) => getMissionProgress(e.id) != MissionProgressType.achieve), orElse: () => mms.first, ), ); } if (mounted) setState(() {}); } MissionProgressType getMissionProgress(int eventMissionId) { final progress = userEventMissions[eventMissionId]?.missionProgressType; if (progress == null) return MissionProgressType.none; return MissionProgressType.fromValue(progress); } bool isMissionClear(int eventMissionId) => getMissionProgress(eventMissionId) == MissionProgressType.clear; void onSelectMM(MasterMission mm) { if (_mm != mm) { selectedMissions.clear(); } _mm = mm; giftObjectIds = mm.missions.expand((e) => e.gifts).map((e) => e.objectId).toSet().toList(); if (mm.id == MasterMission.kExtraMasterMissionId) { final clearGifts = mm.missions .where((e) => isMissionClear(e.id)) .expand((e) => e.gifts) .map((e) => e.objectId) .toSet(); giftObjectIds.sortByList((e) => [clearGifts.contains(e) ? 0 : 1, e]); giftObjectIds.sort((a, b) { final r = (clearGifts.contains(a) ? 0 : 1).compareTo((clearGifts.contains(b) ? 0 : 1)); if (r != 0) return r; return Item.compare2(a, b); }); } else { giftObjectIds.sort(Item.compare2); } havingGifts.options.retainAll(giftObjectIds); notHavingGifts.options.retainAll(giftObjectIds); if (mounted) setState(() {}); } @override Widget build(BuildContext context) { selectedMissions.retainWhere(isMissionClear); final missions = (_mm?.missions ?? const []).where((mission) { final gifts = mission.gifts.map((e) => e.objectId).toSet(); if (havingGifts.isNotEmpty && !havingGifts.matchAny(gifts)) return false; if (notHavingGifts.isNotEmpty && notHavingGifts.matchAny(gifts)) return false; if (!progressFilter.matchOne(getMissionProgress(mission.id))) return false; return true; }).toList(); missions.sort2((e) => e.dispNo); return Scaffold( appBar: AppBar( title: Text(S.current.master_mission), actions: [ if (_mm != null) IconButton( onPressed: () { router.push( url: Routes.masterMissionI(_mm!.id), child: MasterMissionPage(masterMission: _mm, region: runtime.region), ); }, icon: Icon(Icons.info_outline), ), runtime.buildHistoryButton(context), runtime.buildMenuButton(context), ], ), body: Column( children: [ buildHeader(), Expanded( child: Scrollbar( trackVisibility: PlatformU.isDesktopOrWeb, controller: scrollController, child: ListView.builder( controller: scrollController, itemCount: missions.length, itemBuilder: (context, index) { return buildEventMission(missions[index], missions); }, ), ), ), SafeArea(child: buildButtonBar()), ], ), ); } Widget buildHeader() { Widget child = DropdownButton<MasterMission>( isExpanded: true, value: _mm, items: [for (final mm in mms) DropdownMenuItem(value: mm, child: buildMasterMission(mm))], onChanged: (v) { setState(() { if (v != null) onSelectMM(v); }); }, ); return Container( color: Theme.of(context).highlightColor, padding: EdgeInsets.only(bottom: 8), child: DropdownButtonHideUnderline(child: child), ); } Widget buildMasterMission(MasterMission mm) { int clearNum = mm.missions.where((e) => getMissionProgress(e.id) == MissionProgressType.clear).length; int achieveNum = mm.missions.where((e) => getMissionProgress(e.id) == MissionProgressType.achieve).length; int notClearNum = mm.missions.length - clearNum - achieveNum; final now = DateTime.now().timestamp; return ListTile( dense: true, selected: (clearNum > 0 || notClearNum > 0) && mm.startedAt < now && mm.endedAt > now, enabled: !(notClearNum == 0 && clearNum == 0), title: Text( '[${mm.missions.length} ${Transl.enums(mm.type, (v) => v.missionType).l}] ID ${mm.id} ${mm.lMissionIconDetailText ?? ""}', maxLines: 2, overflow: TextOverflow.ellipsis, textScaler: const TextScaler.linear(0.9), ), subtitle: Text( [mm.startedAt, mm.endedAt, if (mm.closedAt != mm.endedAt) mm.closedAt] .map((e) { final date = e.sec2date(); return mm.id == MasterMission.kExtraMasterMissionId ? date.toDateString() : date.toCustomString(year: date.year != thisYear, second: false); }) .join(' ~ '), ), trailing: Text('$notClearNum/$clearNum/$achieveNum'), ); } Widget buildEventMission(EventMission mission, List<EventMission> missions) { Widget title = Text.rich( TextSpan( text: '${mission.dispNo}. ${mission.name}', recognizer: TapGestureRecognizer() ..onTap = () { SimpleConfirmDialog( title: Text('No.${mission.dispNo} (${mission.id})'), scrollable: true, showCancel: false, content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(mission.name, style: Theme.of(context).textTheme.bodySmall), const Divider(), MissionCondsDescriptor(mission: mission, missions: missions), ], ), ).showDialog(context); }, ), maxLines: 2, overflow: TextOverflow.ellipsis, ); Widget subtitle = Wrap( spacing: 1, runSpacing: 1, crossAxisAlignment: WrapCrossAlignment.center, children: [for (final gift in mission.gifts) gift.iconBuilder(context: context, width: 32)], ); // random mission not checked final progressType = getMissionProgress(mission.id); Widget trailing; if (progressType == MissionProgressType.clear) { trailing = Checkbox( visualDensity: VisualDensity.compact, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, value: selectedMissions.contains(mission.id), onChanged: (v) { setState(() { if (v!) { selectedMissions.add(mission.id); } else { selectedMissions.remove(mission.id); } }); }, ); } else { int? progressNum, targetNum; final eventMissionFix = runtime.mstData.userEventMissionFix[mission.id]; if (eventMissionFix != null) { // progressType=eventMissionFix.progressType; progressNum = eventMissionFix.num; } for (final cond in mission.conds) { if (cond.missionProgressType != MissionProgressType.clear) continue; if (cond.condType == CondType.missionConditionDetail) { final condDetailId = cond.targetIds.firstOrNull; if (condDetailId == null) continue; progressNum ??= runtime.mstData.userEventMissionCondDetail[condDetailId]?.progressNum; } else if (cond.condType == CondType.eventMissionClear) { progressNum ??= cond.targetIds.where((mid) { final progressType = runtime.mstData.userEventMission[mid]?.missionProgressType; return progressType == MissionProgressType.clear.value || progressType == MissionProgressType.achieve.value; }).length; } else if (cond.condType == CondType.eventMissionAchieve) { progressNum ??= cond.targetIds.where((mid) { final progressType = runtime.mstData.userEventMission[mid]?.missionProgressType; return progressType == MissionProgressType.achieve.value; }).length; } else if (cond.condType == CondType.questClear) { progressNum ??= cond.targetIds.where((questId) { return (runtime.mstData.userQuest[questId]?.clearNum ?? 0) > 0; }).length; } else { // don't set targetNum continue; } targetNum = cond.targetNum; } trailing = Text( [ progressType.name, if (progressNum != null || targetNum != null) '${progressNum ?? "?"}/${targetNum ?? "?"}', ].join('\n'), textAlign: TextAlign.end, ); } return ListTileTheme.merge( key: ObjectKey(mission), dense: true, minLeadingWidth: 16, child: ListTile( title: title, subtitle: subtitle, enabled: progressType == MissionProgressType.clear || progressType == MissionProgressType.achieve, trailing: trailing, onTap: () { setState(() { selectedMissions.toggle(mission.id); }); }, ), ); } Widget buildButtonBar() { return Column( mainAxisSize: MainAxisSize.min, children: [ for (final (title, filterData) in [(S.current.show, havingGifts), (S.current.hide, notHavingGifts)]) Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(width: 16), ConstrainedBox(constraints: BoxConstraints(minWidth: 48), child: Text(title)), Expanded( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: FilterGroup<int>( options: giftObjectIds, values: filterData, padding: EdgeInsets.zero, combined: true, shrinkWrap: true, optionBuilder: (v) { return GameCardMixin.anyCardItemBuilder( context: context, id: v, height: 36, padding: EdgeInsets.all(2), jumpToDetail: false, ); }, onFilterChanged: (_, _) { setState(() {}); }, ), ), ), ], ), const SizedBox(height: 4), FilterGroup<MissionProgressType>( options: const [MissionProgressType.none, MissionProgressType.clear, MissionProgressType.achieve], values: progressFilter, padding: EdgeInsets.only(bottom: 4), combined: true, optionBuilder: (v) => Text(v.name), onFilterChanged: (v, _) { setState(() {}); }, ), Center( child: FilledButton( onPressed: selectedMissions.isEmpty ? null : receiveMissions, child: Text('Mission Receive ×${selectedMissions.length}'), ), ), const SizedBox(height: 4), ], ); } Future<void> receiveMissions() async { final missions = { if (_mm != null) for (final m in _mm!.missions) m.id: m, }; final gifts = <int, int>{}; if (selectedMissions.isEmpty || !selectedMissions.every((e) => missions.containsKey(e))) { EasyLoading.showError('Another mm mission is selected'); return; } if (!selectedMissions.every(isMissionClear)) { EasyLoading.showError('Contain non-clear progress mission'); return; } for (final id in selectedMissions) { for (final gift in missions[id]!.gifts) { gifts.addNum(gift.objectId, gift.num); } } if (runtime.runningTask.value) return; SimpleConfirmDialog( title: Text('Receive ${selectedMissions.length} missions'), scrollable: true, content: SharedBuilder.itemGrid(context: context, items: gifts.entries.toList(), height: 36), onTapOk: () async { await runtime.runTask(() => runtime.agent.eventMissionClearReward(missionIds: selectedMissions.toList())); selectedMissions.retainWhere(isMissionClear); if (mounted) setState(() {}); }, ).showDialog(context); } }
1
0.900743
1
0.900743
game-dev
MEDIA
0.892064
game-dev
0.965806
1
0.965806
anba/es6draft
6,817
src/main/java/com/github/anba/es6draft/compiler/AbstractIterationGenerator.java
/** * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.compiler; import java.util.List; import com.github.anba.es6draft.ast.Node; import com.github.anba.es6draft.compiler.Labels.TempLabel; import com.github.anba.es6draft.compiler.StatementGenerator.Completion; import com.github.anba.es6draft.compiler.assembler.Jump; import com.github.anba.es6draft.compiler.assembler.MethodName; import com.github.anba.es6draft.compiler.assembler.MutableValue; import com.github.anba.es6draft.compiler.assembler.TryCatchLabel; import com.github.anba.es6draft.compiler.assembler.Type; import com.github.anba.es6draft.compiler.assembler.Value; import com.github.anba.es6draft.compiler.assembler.Variable; import com.github.anba.es6draft.runtime.internal.ScriptException; /** * */ abstract class AbstractIterationGenerator<NODE extends Node, ITERATOR> { private static final class Methods { // class: ErrorOperations static final MethodName ErrorOperations_stackOverflowError = MethodName.findStatic(Types.ErrorOperations, "stackOverflowError", Type.methodType(Types.StackOverflowError, Types.Error)); } private final CodeGenerator codegen; AbstractIterationGenerator(CodeGenerator codegen) { this.codegen = codegen; } /** * Emit code for the iteration body. * * @param node * the ast node * @param iterator * the iterator variable * @param mv * the code visitor * @return the completion value */ protected abstract Completion iterationBody(NODE node, Variable<ITERATOR> iterator, CodeVisitor mv); /** * Emit code for the iteration epilogue. * * @param node * the ast node * @param iterator * the iterator variable * @param mv * the code visitor */ protected void epilogue(NODE node, Variable<ITERATOR> iterator, CodeVisitor mv) { // Default implementation is empty. } /** * Called before emitting the iteration body. * * @param node * the ast node * @param mv * the code visitor * @return the temporary completion object variable or {@code null} */ protected abstract MutableValue<Object> enterIteration(NODE node, CodeVisitor mv); /** * Called after emitting the iteration body. * * @param node * the ast node * @param mv * the code visitor * @return the list of generated labels */ protected abstract List<TempLabel> exitIteration(NODE node, CodeVisitor mv); /** * Emit code for the wrapped iteration. * * @param node * the ast node * @param iterator * the iterator variable * @param mv * the code visitor * @return the completion value */ public final Completion generate(NODE node, Variable<ITERATOR> iterator, CodeVisitor mv) { return generate(node, iterator, null, mv); } /** * Emit code for the wrapped iteration. * * @param node * the ast node * @param iterator * the iterator variable * @param target * the target label * @param mv * the code visitor * @return the completion value */ public final Completion generate(NODE node, Variable<ITERATOR> iterator, Jump target, CodeVisitor mv) { TryCatchLabel startIteration = new TryCatchLabel(), endIteration = new TryCatchLabel(); TryCatchLabel handlerCatch = new TryCatchLabel(); TryCatchLabel handlerCatchStackOverflow = null; if (codegen.isEnabled(Compiler.Option.IterationCatchStackOverflow)) { handlerCatchStackOverflow = new TryCatchLabel(); } boolean hasTarget = target != null; if (!hasTarget) { target = new Jump(); } mv.enterVariableScope(); MutableValue<Object> completion = enterIteration(node, mv); // Emit loop body mv.mark(startIteration); Completion loopBodyResult = iterationBody(node, iterator, mv); if (!loopBodyResult.isAbrupt()) { mv.goTo(target); } mv.mark(endIteration); // Restore temporary abrupt targets List<TempLabel> tempLabels = exitIteration(node, mv); // Emit throw handler emitThrowHandler(node, iterator, handlerCatch, handlerCatchStackOverflow, mv); // Emit return handler emitReturnHandler(node, iterator, completion, tempLabels, mv); mv.exitVariableScope(); mv.tryCatch(startIteration, endIteration, handlerCatch, Types.ScriptException); if (handlerCatchStackOverflow != null) { mv.tryCatch(startIteration, endIteration, handlerCatchStackOverflow, Types.Error); } if (!hasTarget) { mv.mark(target); epilogue(node, iterator, mv); } return loopBodyResult; } private void emitThrowHandler(NODE node, Variable<ITERATOR> iterator, TryCatchLabel handlerCatch, TryCatchLabel handlerCatchStackOverflow, CodeVisitor mv) { mv.enterVariableScope(); Variable<? extends Throwable> throwable; if (handlerCatchStackOverflow == null) { throwable = mv.newVariable("throwable", ScriptException.class); } else { throwable = mv.newVariable("throwable", Throwable.class); } if (handlerCatchStackOverflow != null) { mv.catchHandler(handlerCatchStackOverflow, Types.Error); mv.invoke(Methods.ErrorOperations_stackOverflowError); } mv.catchHandler(handlerCatch, Types.ScriptException); mv.store(throwable); IteratorClose(node, iterator, throwable, mv); mv.load(throwable); mv.athrow(); mv.exitVariableScope(); } private void emitReturnHandler(NODE node, Variable<ITERATOR> iterator, Value<Object> completion, List<TempLabel> tempLabels, CodeVisitor mv) { // (1) Intercept return instructions for (TempLabel temp : tempLabels) { if (temp.isTarget()) { mv.mark(temp); IteratorClose(node, iterator, mv); mv.goTo(temp, completion); } } } protected abstract void IteratorClose(NODE node, Variable<ITERATOR> iterator, Variable<? extends Throwable> throwable, CodeVisitor mv); protected abstract void IteratorClose(NODE node, Variable<ITERATOR> iterator, CodeVisitor mv); }
1
0.877841
1
0.877841
game-dev
MEDIA
0.34526
game-dev
0.847355
1
0.847355
r-lyeh/v3
9,181
ext/ext-lab/ext-spine/3rd/spine/extension.h
/****************************************************************************** * Spine Runtimes License Agreement * Last updated April 5, 2025. Replaces all prior versions. * * Copyright (c) 2013-2025, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ /* Implementation notes: - An OOP style is used where each "class" is made up of a struct and a number of functions prefixed with the struct name. - struct fields that are const are readonly. Either they are set in a create function and can never be changed, or they can only be changed by calling a function. - Inheritance is done using a struct field named "super" as the first field, allowing the struct to be cast to its "super class". This works because a pointer to a struct is guaranteed to be a pointer to the first struct field. - Classes intended for inheritance provide init/deinit functions which subclasses must call in their create/dispose functions. - Polymorphism is done by a base class providing function pointers in its init function. The public API delegates to these function pointers. - Subclasses do not provide a dispose function, instead the base class' dispose function should be used, which will delegate to a dispose function pointer. - Classes not designed for inheritance cannot be extended because they may use an internal subclass to hide private data and don't expose function pointers. - The public API hides implementation details, such as init/deinit functions. An internal API is exposed by extension.h to allow classes to be extended. Internal functions begin with underscore (_). - OOP in C tends to lose type safety. Macros for casting are provided in extension.h to give context for why a cast is being done. */ #ifndef SPINE_EXTENSION_H_ #define SPINE_EXTENSION_H_ #include "../spine/dll.h" /* Required for sprintf and consorts on MSVC */ #ifdef _MSC_VER #pragma warning(disable:4996) #endif /* All allocation uses these. */ #define MALLOC(TYPE, COUNT) ((TYPE*)_spMalloc(sizeof(TYPE) * (COUNT), __FILE__, __LINE__)) #define CALLOC(TYPE, COUNT) ((TYPE*)_spCalloc(COUNT, sizeof(TYPE), __FILE__, __LINE__)) #define REALLOC(PTR, TYPE, COUNT) ((TYPE*)_spRealloc(PTR, sizeof(TYPE) * (COUNT))) #define NEW(TYPE) CALLOC(TYPE,1) /* Gets the direct super class. Type safe. */ #define SUPER(VALUE) (&VALUE->super) /* Cast to a super class. Not type safe, use with care. Prefer SUPER() where possible. */ #define SUPER_CAST(TYPE, VALUE) ((TYPE*)VALUE) /* Cast to a sub class. Not type safe, use with care. */ #define SUB_CAST(TYPE, VALUE) ((TYPE*)VALUE) /* Gets the vtable for the specified type. Not type safe, use with care. */ #define VTABLE(TYPE, VALUE) ((_##TYPE##Vtable*)((TYPE*)VALUE)->vtable) /* Frees memory. Can be used on const types. */ #define FREE(VALUE) _spFree((void*)VALUE) /* Allocates a new char[], assigns it to TO, and copies FROM to it. Can be used on const types. */ #define MALLOC_STR(TO, FROM) strcpy(TO = (char*)MALLOC(char, strlen(FROM) + 1), FROM) #define PI 3.1415926535897932385f #define PI2 (PI * 2) #define INV_PI2 (1 / PI2) #define DEG_RAD (PI / 180) #define RAD_DEG (180 / PI) #define ABS(A) ((A) < 0? -(A): (A)) #define SIGNUM(A) ((A) < 0? -1.0f: (A) > 0 ? 1.0f : 0.0f) #define CEIL(a) ((float)ceil(a)) #ifdef __STDC_VERSION__ #define FMOD(A,B) fmodf(A, B) #define ATAN2(A,B) atan2f(A, B) #define SIN(A) sinf(A) #define COS(A) cosf(A) #define SQRT(A) sqrtf(A) #define ACOS(A) acosf(A) #define POW(A,B) pow(A, B) #define ISNAN(A) (int)isnan(A) #else #define FMOD(A, B) (float)fmod(A, B) #define ATAN2(A, B) (float)atan2(A, B) #define COS(A) (float)cos(A) #define SIN(A) (float)sin(A) #define SQRT(A) (float)sqrt(A) #define ACOS(A) (float)acos(A) #define POW(A, B) (float)pow(A, B) #define ISNAN(A) (int)isnan(A) #endif #define SIN_DEG(A) SIN((A) * DEG_RAD) #define COS_DEG(A) COS((A) * DEG_RAD) #define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x))) #ifndef MIN #define MIN(x, y) ((x) < (y) ? (x) : (y)) #endif #ifndef MAX #define MAX(x, y) ((x) > (y) ? (x) : (y)) #endif #define ATAN2DEG(A, B) ((float)ATAN2(A, B) * RAD_DEG) #define UNUSED(x) (void)(x) #include <stdlib.h> #include <string.h> #include <math.h> #include "../spine/Skeleton.h" #include "../spine/Animation.h" #include "../spine/Atlas.h" #include "../spine/AttachmentLoader.h" #include "../spine/VertexAttachment.h" #include "../spine/RegionAttachment.h" #include "../spine/MeshAttachment.h" #include "../spine/BoundingBoxAttachment.h" #include "../spine/ClippingAttachment.h" #include "../spine/PathAttachment.h" #include "../spine/PointAttachment.h" #include "../spine/AnimationState.h" #ifdef __cplusplus extern "C" { #endif /* * Functions that must be implemented: */ void _spAtlasPage_createTexture(spAtlasPage *self, const char *path); void _spAtlasPage_disposeTexture(spAtlasPage *self); char *_spUtil_readFile(const char *path, int *length); /* * Internal API available for extension: */ void *_spMalloc(size_t size, const char *file, int line); void *_spCalloc(size_t num, size_t size, const char *file, int line); void *_spRealloc(void *ptr, size_t size); void _spFree(void *ptr); float _spRandom(void); SP_API void _spSetMalloc(void *(*_malloc)(size_t size)); SP_API void _spSetDebugMalloc(void *(*_malloc)(size_t size, const char *file, int line)); SP_API void _spSetRealloc(void *(*_realloc)(void *ptr, size_t size)); SP_API void _spSetFree(void (*_free)(void *ptr)); SP_API void _spSetRandom(float (*_random)(void)); char *_spReadFile(const char *path, int *length); /* * Math utilities */ float _spMath_random(float min, float max); float _spMath_randomTriangular(float min, float max); float _spMath_randomTriangularWith(float min, float max, float mode); float _spMath_interpolate(float (*apply)(float a), float start, float end, float a); float _spMath_pow2_apply(float a); float _spMath_pow2out_apply(float a); /**/ typedef union _spEventQueueItem { int type; spTrackEntry *entry; spEvent *event; } _spEventQueueItem; typedef struct _spAnimationState _spAnimationState; typedef struct _spEventQueue { _spAnimationState *state; _spEventQueueItem *objects; int objectsCount; int objectsCapacity; int /*boolean*/ drainDisabled; } _spEventQueue; struct _spAnimationState { spAnimationState super; int eventsCount; spEvent **events; _spEventQueue *queue; spPropertyId *propertyIDs; int propertyIDsCount; int propertyIDsCapacity; int /*boolean*/ animationsChanged; }; /**/ /* configureAttachment and disposeAttachment may be 0. */ void _spAttachmentLoader_init(spAttachmentLoader *self, void (*dispose)(spAttachmentLoader *self), spAttachment *(*createAttachment)(spAttachmentLoader *self, spSkin *skin, spAttachmentType type, const char *name, const char *path, spSequence *sequence), void (*configureAttachment)(spAttachmentLoader *self, spAttachment *), void (*disposeAttachment)(spAttachmentLoader *self, spAttachment *) ); void _spAttachmentLoader_deinit(spAttachmentLoader *self); /* Can only be called from createAttachment. */ void _spAttachmentLoader_setError(spAttachmentLoader *self, const char *error1, const char *error2); void _spAttachmentLoader_setUnknownTypeError(spAttachmentLoader *self, spAttachmentType type); /**/ void _spAttachment_init(spAttachment *self, const char *name, spAttachmentType type, void (*dispose)(spAttachment *self), spAttachment *(*copy)(spAttachment *self)); void _spAttachment_deinit(spAttachment *self); void _spVertexAttachment_init(spVertexAttachment *self); void _spVertexAttachment_deinit(spVertexAttachment *self); #ifdef __cplusplus } #endif #endif /* SPINE_EXTENSION_H_ */
1
0.888762
1
0.888762
game-dev
MEDIA
0.351062
game-dev
0.602603
1
0.602603
mekanism/Mekanism
2,329
src/main/java/mekanism/client/render/transmitter/RenderUniversalCable.java
package mekanism.client.render.transmitter; import com.mojang.blaze3d.vertex.PoseStack; import mekanism.api.annotations.NothingNullByDefault; import mekanism.client.render.MekanismRenderer; import mekanism.common.base.ProfilerConstants; import mekanism.common.content.network.EnergyNetwork; import mekanism.common.content.network.transmitter.UniversalCable; import mekanism.common.tile.transmitter.TileEntityUniversalCable; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.Sheets; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.phys.Vec3; @NothingNullByDefault public class RenderUniversalCable extends RenderTransmitterBase<TileEntityUniversalCable> { public RenderUniversalCable(BlockEntityRendererProvider.Context context) { super(context); } @Override protected void render(TileEntityUniversalCable tile, float partialTick, PoseStack matrix, MultiBufferSource renderer, int light, int overlayLight, ProfilerFiller profiler) { EnergyNetwork network = tile.getTransmitter().getTransmitterNetwork(); if (network == null) { return;//race condition perhaps } matrix.pushPose(); matrix.translate(0.5, 0.5, 0.5); renderModel(tile, matrix, renderer.getBuffer(Sheets.translucentCullBlockSheet()), 0xFFFFFF, network.currentScale, LightTexture.FULL_BRIGHT, overlayLight, MekanismRenderer.energyIcon); matrix.popPose(); } @Override protected String getProfilerSection() { return ProfilerConstants.UNIVERSAL_CABLE; } @Override protected boolean shouldRenderTransmitter(TileEntityUniversalCable tile, Vec3 camera) { if (super.shouldRenderTransmitter(tile, camera)) { UniversalCable cable = tile.getTransmitter(); if (cable.hasTransmitterNetwork()) { EnergyNetwork network = cable.getTransmitterNetwork(); //Note: We don't check if the network is empty as we don't actually ever sync the energy value to the client return network.currentScale > 0; } } return false; } }
1
0.822599
1
0.822599
game-dev
MEDIA
0.699876
game-dev,graphics-rendering
0.763839
1
0.763839
Intel-Media-SDK/MediaSDK
30,512
tools/asg-hevc/src/mvmvp_processor.cpp
// Copyright (c) 2018-2019 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "mfxvideo.h" #if MFX_VERSION >= MFX_VERSION_NEXT #include "mvmvp_processor.h" // Generates MVP pool groups according to PU positioning in CTU and constructed MVP blocks grid void MVMVPProcessor::InitMVPGridData(const CTUDescriptor& CTU, const FrameChangeDescriptor & frameDescr) { mfxU32 gridSizeIn32x32Blocks = CTU.m_BWidth / (2 * MVP_BLOCK_SIZE); // 16x16 MVP blocks in frame; numbers denote order in file: // ++++++++++++++++++++ // + 0 + 1 + 4 + 5 + // +++++++++++++++++ ... // + 2 + 3 + 6 + 7 + // +++++++++++++++++ // + ... // Each quarter of 16x16 blocks with sequent indecies are forming a 32x32 block group m_mvpBlockGrid.reserve(gridSizeIn32x32Blocks * gridSizeIn32x32Blocks); if (!gridSizeIn32x32Blocks) // only one 16x16 block { m_mvpBlockGrid.emplace_back(CTU.m_AdrX, CTU.m_AdrY, MVP_BLOCK_SIZE, MVP_BLOCK_SIZE); } else { // Pushing MVP blocks onto the grid in zig-zag order described above for (mfxU32 gridIdx = 0; gridIdx < gridSizeIn32x32Blocks * gridSizeIn32x32Blocks; ++gridIdx) { for (mfxU32 elemIdx = 0; elemIdx < 4; ++elemIdx) { m_mvpBlockGrid.emplace_back( CTU.m_AdrX + (2 * (gridIdx % gridSizeIn32x32Blocks) + (elemIdx % 2)) * MVP_BLOCK_SIZE, CTU.m_AdrY + (2 * (gridIdx / gridSizeIn32x32Blocks) + (elemIdx / 2)) * MVP_BLOCK_SIZE, MVP_BLOCK_SIZE, MVP_BLOCK_SIZE); } } } mfxI32 mvpGroupsNum = ConstructMVPPoolGroups(CTU); // All PUs are processed - constructing actual MVP pools per each group m_mvpPools.resize(mvpGroupsNum); for (mfxI32 groupNo = 0; groupNo < mvpGroupsNum; ++groupNo) { m_mvpPools[groupNo].reserve(MVP_PER_16x16_BLOCK); for (mfxU32 mvpCount = 0; mvpCount < MVP_PER_16x16_BLOCK; ++mvpCount) { m_mvpPools[groupNo].emplace_back(GenerateMVP(CTU, frameDescr)); } } } mfxI32 MVMVPProcessor::ConstructMVPPoolGroups(const CTUDescriptor& CTU) { switch (m_GenMVPBlockSize) { case 1: if (CTU.m_BWidth == 32 || CTU.m_BWidth == 64) { return PutPUAndMVPBlocksIn16x16MVPPoolGroups(CTU); } case 2: if (CTU.m_BWidth == 64) { return PutPUAndMVPBlocksIn32x32MVPPoolGroups(CTU); } case 3: return PutPUAndMVPBlocksInSingleMVPPoolGroup(CTU); default: throw std::string("ERROR: MVMVPProcessor: ConstructMVPPoolGroups: Incorrect m_GenMVPBlockSize used"); } } mfxI32 MVMVPProcessor::PutPUAndMVPBlocksIn16x16MVPPoolGroups(const CTUDescriptor & CTU) { mfxI32 extMVPGroupNo = 0; for (const auto& CU : CTU.m_CUVec) { if (CU.m_PredType == INTER_PRED) { // For all the inter PUs constructing a MVP block list which this PU has intersections with for (const auto& PU : CU.m_PUVec) { // Construct a list with all MVP blocks which have intersections with current PU std::list<MVPBlock> intersectedMVPBlocks; for (const auto& mvpBlock : m_mvpBlockGrid) { if (PU.CheckForIntersect(mvpBlock)) { intersectedMVPBlocks.push_back(mvpBlock); } } // Checking the list validity. It should have at least 1 element if (intersectedMVPBlocks.empty()) { throw std::string("ERROR: MVMVPProcessor: PutPUAndMVPBlocksIn16x16MVPPoolGroups: Found a PU which doesn't intersect the MVP grid"); } // Check if there is at least one block which is included in some group // MVP blocks should have no group or be included in the one group auto validGroupMVPBlock = std::find_if(intersectedMVPBlocks.begin(), intersectedMVPBlocks.end(), [](const MVPBlock& block) { return block.IsAlreadyInGroup(); }); // If it exists, put all MVP blocks intersected with current PU in this group if (validGroupMVPBlock != intersectedMVPBlocks.end()) { mfxI32 firstValidGroupNo = validGroupMVPBlock->GetGroupNo(); if (std::any_of(intersectedMVPBlocks.begin(), intersectedMVPBlocks.end(), [firstValidGroupNo](const MVPBlock& block) { return (block.IsAlreadyInGroup() && !block.IsInGroup(firstValidGroupNo)); })) { throw std::string("ERROR: PutPUAndMVPBlocksIn16x16MVPPoolGroups : Found a pair of MVP blocks intersecting with current PU which are in the different MVP groups"); } else // include all intersecting MVP blocks in the single group { for (MVPBlock& block : m_mvpBlockGrid) { if (std::find(intersectedMVPBlocks.begin(), intersectedMVPBlocks.end(), block) != intersectedMVPBlocks.end()) { block.SetGroup(firstValidGroupNo); } } // The list is valid - set PU pool group no. with the value for MVP blocks m_PUtoMVPPoolGroupMap[PU] = firstValidGroupNo; } } else // Otherwise, put all MVP blocks in the new group { for (MVPBlock& block : m_mvpBlockGrid) { if (std::find(intersectedMVPBlocks.begin(), intersectedMVPBlocks.end(), block) != intersectedMVPBlocks.end()) { block.SetGroup(extMVPGroupNo); } } // The list is valid - set PU pool group no. with the value for MVPs m_PUtoMVPPoolGroupMap[PU] = extMVPGroupNo; ++extMVPGroupNo; } } } } return extMVPGroupNo; } mfxI32 MVMVPProcessor::PutPUAndMVPBlocksIn32x32MVPPoolGroups(const CTUDescriptor & CTU) { // Special case for 64x64 CTUs and 32x32 MVP block size mfxI32 extMVPGroupNo = 0; // Construct FOUR 32x32 block groups from the 16x16 block grid std::vector<MVP32x32BlockGroup> mvp32x32BlockGroups; mvp32x32BlockGroups.reserve(4); for (mfxU32 gridIdx = 0; gridIdx < m_mvpBlockGrid.size(); gridIdx += 4) { mvp32x32BlockGroups.emplace_back(BaseBlock(m_mvpBlockGrid[gridIdx].m_AdrX, m_mvpBlockGrid[gridIdx].m_AdrY, MVP_BLOCK_SIZE * 2, MVP_BLOCK_SIZE * 2), gridIdx); } for (const auto& CU : CTU.m_CUVec) { if (CU.m_PredType == INTER_PRED) { // For all the inter PUs constructing a list of 32x32 MVP block groups // that this PU has intersections with for (const auto& PU : CU.m_PUVec) { // Construct a list with all 32x32 MVP block groups which have intersections with current PU std::list<MVP32x32BlockGroup> intersected32x32MVPBlocks; for (const auto& mvp32x32Block : mvp32x32BlockGroups) { if (PU.CheckForIntersect(mvp32x32Block.first)) { intersected32x32MVPBlocks.push_back(mvp32x32Block); } } // Checking the list validity. It should have at least 1 element if (intersected32x32MVPBlocks.empty()) { throw std::string("ERROR: MVMVPProcessor: PutPUAndMVPBlocksIn32x32MVPPoolGroups: Found a PU which doesn't intersect the 32x32 MVP groups grid"); } // Check if there is at least one block which is included in some group // MVP blocks should have no group or be included in a single group auto validGroupMVPBlock = std::find_if(intersected32x32MVPBlocks.begin(), intersected32x32MVPBlocks.end(), [this](const MVP32x32BlockGroup& block32x32) { return m_mvpBlockGrid[block32x32.second].IsAlreadyInGroup(); }); // If it exists, put all MVP blocks intersecting the current PU in this group if (validGroupMVPBlock != intersected32x32MVPBlocks.end()) { mfxI32 firstValidGroupNo = m_mvpBlockGrid[validGroupMVPBlock->second].GetGroupNo(); if (std::any_of(intersected32x32MVPBlocks.begin(), intersected32x32MVPBlocks.end(), [this, firstValidGroupNo](const MVP32x32BlockGroup& block32x32) { return (m_mvpBlockGrid[block32x32.second].IsAlreadyInGroup() && !m_mvpBlockGrid[block32x32.second].IsInGroup(firstValidGroupNo)); })) { throw std::string("ERROR: PutPUAndMVPBlocksIn32x32MVPPoolGroups : Found a pair of MVP blocks intersecting with current PU which are in the different MVP groups"); } else // include all intersecting MVP blocks in the single group { for (MVPBlock& block : m_mvpBlockGrid) { if (std::find_if(intersected32x32MVPBlocks.begin(), intersected32x32MVPBlocks.end(), [this, &block](const MVP32x32BlockGroup& block32x32) { return m_mvpBlockGrid[block32x32.second] == block; }) != intersected32x32MVPBlocks.end()) { block.SetGroup(firstValidGroupNo); } } // The list is valid - set PU pool group no. with the value for MVP blocks m_PUtoMVPPoolGroupMap[PU] = firstValidGroupNo; } } else // Otherwise, put all MVP blocks in the new group { for (MVPBlock& block : m_mvpBlockGrid) { if (std::find_if(intersected32x32MVPBlocks.begin(), intersected32x32MVPBlocks.end(), [this, &block](const MVP32x32BlockGroup& block32x32) { return m_mvpBlockGrid[block32x32.second] == block; }) != intersected32x32MVPBlocks.end()) { block.SetGroup(extMVPGroupNo); } } // The list is valid - set PU pool group no. with the value for MVPs m_PUtoMVPPoolGroupMap[PU] = extMVPGroupNo; ++extMVPGroupNo; } } } } return extMVPGroupNo; } mfxI32 MVMVPProcessor::PutPUAndMVPBlocksInSingleMVPPoolGroup(const CTUDescriptor & CTU) { const mfxI32 extGroupNo = 0; for (MVPBlock& block : m_mvpBlockGrid) { block.SetGroup(extGroupNo); } for (const auto& CU : CTU.m_CUVec) { if (CU.m_PredType == INTER_PRED) { for (const auto& PU : CU.m_PUVec) { m_PUtoMVPPoolGroupMap[PU] = extGroupNo; } } } return 1; } // Fills output mfxExtFeiHevcEncMVPredictors::Data with generated MVP Grid data depending on the m_GenMVPBlockSize value // // frameDescr - MOD frame descriptor. It holds ext buffers void MVMVPProcessor::FillFrameMVPExtBuffer(FrameChangeDescriptor& frameDescr) { ExtendedSurface& surf = *frameDescr.m_frame; mfxExtFeiHevcEncMVPredictors* mvpBuf = reinterpret_cast<mfxExtFeiHevcEncMVPredictors*>(surf.GetBuffer(MFX_EXTBUFF_HEVCFEI_ENC_MV_PRED)); m_DoUseIntra = !!(frameDescr.m_testType & GENERATE_INTRA); switch (m_GenMVPBlockSize) { case 0: // No MVP specified. Left buffer unchanged break; case 1: // MVP for 16x16 blocks // Iterating over all generated blocks for (const auto& block : m_mvpBlockGrid) { PutMVPIntoExtBuffer(block, mvpBuf); } break; case 2: // MVP for 32x32 blocks // Iterating over each upper-left block in the 32x32 group // | 0* 1 | 4* 5 | // | 2 3 | 6 7 | for (std::size_t gridIdx = 0; gridIdx < m_mvpBlockGrid.size(); gridIdx += 4) { PutMVPIntoExtBuffer(m_mvpBlockGrid[gridIdx], mvpBuf); } break; case 3: // MVP for 64x64 blocks // 16x16 blocks marked with X should be the same in the output predictors buffer // ++++++++++++++++++++ // + X + + X + + // +++++++++++++++++ ... // + + + + + // +++++++++++++++++ // + X + + X + + ... // +++++++++++++++++ // + + + + + // +++++++++++++++++ // + ... PutMVPIntoExtBuffer(m_mvpBlockGrid[0], mvpBuf); break; default: break; } } bool MVMVPProcessor::GenValidMVMVPForPU(PUBlock & PU, const FrameChangeDescriptor & frameDescr) { const auto mvpGroupNo = m_PUtoMVPPoolGroupMap.find(PU); if (mvpGroupNo != m_PUtoMVPPoolGroupMap.end()) { if (mvpGroupNo->second < 0) { throw std::string("ERROR: MVMVPProcessor: GenValidMVMVPForPU: Some PU has invalid MVP pool no."); } } else { throw std::string("ERROR: MVMVPProcessor: GenValidMVMVPForPU: Some PU hasn't been included in MVP pool group map"); } // Inter prediction test // Try 100 times max to generate valid references for (mfxU32 i = 0; i < MAX_GEN_MV_ATTEMPTS; ++i) { PUMotionVector mvSW; if (frameDescr.m_testType & GENERATE_MV) { // If GENERATE_MV is specified, generate a vector inside SW; else, leave mvSW a zero vector // Always create mv inside SW; mvp - outside SW mvSW = GenerateMV(frameDescr); } std::vector<PUMotionVector> mvpPoolForPU(m_mvpPools[mvpGroupNo->second]); while (!mvpPoolForPU.empty()) { mfxU32 localMvpIndex = GetRandomGen().GetRandomNumber(0, (mfxI32)mvpPoolForPU.size() - 1); PU.m_MVP = mvpPoolForPU[localMvpIndex]; // Final MV; operator + used here // Important: m_MV inherits refIdx from m_MVP. It is done so because MVP would be written to file if required. // MV is never reported outside. PU.m_MV = PU.m_MVP + mvSW; if (frameDescr.IsNewPUValid(PU)) { // Get index of the MVP applied to this PU from the original MVP generation pool for (mfxU32 originalMvpIndex = 0; originalMvpIndex < MVP_PER_16x16_BLOCK; ++originalMvpIndex) { if (m_mvpPools[mvpGroupNo->second][originalMvpIndex] == PU.m_MVP) { PU.usedMVPPoolNo = mvpGroupNo->second; PU.usedMVPIndex = originalMvpIndex; } } return true; // MV generation for current PU succeeded } else { mvpPoolForPU.erase(mvpPoolForPU.begin() + localMvpIndex); } } } return false; //MV generation for current PU failed } //Attempts to generate MVs for PUs inside the CU and store the information about the blocks occupied //by newly generated PUs in corresponding reference frame descriptors bool MVMVPProcessor::GenValidMVForPU(PUBlock & PU, const FrameChangeDescriptor & frameDescr) { if (!(frameDescr.m_testType & GENERATE_MV)) { return true; //No MVs requested } // Inter prediction test // Try 100 times max to generate valid references for (mfxU32 i = 0; i < MAX_GEN_MV_ATTEMPTS; ++i) { // Always create mv inside SW; mvp - outside SW (if predictors are not required, mvp is zero vector) PUMotionVector mvSW = GenerateMV(frameDescr); PU.m_MVP = PUMotionVector( mfxU8(GetRandomGen().GetRandomNumber(0, std::max(0, mfxU8(frameDescr.m_refDescrList0.size()) - 1))), mfxU8(GetRandomGen().GetRandomNumber(0, std::max(0, mfxU8(frameDescr.m_refDescrList1.size()) - 1))), mfxI16(0), mfxI16(0), mfxI16(0), mfxI16(0)); // Final MV; operator + used here // Important: m_MV inherits refIdx from m_MVP. It is done so because MVP would be written to file if required. // MV is never reported outside. PU.m_MV = PU.m_MVP + mvSW; // Check whether the generated PU is located inside frame boundaries // Check generated PU for intersection with previous PUs pointing to other frames if (frameDescr.IsNewPUValid(PU)) { return true; //MV generation for current PU succeeded } } return false; //MV generation for current PU failed } // Generate Motion Vector Predictor, i.e such a vector that all HW_SEARCH_ELEMENT_SIZE-sized square blocks // inside the CTU shifted by this vector will be located outside their own search windows (which have same // size but are centered each on its own search element block), and the CTU itself is still located // inside the frame // If the frame size is smaller than the search window size, generate MVP with zero spatial coordinates. // Function generates predictors for list 1 only on B frames (not on GPB) // // const CTUDescriptor & CTU - current CTU which should be located inside the frame with predictor applied as MV // const FrameChangeDescriptor & frameChangeDescr - descriptor which contains these fields: // mfxU8 numl0_refs / numl1_refs - current limits on number of active references // mfxU32 surf_width / surf_height - size of current surface PUMotionVector MVMVPProcessor::GenerateMVP(const CTUDescriptor & CTU, const FrameChangeDescriptor & frameChangeDescr) { const auto& numl0_refs = frameChangeDescr.m_refDescrList0; const auto& numl1_refs = frameChangeDescr.m_refDescrList1; bool hasList1 = !numl1_refs.empty(); if (hasList1 && !frameChangeDescr.m_bUseBiDirSW) { throw std::string("ERROR: GenerateMVP: attempted to generate MVPs for a B-frame/GPB using unidirectional search window"); } bool isB = !!(frameChangeDescr.m_frameType & MFX_FRAMETYPE_B); const mfxU32* current_lim = frameChangeDescr.m_bUseBiDirSW ? SKL_SW_LIM_BD : SKL_SW_LIM_OD; mfxU32 x_lim_SW = current_lim[0] / 2; mfxU32 y_lim_SW = current_lim[1] / 2; mfxI32 x_coord[2] = { 0 }; mfxI32 y_coord[2] = { 0 }; // Precomputing min and max possible MVP coordinates so that the MVP points outside SW but inside // the frame (i.e. the CTU with applied MVP should be located outside SW and inside the frame, // if possible) mfxU32 x_min = x_lim_SW + HW_SEARCH_ELEMENT_SIZE / 2; //When determining min absolute shift, one should use //the search element size, not the CTU size. With max //CTU size is still used so that it stays inside the frame mfxU32 x_max_pos = frameChangeDescr.GetFrameCropW() - (CTU.m_BWidth + CTU.m_AdrX); //Max absolute value of MVP coord for positive mfxU32 x_max_neg = CTU.m_AdrX; //and negative coordinates respectively. mfxU32 y_min = y_lim_SW + HW_SEARCH_ELEMENT_SIZE / 2; mfxU32 y_max_pos = frameChangeDescr.GetFrameCropH() - (CTU.m_BWidth + CTU.m_AdrY); mfxU32 y_max_neg = CTU.m_AdrY; //Crop the max coords due to hardware limitations x_max_pos = std::min(x_max_pos, ((mfxU32)((MVMVP_SIZE_LIMIT >> 2) - x_lim_SW))); x_max_neg = std::min(x_max_neg, ((mfxU32)((MVMVP_SIZE_LIMIT >> 2) - x_lim_SW))); y_max_pos = std::min(y_max_pos, ((mfxU32)((MVMVP_SIZE_LIMIT >> 2) - y_lim_SW))); y_max_neg = std::min(y_max_neg, ((mfxU32)((MVMVP_SIZE_LIMIT >> 2) - y_lim_SW))); enum SHIFT { X_POS, X_NEG, Y_POS, Y_NEG }; std::vector<SHIFT> availShifts; availShifts.reserve(4); if (x_min < x_max_pos) availShifts.push_back(X_POS); if (x_min < x_max_neg) availShifts.push_back(X_NEG); if (y_min < y_max_pos) availShifts.push_back(Y_POS); if (y_min < y_max_neg) availShifts.push_back(Y_NEG); if (!availShifts.empty()) { for (mfxI32 i = 0; i < (isB ? 2 : 1); i++) { SHIFT shift = availShifts[GetRandomGen().GetRandomNumber(0, (mfxI32)(availShifts.size() - 1))]; switch (shift) { case X_POS: x_coord[i] = GetRandomMVComponent(x_min, x_max_pos); break; case X_NEG: x_coord[i] = -GetRandomMVComponent(x_min, x_max_neg); break; case Y_POS: y_coord[i] = GetRandomMVComponent(y_min, y_max_pos); break; case Y_NEG: y_coord[i] = -GetRandomMVComponent(y_min, y_max_neg); break; } //The complementary MVP coordinate should be subjected to the HW limit as well if (shift == X_POS || shift == X_NEG) { mfxU32 max_pos_shift_y = std::min(frameChangeDescr.GetFrameCropH() - CTU.m_BHeight - CTU.m_AdrY, (mfxU32)MVMVP_SIZE_LIMIT >> 2); mfxU32 max_neg_shift_y = std::min(CTU.m_AdrY, (mfxU32)MVMVP_SIZE_LIMIT >> 2); y_coord[i] = GetRandomMVComponent(-(mfxI32)max_neg_shift_y, max_pos_shift_y); } else { mfxU32 max_pos_shift_x = std::min(frameChangeDescr.GetFrameCropW() - CTU.m_BWidth - CTU.m_AdrX, (mfxU32)MVMVP_SIZE_LIMIT >> 2); mfxU32 max_neg_shift_x = std::min(CTU.m_AdrX, (mfxU32)MVMVP_SIZE_LIMIT >> 2); x_coord[i] = GetRandomMVComponent(-(mfxI32)max_neg_shift_x, max_pos_shift_x); } } } return PUMotionVector( (mfxI32)!numl0_refs.empty() ? mfxU8(GetRandomGen().GetRandomNumber(0, (mfxI32)numl0_refs.size() - 1)) : 0, (mfxI32)!numl1_refs.empty() ? mfxU8(GetRandomGen().GetRandomNumber(0, (mfxI32)numl1_refs.size() - 1)) : 0, // RefIdx struct x_coord[0], // MV[0].x y_coord[0], // MV[0].y isB ? x_coord[1] : 0, // MV[1].x isB ? y_coord[1] : 0 // MV[1].y ); } // Generates an MV so that a PU_width x PU_height-sized block shifted by this MV // will be located inside(sic!) SW. It doesn't generate refIdx. refIdx is generated in GenerateMVP // Function generates MVs for list 1 only on B frames (not on GPB) // // mfxU32 PU_width/PU_height - size of current PU PUMotionVector MVMVPProcessor::GenerateMV(const FrameChangeDescriptor & frameChangeDescr) { const auto& numl1_refs = frameChangeDescr.m_refDescrList1; bool hasList1 = !numl1_refs.empty(); if (hasList1 && !frameChangeDescr.m_bUseBiDirSW) { throw std::string("ERROR: GenerateMV: attempted to generate MVs for a B-frame/GPB using unidirectional search window"); } bool isB = !!(frameChangeDescr.m_frameType & MFX_FRAMETYPE_B); const mfxU32* current_lim = frameChangeDescr.m_bUseBiDirSW ? SKL_SW_LIM_BD : SKL_SW_LIM_OD; // Just half of current SW width / height mfxI32 x_lim = 0, y_lim = 0; constexpr mfxU32 searchElementWidth = HW_SEARCH_ELEMENT_SIZE; constexpr mfxU32 searchElementHeight = HW_SEARCH_ELEMENT_SIZE; //Leave limits at zero if PU size exceeds the search window if (current_lim[0] >= searchElementWidth && current_lim[1] >= searchElementHeight) { x_lim = (current_lim[0] - searchElementWidth) / 2; y_lim = (current_lim[1] - searchElementHeight) / 2; } // Using RVO here return PUMotionVector( 0, 0, // RefIdx struct GetRandomMVComponent(-x_lim, x_lim), // MV[0].x GetRandomMVComponent(-y_lim, y_lim), // MV[0].y isB ? GetRandomMVComponent(-x_lim, x_lim) : 0, // MV[1].x isB ? GetRandomMVComponent(-y_lim, y_lim) : 0 // MV[1].y ); } // Randomly generates single MV-component within [lower; upper] accordigly to the sub pixel precision mode // Where lower and upper given in full-pixel units. // Output component is in quarter-pixel units. // // { a = lower * 4 } // { b = upper * 4 } // // [a * # * a+1 * # * a+2 ... b-2 * # * b-1 * # * b] // For mode 0: only full-pixels a, a+1, ... b-2, b-1, b are allowed // For mode 1: full and half-pixels # are allowed // For mode 3: every quarter-pixel value is allowed mfxI32 MVMVPProcessor::GetRandomMVComponent(mfxI32 lower, mfxI32 upper) { ASGRandomGenerator& randomGen = GetRandomGen(); switch (m_SubPelMode) { case 0: return 4 * lower + randomGen.GetRandomNumber(0, upper - lower) * 4; case 1: return 4 * lower + randomGen.GetRandomNumber(0, 2 * (upper - lower)) * 2; case 3: return randomGen.GetRandomNumber(4 * lower, 4 * upper); default: throw std::string("ERROR: MVMVPProcessor: GetRandomMVComponent: Incorrect m_SubPelMode used"); } } mfxU32 MVMVPProcessor::CalculateOffsetInMVPredictorsBuffer(mfxU32 bufferPitch, const MVPBlock & mvpBlock) { // Calculating a no. of 32x32 block corresponding to left upper pixel of the CTU MVP grid // In sum below: first addendum is offset by vertical axis, second addendum is offset by horizontal axis mfxU32 offsetBig = (bufferPitch / 2) * (mvpBlock.m_AdrY / (2 * MVP_BLOCK_SIZE)) + (mvpBlock.m_AdrX / (2 * MVP_BLOCK_SIZE)); // Calculating a postion for 16x16 block inside parent 32x32 block mfxU32 offsetSmall = 2 * ((mvpBlock.m_AdrY % (2 * MVP_BLOCK_SIZE)) / MVP_BLOCK_SIZE) + ((mvpBlock.m_AdrX % (2 * MVP_BLOCK_SIZE)) / MVP_BLOCK_SIZE); return 4 * offsetBig + offsetSmall; } void MVMVPProcessor::PutMVPIntoExtBuffer(const MVPBlock& mvpBlock, mfxExtFeiHevcEncMVPredictors* outputMVPBuf) { if (!outputMVPBuf) { throw std::string("ERROR: MVMVPProcessor: PutMVPIntoExtBuffer: Output mfxExtFeiHevcEncMVPredictors buffer is null"); } mfxU32 offset = CalculateOffsetInMVPredictorsBuffer(outputMVPBuf->Pitch, mvpBlock); mfxFeiHevcEncMVPredictors& actualPredictor = outputMVPBuf->Data[offset]; mfxI32 mvpGroupNo = mvpBlock.GetGroupNo(); // In case of INTRAxINTER test some MVP blocks // may not intersect with PUs inside CTU // Otherwise, all MVP blocks should be assigned with a valid group no. if (mvpGroupNo < 0) { if (m_DoUseIntra) { // For such intra MVP block filling corresponding element in the buffer with ignored values for (mfxU32 mvpIdx = 0; mvpIdx < MVP_PER_16x16_BLOCK; mvpIdx++) { actualPredictor.MV[mvpIdx][0].x = actualPredictor.MV[mvpIdx][0].y = (mfxI16)0x8000; actualPredictor.MV[mvpIdx][1].x = actualPredictor.MV[mvpIdx][1].y = (mfxI16)0x8000; actualPredictor.RefIdx[mvpIdx].RefL0 = (mfxU8)0xf; actualPredictor.RefIdx[mvpIdx].RefL1 = (mfxU8)0xf; } // Nevertheless, setting BlockSize appropriately actualPredictor.BlockSize = m_GenMVPBlockSize; return; } // Otherwise, something definitely went wrong throw std::string("ERROR: PutMVPIntoExtBuffer: Some MVP block has invalid MVP pool no."); } for (mfxU32 mvpIdx = 0; mvpIdx < MVP_PER_16x16_BLOCK; mvpIdx++) { const auto& genMVPred = m_mvpPools[mvpGroupNo][mvpIdx]; if (genMVPred.CheckMVPExceedsSizeLimits()) { throw std::string("ERROR: PutMVPIntoExtBuffer: generated MVP size exceeds hardware limit"); } actualPredictor.RefIdx[mvpIdx].RefL0 = genMVPred.RefIdx.RefL0; actualPredictor.RefIdx[mvpIdx].RefL1 = genMVPred.RefIdx.RefL1; actualPredictor.MV[mvpIdx][0] = genMVPred.MV[0]; actualPredictor.MV[mvpIdx][1] = genMVPred.MV[1]; } // Assuming that, m_GenMVPBlockSize has correct value actualPredictor.BlockSize = m_GenMVPBlockSize; // Special case for 64x64 blocks - copying initialized data to the neighbour blocks if (m_GenMVPBlockSize == 3) { if (outputMVPBuf->Pitch > 0) { outputMVPBuf->Data[offset + 4] = actualPredictor; outputMVPBuf->Data[offset + outputMVPBuf->Pitch] = actualPredictor; outputMVPBuf->Data[offset + outputMVPBuf->Pitch + 4] = actualPredictor; } else { throw std::string("ERROR: PutMVPIntoExtBuffer: mfxExtFeiHevcEncMVPredictors have zero pitch"); } } } void MVMVPProcessor::GetMVPPools(std::vector<std::vector<PUMotionVector>>& outMVPPools) { outMVPPools = m_mvpPools; } #endif // MFX_VERSION
1
0.983849
1
0.983849
game-dev
MEDIA
0.716295
game-dev
0.888448
1
0.888448
OpenXRay/xray-15
12,110
cs/sdk/3d_sdk/maya/ver-8.5/devkit/plug-ins/splitUVCmd.cpp
//- // ========================================================================== // Copyright (C) 1995 - 2006 Autodesk, Inc. and/or its licensors. All // rights reserved. // // The coded instructions, statements, computer programs, and/or related // material (collectively the "Data") in these files contain unpublished // information proprietary to Autodesk, Inc. ("Autodesk") and/or its // licensors, which is protected by U.S. and Canadian federal copyright // law and by international treaties. // // The Data is provided for use exclusively by You. You have the right // to use, modify, and incorporate this Data into other products for // purposes authorized by the Autodesk software license agreement, // without fee. // // The copyright notices in the Software and this entire statement, // including the above license grant, this restriction and the // following disclaimer, must be included in all copies of the // Software, in whole or in part, and all derivative works of // the Software, unless such copies or derivative works are solely // in the form of machine-executable object code generated by a // source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. // AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED // WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF // NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR // PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR // TRADE PRACTICE. IN NO EVENT WILL AUTODESK AND/OR ITS LICENSORS // BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL, // DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK // AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY // OR PROBABILITY OF SUCH DAMAGES. // // ========================================================================== //+ // // File: splitUVCmd.cpp // // MEL Command: splitUV // // Author: Lonnie Li // #include "splitUVCmd.h" #include "splitUVNode.h" // Function Sets // #include <maya/MFnDependencyNode.h> #include <maya/MFnMesh.h> #include <maya/MFnSingleIndexedComponent.h> // Iterators // #include <maya/MItSelectionList.h> #include <maya/MItMeshPolygon.h> // General Includes // #include <maya/MGlobal.h> #include <maya/MSelectionList.h> #include <maya/MPlug.h> #include <maya/MIOStream.h> // Status Checking Macro - MCheckStatus (Debugging tool) // #define MCheckStatus(status,message) \ if( MS::kSuccess != status ) { \ cerr << message << "\n"; \ return status; \ } splitUV::splitUV() // // Description: // splitUV constructor // {} splitUV::~splitUV() // // Description: // splitUV destructor // {} void* splitUV::creator() // // Description: // this method exists to give Maya a way to create new objects // of this type. // // Return Value: // a new object of this type // { return new splitUV(); } bool splitUV::isUndoable() const // // Description: // this method tells Maya this command is undoable. It is added to the // undo queue if it is. // // Return Value: // true if this command is undoable. // { return true; } MStatus splitUV::doIt( const MArgList& ) // // Description: // implements the MEL splitUV command. // // Arguments: // args - the argument list that was passes to the command from MEL // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { MStatus status; // Parse the selection list for objects with selected UV components. // To simplify things, we only take the first object that we find with // selected UVs and operate on that object alone. // // All other objects are ignored and return warning messages indicating // this limitation. // MSelectionList selList; MGlobal::getActiveSelectionList( selList ); MItSelectionList selListIter( selList ); selListIter.setFilter( MFn::kMesh ); // The splitUV node only accepts a component list input, so we build // a component list using MFnComponentListData. // // MIntArrays could also be passed into the node to represent the uvIds, // but are less storage efficient than component lists, since consecutive // components are bundled into a single entry in component lists. // MFnComponentListData compListFn; compListFn.create(); bool found = false; bool foundMultiple = false; for( ; !selListIter.isDone(); selListIter.next() ) { MDagPath dagPath; MObject component; selListIter.getDagPath( dagPath, component ); // Check for selected UV components // if( component.apiType() == MFn::kMeshMapComponent ) { if( !found ) { // The variable 'component' holds all selected components on the selected // object, thus only a single call to MFnComponentListData::add() is needed // to store the selected components for a given object. // compListFn.add( component ); // Copy the component list created by MFnComponentListData into our local // component list MObject member. // fComponentList = compListFn.object(); // Locally store the actual uvIds of the selected UVs so that this command // can directly modify the mesh in the case when there is no history and // history is turned off. // MFnSingleIndexedComponent compFn( component ); compFn.getElements( fSelUVs ); // Ensure that this DAG path will point to the shape of our object. // Set the DAG path for the polyModifierCmd. // dagPath.extendToShape(); setMeshNode( dagPath ); found = true; } else { // Break once we have found a multiple object holding selected UVs, since // we are not interested in how many multiple objects there are, only // the fact that there are multiple objects. // foundMultiple = true; break; } } } if( foundMultiple ) { displayWarning("Found more than one object with selected UVs - Only operating on first found object."); } // Initialize the polyModifierCmd node type - mesh node already set // setModifierNodeType( splitUVNode::id ); if( found ) { if( validateUVs() ) { // Now, pass control over to the polyModifierCmd::doModifyPoly() method // to handle the operation. // status = doModifyPoly(); if( status == MS::kSuccess ) { setResult( "splitUV command succeeded!" ); } else { displayError( "splitUV command failed!" ); } } else { displayError( "splitUV command failed: Selected UVs are not splittable" ); status = MS::kFailure; } } else { displayError( "splitUV command failed: Unable to find selected UVs" ); status = MS::kFailure; } return status; } MStatus splitUV::redoIt() // // Description: // Implements redo for the MEL splitUV command. // // This method is called when the user has undone a command of this type // and then redoes it. No arguments are passed in as all of the necessary // information is cached by the doIt method. // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - redoIt failed. this is a serious problem that will // likely cause the undo queue to be purged // { MStatus status; // Process the polyModifierCmd // status = redoModifyPoly(); if( status == MS::kSuccess ) { setResult( "splitUV command succeeded!" ); } else { displayError( "splitUV command failed!" ); } return status; } MStatus splitUV::undoIt() // // Description: // implements undo for the MEL splitUV command. // // This method is called to undo a previous command of this type. The // system should be returned to the exact state that it was it previous // to this command being executed. That includes the selection state. // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - redoIt failed. this is a serious problem that will // likely cause the undo queue to be purged // { MStatus status; status = undoModifyPoly(); if( status == MS::kSuccess ) { setResult( "splitUV undo succeeded!" ); } else { setResult( "splitUV undo failed!" ); } return status; } MStatus splitUV::initModifierNode( MObject modifierNode ) { MStatus status; // We need to tell the splitUV node which UVs to operate on. By overriding // the polyModifierCmd::initModifierNode() method, we can insert our own // modifierNode initialization code. // MFnDependencyNode depNodeFn( modifierNode ); MObject uvListAttr; uvListAttr = depNodeFn.attribute( "inputComponents" ); // Pass the component list down to the splitUV node // MPlug uvListPlug( modifierNode, uvListAttr ); status = uvListPlug.setValue( fComponentList ); return status; } MStatus splitUV::directModifier( MObject mesh ) { MStatus status; fSplitUVFactory.setMesh( mesh ); fSplitUVFactory.setUVIds( fSelUVs ); // Now, perform the splitUV // status = fSplitUVFactory.doIt(); return status; } // Private Methods // bool splitUV::validateUVs() // // Description: // // Validate the UVs for the splitUV operation. UVs are valid only if they are shared // by more than one face. While the splitUVNode is smart enough to not process the // split if a UV is not splittable, a splitUV node is still created by the polyModifierCmd. // So call this method to validate the UVs before calling doModifyPoly(). // // validateUVs() will return true so long as there is at least one valid UV. It will // also prune out any invalid UVs from both the component list and UVId array. // { // Get the mesh that we are operating on // MDagPath dagPath = getMeshNode(); MObject mesh = dagPath.node(); // Get the number of faces sharing the selected UVs // MFnMesh meshFn( mesh ); MItMeshPolygon polyIter( mesh ); MIntArray selUVFaceCountArray; int i; int j; int count = 0; int selUVsCount = fSelUVs.length(); for( i = 0; i < selUVsCount; i++ ) { for( ; !polyIter.isDone(); polyIter.next() ) { if( polyIter.hasUVs() ) { int polyVertCount = polyIter.polygonVertexCount(); for( j = 0; j < polyVertCount; j++ ) { int UVIndex = 0; polyIter.getUVIndex(j, UVIndex); if( UVIndex == fSelUVs[i] ) { count++; break; } } } } selUVFaceCountArray.append(count); } // Now, check to make sure that at least one UV is being shared by more than one // face. So long as we have one UV that we can operate on, we should proceed and let // the splitUVNode ignore the UVs which are only shared by one face. // bool isValid = false; MIntArray validUVIndices; for( i = 0; i < selUVsCount; i++ ) { if( selUVFaceCountArray[i] > 1 ) { isValid = true; validUVIndices.append(i); } } if( isValid ) { pruneUVs( validUVIndices ); } return isValid; } MStatus splitUV::pruneUVs( MIntArray& validUVIndices ) // // Description: // // This method will remove any invalid UVIds from the component list and UVId array. // The benefit of this is to reduce the amount of extra processing that the node would // have to perform. It will result in less iterations through the mesh as there are // less UVs to search for. // { MStatus status; unsigned i; MIntArray validUVIds; for( i = 0; i < validUVIndices.length(); i++ ) { int uvIndex = validUVIndices[i]; validUVIds.append( fSelUVs[uvIndex] ); } // Replace the local int array of UVIds // fSelUVs.clear(); fSelUVs = validUVIds; // Build the list of valid components // MFnSingleIndexedComponent compFn; compFn.create( MFn::kMeshMapComponent, &status ); MCheckStatus( status, "compFn.create( MFn::kMeshMapComponent )" ); status = compFn.addElements( validUVIds ); MCheckStatus( status, "compFn.addElements( validUVIds )" ); MObject component = compFn.object(); // Replace the component list // MFnComponentListData compListFn; compListFn.create(); status = compListFn.add( component ); MCheckStatus( status, "compListFn.add( component )" ); fComponentList = compListFn.object(); return status; }
1
0.919001
1
0.919001
game-dev
MEDIA
0.227529
game-dev
0.936828
1
0.936828
Isidorsson/Eluna-scripts
21,977
AIO Scripts/GameMasterSystem/GameMasterUI/Client/03_Systems/02_ContextMenus/GMClient_ItemContextMenu.lua
local AIO = AIO or require("AIO") if AIO.AddAddon() then return -- Exit if on server end -- Get module references local PlayerInventory = _G.PlayerInventory if not PlayerInventory then print("[ERROR] PlayerInventory namespace not found! Check load order.") return end -- Debug: Confirm this file is loading print("[PlayerInventory] ItemContextMenu module loading...") local GameMasterSystem = _G.GameMasterSystem local GMConfig = _G.GMConfig -- ================================================================================ -- ITEM CONTEXT MENU FUNCTIONS -- This module provides item-specific context menu functionality including: -- - Empty slot context menus -- - Item action context menus -- - Item management dialogs -- ================================================================================ -- Show context menu for empty slots function PlayerInventory.showEmptySlotContextMenu(slot, isEquipment) -- Close any existing context menu first PlayerInventory.closeContextMenu() local menuItems = { { text = "Empty Slot Actions", isTitle = true } } -- Add separator table.insert(menuItems, { text = "", disabled = true, notCheckable = true }) -- Main action - search and add items table.insert(menuItems, { text = "Search Items...", icon = "Interface\\Icons\\INV_Misc_Spyglass_03", func = function() -- Determine slot restrictions for equipment local slotRestriction = nil if isEquipment and slot.slotId then slotRestriction = slot.slotId end -- Show item search dialog if PlayerInventory.showItemSearchDialog then PlayerInventory.showItemSearchDialog(slot, isEquipment) else print("|cffff0000Item search dialog not yet implemented|r") end end }) -- Quick add common items submenu local quickAddItems = {} if isEquipment then -- Add equipment-appropriate quick items based on slot if slot.slotId == 15 then -- Main hand table.insert(quickAddItems, { text = "Shadowmourne", itemId = 49623 }) table.insert(quickAddItems, { text = "Val'anyr", itemId = 46017 }) table.insert(quickAddItems, { text = "Thunderfury", itemId = 19019 }) elseif slot.slotId == 4 then -- Chest table.insert(quickAddItems, { text = "Sanctified Ymirjar Lord's Battleplate", itemId = 51227 }) table.insert(quickAddItems, { text = "Sanctified Frost Witch's Tunic", itemId = 51200 }) elseif slot.slotId == 0 then -- Head table.insert(quickAddItems, { text = "Sanctified Ymirjar Lord's Helmet", itemId = 51226 }) table.insert(quickAddItems, { text = "Sanctified Frost Witch's Helm", itemId = 51202 }) end else -- Add common consumables for inventory table.insert(quickAddItems, { text = "Flask of Endless Rage", itemId = 46377 }) table.insert(quickAddItems, { text = "Potion of Speed", itemId = 40211 }) table.insert(quickAddItems, { text = "Fish Feast", itemId = 43015 }) table.insert(quickAddItems, { text = "Heavy Frostweave Bandage", itemId = 34722 }) table.insert(quickAddItems, { text = "Runic Mana Potion", itemId = 33448 }) end -- Create quick add submenu if #quickAddItems > 0 then local quickAddMenu = {} for _, item in ipairs(quickAddItems) do table.insert(quickAddMenu, { text = item.text, icon = "Interface\\Icons\\INV_Misc_QuestionMark", -- Default icon func = function() -- Add item to the specific slot local targetBag = slot.bagId or 0 local targetSlot = slot.slotId or 0 if isEquipment then -- For equipment, equip directly AIO.Handle("GameMasterSystem", "equipItemById", PlayerInventory.currentPlayerName, item.itemId, slot.slotId) print(string.format("Equipping %s to slot %d", item.text, slot.slotId)) else -- For inventory, add to specific bag/slot AIO.Handle("GameMasterSystem", "addItemToSpecificSlot", PlayerInventory.currentPlayerName, item.itemId, 1, targetBag, targetSlot) print(string.format("Adding %s to bag %d slot %d", item.text, targetBag, targetSlot)) end -- Server will send refreshInventoryDisplay to update the UI end }) end table.insert(menuItems, { text = "Quick Add", icon = "Interface\\Icons\\INV_Misc_Gift_01", hasArrow = true, menuList = quickAddMenu }) end -- Add custom item by ID table.insert(menuItems, { text = "Add by Item ID...", icon = "Interface\\Icons\\INV_Misc_Note_01", func = function() PlayerInventory.showAddItemByIdDialog(slot, isEquipment) end }) -- Store the menu reference PlayerInventory.currentContextMenu = PlayerInventory.showContextMenuWithSmartPositioning(menuItems, slot) end -- Show context menu for inventory items function PlayerInventory.showItemContextMenu(slot, itemData, isEquipment) if not itemData or not itemData.entry then return end -- Debug: Confirm real function is being called if GMConfig and GMConfig.config and GMConfig.config.debug then print("[PlayerInventory] Real showItemContextMenu called!") end -- Debug: Check itemData contents for custom bags if GMConfig.config.debug and itemData.bag and itemData.bag >= 1500 then print(string.format("[PlayerInventory] Context menu for custom bag item: %s", itemData.name or "Unknown")) print(string.format("[PlayerInventory] Bag: %d, Slot: %d", itemData.bag, itemData.slot or 0)) print(string.format("[PlayerInventory] itemGuid: %s", tostring(itemData.itemGuid))) print(string.format("[PlayerInventory] All fields: entry=%s, count=%s, quality=%s", tostring(itemData.entry), tostring(itemData.count), tostring(itemData.quality))) end -- Close any existing context menu first PlayerInventory.closeContextMenu() local menuItems = { { text = string.format("%s Actions", isEquipment and "Equipment" or "Item"), isTitle = true }, { text = string.format("ID: %d | %s", itemData.entry, itemData.name or "Unknown"), isTitle = true, notCheckable = true } } -- Add separator table.insert(menuItems, { text = "", disabled = true, notCheckable = true }) if isEquipment then -- Equipment-specific actions table.insert(menuItems, { text = "Unequip Item", icon = "Interface\\Icons\\INV_Misc_Bag_08", func = function() AIO.Handle("GameMasterSystem", "unequipPlayerItem", PlayerInventory.currentPlayerName, slot.slotId) print(string.format("Unequipping item from slot %d", slot.slotId)) end }) table.insert(menuItems, { text = "Repair Item", icon = "Interface\\Icons\\Trade_BlackSmithing", func = function() AIO.Handle("GameMasterSystem", "repairPlayerItem", PlayerInventory.currentPlayerName, slot.slotId, true) print("Repairing item...") end }) else -- Inventory item actions if itemData.equipable then table.insert(menuItems, { text = "Equip Item", icon = "Interface\\Icons\\INV_Chest_Chain", func = function() AIO.Handle("GameMasterSystem", "equipPlayerItem", PlayerInventory.currentPlayerName, itemData.bag, itemData.slot) print("Equipping item...") end }) end if itemData.count and itemData.count > 1 then table.insert(menuItems, { text = "Split Stack", icon = "Interface\\Icons\\INV_Misc_Coin_01", func = function() PlayerInventory.showSplitStackDialog(itemData) end }) table.insert(menuItems, { text = "Modify Stack Count", icon = "Interface\\Icons\\INV_Misc_Note_01", func = function() PlayerInventory.showModifyStackDialog(itemData) end }) end end -- Common actions for both equipment and inventory table.insert(menuItems, { text = "", disabled = true, notCheckable = true }) -- Separator -- Enchantment submenu table.insert(menuItems, { text = "Enchantments", icon = "Interface\\Icons\\INV_Enchant_DustPrismatic", hasArrow = true, menuList = PlayerInventory.createEnchantmentMenu(itemData, isEquipment, slot) }) table.insert(menuItems, { text = "Duplicate Item", icon = "Interface\\Icons\\INV_Misc_Gift_01", func = function() local count = itemData.count or 1 AIO.Handle("GameMasterSystem", "duplicatePlayerItem", PlayerInventory.currentPlayerName, itemData.entry, count) print(string.format("Duplicating %dx %s", count, itemData.name or "item")) end }) -- Add More submenu with target selection local _, _, _, _, _, _, _, itemStackCount = GetItemInfo(itemData.entry) local maxStack = itemStackCount or 20 -- Default to 20 if not found -- Get self name and current player name local selfName = UnitName("player") local targetName = PlayerInventory.currentPlayerName local isSelf = (selfName == targetName) -- Helper function to create add options for a target local function createAddOptions(target) local options = { { text = "Add x1", icon = "Interface\\Icons\\INV_Misc_Coin_01", func = function() AIO.Handle("GameMasterSystem", "addItemToPlayer", target, itemData.entry, 1) print(string.format("Adding 1x %s to %s", itemData.name or "item", target)) PlayerInventory.closeContextMenu() end }, { text = string.format("Add Stack (x%d)", maxStack), icon = "Interface\\Icons\\INV_Misc_Coin_02", func = function() AIO.Handle("GameMasterSystem", "addItemToPlayer", target, itemData.entry, maxStack) print(string.format("Adding %dx %s to %s", maxStack, itemData.name or "item", target)) PlayerInventory.closeContextMenu() end } } -- Add custom amount option table.insert(options, { text = "", disabled = true, notCheckable = true }) -- Separator table.insert(options, { text = "Custom Amount...", icon = "Interface\\Icons\\INV_Misc_Note_01", func = function() PlayerInventory.showAddItemDialog(itemData, target) end }) return options end -- Build the Add More menu structure local addMoreMenuItems = {} if isSelf then -- If viewing own inventory, just show direct options addMoreMenuItems = createAddOptions(selfName) else -- If viewing another player's inventory, show both options table.insert(addMoreMenuItems, { text = "Add to Self", icon = "Interface\\Icons\\INV_Misc_Gift_02", hasArrow = true, menuList = createAddOptions(selfName) }) table.insert(addMoreMenuItems, { text = string.format("Add to %s", targetName or "Player"), icon = "Interface\\Icons\\INV_Misc_Gift_01", hasArrow = true, menuList = createAddOptions(targetName) }) end table.insert(menuItems, { text = "Add More", icon = "Interface\\Icons\\Spell_ChargePositive", hasArrow = true, menuList = addMoreMenuItems }) table.insert(menuItems, { text = "Mail to Player", icon = "Interface\\Icons\\INV_Letter_01", func = function() PlayerInventory.showMailItemDialog(itemData) end }) table.insert(menuItems, { text = "View Stats", icon = "Interface\\Icons\\INV_Misc_Note_02", func = function() PlayerInventory.showItemStatsDialog(itemData) end }) -- Add separator before delete table.insert(menuItems, { text = "", disabled = true, notCheckable = true }) -- Delete action (last item, with warning color) table.insert(menuItems, { text = "|cffff0000Delete Item|r", icon = "Interface\\Icons\\INV_Misc_Bomb_02", func = function() PlayerInventory.showDeleteConfirmDialog(itemData, isEquipment, slot) end }) -- Store the menu reference PlayerInventory.currentContextMenu = PlayerInventory.showContextMenuWithSmartPositioning(menuItems, slot) end -- Dialog for adding item by ID to empty slot function PlayerInventory.showAddItemByIdDialog(slot, isEquipment) local dialog = PlayerInventory.CreateInputDialog({ title = "Add Item by ID", message = isEquipment and string.format("Enter item ID to equip in %s slot:", PlayerInventory.INVENTORY_CONFIG.EQUIPMENT_SLOTS[slot.slotId] or "equipment") or -- Display 1-based slot number to user (internal is 0-based) string.format("Enter item ID to add to bag %d, slot %d:", slot.bagId or 0, (slot.slotId or 0) + 1), placeholder = "Enter item ID...", numeric = true, buttons = { { text = "Add", onClick = function(dialog, inputText) local itemId = tonumber(inputText) if itemId and itemId > 0 then if isEquipment then -- For equipment, equip directly AIO.Handle("GameMasterSystem", "equipItemById", PlayerInventory.currentPlayerName, itemId, slot.slotId) print(string.format("Equipping item %d to slot %d", itemId, slot.slotId)) else -- For inventory, add to specific bag/slot AIO.Handle("GameMasterSystem", "addItemToSpecificSlot", PlayerInventory.currentPlayerName, itemId, 1, slot.bagId or 0, slot.slotId or 0) print(string.format("Adding item %d to bag %d slot %d", itemId, slot.bagId or 0, slot.slotId or 0)) end dialog:Hide() -- Server will send refreshInventoryDisplay to update the UI else print("|cffff0000Invalid item ID!|r") end end }, { text = "Cancel", onClick = function(dialog) dialog:Hide() end } } }) PlayerInventory.closeContextMenu() dialog:Show() end -- ================================================================================ -- FORWARD DECLARATIONS FOR DIALOGS -- These functions are implemented in other modules but referenced here -- ================================================================================ -- Forward declaration for Add Item dialog if not PlayerInventory.showAddItemDialog then PlayerInventory.showAddItemDialog = function(itemData, targetPlayer) -- Use the target player if provided, otherwise fall back to current player local target = targetPlayer or PlayerInventory.currentPlayerName -- Use the CreateInputDialog helper function local dialog = PlayerInventory.CreateInputDialog({ title = "Add More Items", message = string.format("How many %s to add to %s?", itemData.name or "items", target), placeholder = "Enter amount...", numeric = true, buttons = { { text = "Add", onClick = function(dialog, inputText) local amount = tonumber(inputText) if amount and amount > 0 then AIO.Handle("GameMasterSystem", "addItemToPlayer", target, itemData.entry, amount) print(string.format("Adding %dx %s to %s", amount, itemData.name or "item", target)) dialog:Hide() else print("|cffff0000Invalid amount!|r") end end }, { text = "Cancel", onClick = function(dialog) dialog:Hide() end } } }) PlayerInventory.closeContextMenu() dialog:Show() end end -- Forward declaration for Delete Confirm dialog if not PlayerInventory.showDeleteConfirmDialog then PlayerInventory.showDeleteConfirmDialog = function(itemData, isEquipment, slot) -- Use CreateStyledDialog for the confirmation local dialog = CreateStyledDialog({ title = "|cffff0000Delete Item|r", message = string.format( "|cffff0000WARNING: This action cannot be undone!|r\n\n" .. "Are you sure you want to delete:\n" .. "|cffffff00%s|r x%d?", itemData.name or "Unknown Item", itemData.count or 1 ), buttons = { { text = "|cffff0000Delete|r", callback = function() if isEquipment then print(string.format("[DEBUG] Deleting equipped item at slot %d", slot.slotId)) AIO.Handle("GameMasterSystem", "deleteEquippedItem", PlayerInventory.currentPlayerName, slot.slotId) else -- Debug print to check bag and slot values print(string.format("[DEBUG] Deleting inventory item: bag=%s, slot=%s", tostring(itemData.bag), tostring(itemData.slot))) -- Check if bag and slot exist if not itemData.bag or not itemData.slot then print("|cffff0000ERROR: Missing bag or slot information for item!|r") print("[DEBUG] ItemData contents:") for k, v in pairs(itemData) do print(string.format(" %s = %s", tostring(k), tostring(v))) end return end AIO.Handle("GameMasterSystem", "deleteInventoryItem", PlayerInventory.currentPlayerName, itemData.bag, itemData.slot) end print(string.format("|cffff0000Deleting: %s|r", itemData.name or "item")) end }, { text = "Cancel", callback = function() end -- Dialog will auto-hide } } }) PlayerInventory.closeContextMenu() dialog:Show() end end -- Forward declaration for Mail Item dialog if not PlayerInventory.showMailItemDialog then PlayerInventory.showMailItemDialog = function(itemData) -- Use the GameMasterSystem mail dialog with the item pre-populated if GameMasterSystem and GameMasterSystem.OpenMailDialog then -- Prepare item data for the mail dialog local itemToMail = { id = itemData.entry, icon = itemData.icon or itemData.texture, count = itemData.count or 1, quality = itemData.quality, name = itemData.name, link = itemData.link } -- Mark that mail dialog is being opened from inventory modal if PlayerInventory.currentModal then PlayerInventory.currentModal.isMailDialogOpen = true end -- Open mail dialog with the item pre-attached local mailFrame = GameMasterSystem.OpenMailDialog(PlayerInventory.currentPlayerName, itemToMail, true) -- true = from inventory -- Store reference to mail frame if needed if PlayerInventory.currentModal and mailFrame then PlayerInventory.currentModal.mailFrame = mailFrame end else print("|cffff0000Mail system not available|r") end end end -- Debug message if GMConfig and GMConfig.config and GMConfig.config.debug then -- print("[PlayerInventory] Item context menu module loaded") end -- Debug message -- print('[PlayerInventory] ItemContextMenu module fully loaded with showItemContextMenu function')
1
0.857257
1
0.857257
game-dev
MEDIA
0.944472
game-dev
0.890016
1
0.890016
gametutorials/tutorials
4,275
Win32/2D RPG Part1/Player.h
#ifndef _PLAYER_H #define _PLAYER_H // Include the main header file #include "main.h" // This is our starting position for our player on the map const int kPlayerStartX = 10; const int kPlayerStartY = 10; // These are the images for our game characters in the game const char kPlayerImage[] = "Npcs\\Player.bmp"; const char kTrendorImage[] = "Npcs\\Trendor.bmp"; // This is the direction constants that we use for moving the character enum eDirections { kUp = 0, kDown, kLeft, kRight }; // This stores the constants for the types of items to equip enum eEquipment { kEqHead = 0, kEqChest, kEqWeapon, kEqFeet }; // This is our player class class CPlayer { public: // The constructor and deconstructor CPlayer(); ~CPlayer(); // This inits the player with an image and a position void Init(HBITMAP image, int x, int y); // This draws the player to the screen void Draw(); // This moves the player according to the desired direction (kUp, kDown, kLeft, kRight) bool Move(int direction); // This restores the players previous position void MovePlayerBack() { m_position = m_lastPosition; } // These functions set the player's data void SetName(char *szPlayerName) { strcpy(m_szName, szPlayerName); } void SetHealth(int playerHealth) { m_health = playerHealth; } void SetHealthMax(int maxHealth) { m_healthMax = maxHealth; } void SetStrength(int playerStrength) { m_strength = playerStrength; } void SetProtection(int protection) { m_protection = protection; } void SetExperience(int experience) { m_experience = experience; } void SetLevel(int level) { m_level = level; } void SetGold(int gold) { m_gold = gold; } // These function retrieve info about the player int GetStrength() { return m_strength; } int GetHealth() { return m_health; } int GetHealthMax() { return m_healthMax; } int GetProtection() { return m_protection; } int GetExperience() { return m_experience; } int GetLevel() { return m_level; } int GetGold() { return m_gold; } char *GetName() { return m_szName; } // These get and set the player's image HBITMAP GetImage() { return m_image; } void SetImage(HBITMAP newImage) { m_image = newImage; } // These get and set the players position POINT GetPosition() { return m_position; } void SetPosition(POINT newPosition) { m_position = newPosition; } // These get and set the players last position POINT GetLastPosition() { return m_lastPosition; } void SetLastPosition(POINT lastPosition) { m_lastPosition = lastPosition; } // This tells us if the player is still alive or not bool IsAlive() { return (m_health > 0); } private: HBITMAP m_image; // The player's image POINT m_position; // The player's position POINT m_lastPosition; // The player's last position char m_szName[kMaxNameLen]; // The player's name int m_health; // The player's current health int m_strength; // The player's strength int m_protection; // The player's protection int m_experience; // The player's experience points int m_level; // The player's level int m_gold; // The player's gold int m_healthMax; // The player's max health CItem *m_pHead; // The current equipment on the player's head CItem *m_pChest; // The current equipment on the player's chest CItem *m_pWeapon; // The current player's weapon CItem *m_pFeet; // The current equipment on the player's feet vector<CPlayer*> m_vParty; // The list of players in your party vector<CItem> m_vItems; // The inventory list for the player }; #endif //////////////////////////////////////////////////////////////////// // // *Quick Notes* // // This file holds the CPlayer class for our player. We also put some // enum values for the player's directions of movement. Not all of the // variables in the class are being used, but we will put them there // to give you an idea of what will be used later. We still have some // functions that we need to add for saving and loading, as well as for // attacking monsters. // // // Ben Humphrey (DigiBen) // Game Programmer // DigiBen@GameTutorials.com // Co-Web Host of www.GameTutorials.com // // 2000-2005 GameTutorials
1
0.949504
1
0.949504
game-dev
MEDIA
0.987643
game-dev
0.545359
1
0.545359
moai/moai-beta
3,318
3rdparty/box2d-2.2.1/Box2D/Collision/Shapes/b2EdgeShape.cpp
/* * Copyright (c) 2006-2010 Erin Catto http://www.box2d.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. */ #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <new> using namespace std; void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) { m_vertex1 = v1; m_vertex2 = v2; m_hasVertex0 = false; m_hasVertex3 = false; } b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const { void* mem = allocator->Allocate(sizeof(b2EdgeShape)); b2EdgeShape* clone = new (mem) b2EdgeShape; *clone = *this; return clone; } int32 b2EdgeShape::GetChildCount() const { return 1; } bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { B2_NOT_USED(xf); B2_NOT_USED(p); return false; } // p = p1 + t * d // v = v1 + s * e // p1 + t * d = v1 + s * e // s * e - t * d = p1 - v1 bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); // Put the ray into the edge's frame of reference. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); b2Vec2 d = p2 - p1; b2Vec2 v1 = m_vertex1; b2Vec2 v2 = m_vertex2; b2Vec2 e = v2 - v1; b2Vec2 normal(e.y, -e.x); normal.Normalize(); // q = p1 + t * d // dot(normal, q - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 float32 numerator = b2Dot(normal, v1 - p1); float32 denominator = b2Dot(normal, d); if (denominator == 0.0f) { return false; } float32 t = numerator / denominator; if (t < 0.0f || input.maxFraction < t) { return false; } b2Vec2 q = p1 + t * d; // q = v1 + s * r // s = dot(q - v1, r) / dot(r, r) b2Vec2 r = v2 - v1; float32 rr = b2Dot(r, r); if (rr == 0.0f) { return false; } float32 s = b2Dot(q - v1, r) / rr; if (s < 0.0f || 1.0f < s) { return false; } output->fraction = t; if (numerator > 0.0f) { output->normal = -normal; } else { output->normal = normal; } return true; } void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); b2Vec2 v1 = b2Mul(xf, m_vertex1); b2Vec2 v2 = b2Mul(xf, m_vertex2); b2Vec2 lower = b2Min(v1, v2); b2Vec2 upper = b2Max(v1, v2); b2Vec2 r(m_radius, m_radius); aabb->lowerBound = lower - r; aabb->upperBound = upper + r; } void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const { B2_NOT_USED(density); massData->mass = 0.0f; massData->center = 0.5f * (m_vertex1 + m_vertex2); massData->I = 0.0f; }
1
0.954522
1
0.954522
game-dev
MEDIA
0.949149
game-dev
0.971875
1
0.971875
Siv3D/OpenSiv3D
3,442
Siv3D/include/Siv3D/Effect.hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2025 Ryo Suzuki // Copyright (c) 2016-2025 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Common.hpp" # include "IEffect.hpp" # include "Duration.hpp" # include "AssetHandle.hpp" namespace s3d { /// @brief エフェクトグループ class Effect : public AssetHandle<Effect> { public: /// @brief エフェクトグループを作成します。 /// @param maxLifeTimeSec このエフェクトグループでのエフェクトの最大継続時間(秒) SIV3D_NODISCARD_CXX20 Effect(double maxLifeTimeSec = 10.0); /// @brief エフェクトグループを作成します。 /// @param maxLifeTimeSec このエフェクトグループでのエフェクトの最大継続時間(秒) SIV3D_NODISCARD_CXX20 Effect(const Duration& maxLifeTimeSec); /// @brief デストラクタ virtual ~Effect(); /// @brief エフェクトグループに新しいエフェクトを追加します /// @param effect 追加するエフェクト const Effect& add(std::unique_ptr<IEffect>&& effect) const; /// @brief エフェクトグループに新しいエフェクトを追加します /// @tparam IEffectType 追加するエフェクトの型 /// @tparam ...Args コンストラクタ引数の型 /// @param ...args コンストラクタ引数 template <class IEffectType, class... Args, std::enable_if_t<std::is_base_of_v<IEffect, IEffectType>>* = nullptr> const Effect& add(Args&&... args) const; /// @brief エフェクトグループに新しいエフェクトを追加します /// @remark 関数オブジェクトは double 型を受け取り bool 型を返す必要があります。 /// @tparam Fty エフェクト(関数オブジェクト)の型 /// @param f エフェクトの関数オブジェクト template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, double>>* = nullptr> const Effect& add(Fty f) const; /// @brief エフェクトグループがアクティブなエフェクトを持っているかを返します。 /// @remark `Effect::hasEffects()` と同じ結果を返します。 /// @return アクティブなエフェクトがある場合 true, それ以外の場合は false [[nodiscard]] explicit operator bool() const; /// @brief エフェクトグループがアクティブなエフェクトを持っていないかを返します。 /// @return アクティブなエフェクトがない場合 true, それ以外の場合は false [[nodiscard]] bool isEmpty() const; /// @brief エフェクトグループがアクティブなエフェクトを持っているかを返します。 /// @return アクティブなエフェクトがある場合 true, それ以外の場合は false [[nodiscard]] bool hasEffects() const; /// @brief エフェクトグループでアクティブなエフェクトの個数を返します。 /// @return アクティブなエフェクトの個数 [[nodiscard]] size_t num_effects() const; /// @brief このエフェクトグループの時間経過を一時停止します。 void pause() const; /// @brief このエフェクトグループの時間経過が一時停止されているかを返します。 /// @return 一時停止されている場合 true, それ以外の場合は false [[nodiscard]] bool isPaused() const; /// @brief このエフェクトグループの時間経過が一時停止されている場合、再開します。 void resume() const; /// @brief このエフェクトグループの時間経過の速さを、実時間に対する倍率 (2.0 で 2 倍早く経過)で設定します。 /// @param speed 時間経過の速さ const Effect& setSpeed(double speed) const; /// @brief このエフェクトグループの時間経過の速さを返します。 /// @return 時間経過の速さ [[nodiscard]] double getSpeed() const; /// @brief このエフェクトグループでのエフェクトの最大継続時間(秒)を設定します。 /// @param maxLifeTimeSec このエフェクトグループでのエフェクトの最大継続時間(秒) const Effect& setMaxLifeTime(double maxLifeTimeSec); /// @brief このエフェクトグループでのエフェクトの最大継続時間(秒)を設定します。 /// @param maxLifeTimeSec このエフェクトグループでのエフェクトの最大継続時間(秒) void setMaxLifeTime(const Duration& maxLifeTimeSec); /// @brief このエフェクトグループでのエフェクトの最大継続時間(秒)を返します。 /// @return このエフェクトグループでのエフェクトの最大継続時間(秒) [[nodiscard]] double getMaxLifeTime() const; /// @brief このエフェクトグループ内のエフェクトの `update()` を実行します。 void update() const; /// @brief このエフェクトグループ内の全てのエフェクトを、経過時間に関わらず消去します。 void clear() const; void swap(Effect& other) noexcept; }; } template <> inline void std::swap(s3d::Effect& a, s3d::Effect& b) noexcept; # include "detail/Effect.ipp"
1
0.797456
1
0.797456
game-dev
MEDIA
0.466127
game-dev
0.532779
1
0.532779
delight-dev/Delight
3,094
UnityProject/Delight/Assets/TextMesh Pro/Examples & Extras/Scripts/Benchmark04.cs
using UnityEngine; using System.Collections; namespace TMPro.Examples { public class Benchmark04 : MonoBehaviour { public int SpawnType = 0; public int MinPointSize = 12; public int MaxPointSize = 64; public int Steps = 4; private Transform m_Transform; //private TextMeshProFloatingText floatingText_Script; //public Material material; void Start() { m_Transform = transform; float lineHeight = 0; float orthoSize = Camera.main.orthographicSize = Screen.height / 2; float ratio = (float)Screen.width / Screen.height; for (int i = MinPointSize; i <= MaxPointSize; i += Steps) { if (SpawnType == 0) { // TextMesh Pro Implementation GameObject go = new GameObject("Text - " + i + " Pts"); if (lineHeight > orthoSize * 2) return; go.transform.position = m_Transform.position + new Vector3(ratio * -orthoSize * 0.975f, orthoSize * 0.975f - lineHeight, 0); TextMeshPro textMeshPro = go.AddComponent<TextMeshPro>(); //textMeshPro.fontSharedMaterial = material; //textMeshPro.font = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(TextMeshProFont)) as TextMeshProFont; //textMeshPro.anchor = AnchorPositions.Left; textMeshPro.rectTransform.pivot = new Vector2(0, 0.5f); textMeshPro.enableWordWrapping = false; textMeshPro.extraPadding = true; textMeshPro.isOrthographic = true; textMeshPro.fontSize = i; textMeshPro.text = i + " pts - Lorem ipsum dolor sit..."; textMeshPro.color = new Color32(255, 255, 255, 255); lineHeight += i; } else { // TextMesh Implementation // Causes crashes since atlas needed exceeds 4096 X 4096 /* GameObject go = new GameObject("Arial " + i); //if (lineHeight > orthoSize * 2 * 0.9f) return; go.transform.position = m_Transform.position + new Vector3(ratio * -orthoSize * 0.975f, orthoSize * 0.975f - lineHeight, 1); TextMesh textMesh = go.AddComponent<TextMesh>(); textMesh.font = Resources.Load("Fonts/ARIAL", typeof(Font)) as Font; textMesh.renderer.sharedMaterial = textMesh.font.material; textMesh.anchor = TextAnchor.MiddleLeft; textMesh.fontSize = i * 10; textMesh.color = new Color32(255, 255, 255, 255); textMesh.text = i + " pts - Lorem ipsum dolor sit..."; lineHeight += i; */ } } } } }
1
0.666919
1
0.666919
game-dev
MEDIA
0.899228
game-dev
0.935726
1
0.935726
SuperNewRoles/SuperNewRoles
2,365
SuperNewRoles/Roles/Ability/SpeedBoosterAbility.cs
using System; using SuperNewRoles.Modules; using SuperNewRoles.Modules.Events; using SuperNewRoles.Modules.Events.Bases; using SuperNewRoles.Roles.Ability.CustomButton; using UnityEngine; namespace SuperNewRoles.Roles.Ability; public class SpeedBoosterAbility : CustomButtonBase, IButtonEffect { private EventListener<PlayerPhysicsFixedUpdateEventData> _physicsUpdateListener; private bool SpeedBoosterActive; public bool isEffectActive { get; set; } public float EffectTimer { get; set; } Action IButtonEffect.OnEffectEnds => () => { RpcSetSpeedBooster(this, false); }; public float EffectDuration => _effectDuration; public bool effectCancellable => true; public override float DefaultTimer => _coolTime; public override string buttonText => ModTranslation.GetString("SpeedBoosterButton"); public override Sprite Sprite => AssetManager.GetAsset<Sprite>("SpeedUpButton.png"); protected override KeyType keytype => KeyType.Ability1; private float _coolTime; private float _effectDuration; private float _multiplier; public SpeedBoosterAbility(float coolTime, float effectDuration, float multiplier) { _coolTime = coolTime; _effectDuration = effectDuration; _multiplier = multiplier; } public override bool CheckIsAvailable() => true; public override void OnClick() { RpcSetSpeedBooster(this, true); } [CustomRPC] public static void RpcSetSpeedBooster(SpeedBoosterAbility ability, bool isSpeedBoosterActive) { ability.SpeedBoosterActive = isSpeedBoosterActive; } public override void AttachToLocalPlayer() { base.AttachToLocalPlayer(); _physicsUpdateListener = PlayerPhysicsFixedUpdateEvent.Instance.AddListener(OnPhysicsFixedUpdate); } public override void DetachToLocalPlayer() { base.DetachToLocalPlayer(); _physicsUpdateListener?.RemoveListener(); } private void OnPhysicsFixedUpdate(PlayerPhysicsFixedUpdateEventData data) { if (!data.Instance.AmOwner) return; if (MeetingHud.Instance != null) { SpeedBoosterActive = false; return; } if (SpeedBoosterActive) { var vel = data.Instance.body.velocity; data.Instance.body.velocity = vel * _multiplier; } } }
1
0.531308
1
0.531308
game-dev
MEDIA
0.990462
game-dev
0.865193
1
0.865193
Oryxel/Boar
9,120
src/main/java/ac/boar/anticheat/packets/input/AuthInputPackets.java
package ac.boar.anticheat.packets.input; import ac.boar.anticheat.GlobalSetting; import ac.boar.anticheat.data.input.TickData; import ac.boar.anticheat.data.input.VelocityData; import ac.boar.anticheat.packets.input.legacy.LegacyAuthInputPackets; import ac.boar.anticheat.player.BoarPlayer; import ac.boar.anticheat.prediction.PredictionRunner; import ac.boar.anticheat.teleport.data.TeleportCache; import ac.boar.anticheat.util.math.Vec3; import ac.boar.protocol.event.CloudburstPacketEvent; import ac.boar.protocol.listener.PacketListener; import org.cloudburstmc.protocol.bedrock.data.PlayerAuthInputData; import org.cloudburstmc.protocol.bedrock.packet.MovePlayerPacket; import org.cloudburstmc.protocol.bedrock.packet.PlayerAuthInputPacket; import java.util.Iterator; import java.util.Map; import java.util.Queue; public class AuthInputPackets implements PacketListener { @Override public void onPacketReceived(final CloudburstPacketEvent event) { final BoarPlayer player = event.getPlayer(); if (!(event.getPacket() instanceof PlayerAuthInputPacket packet)) { return; } if (event.isCancelled()) { return; } LegacyAuthInputPackets.processAuthInput(player, packet, true); boolean handleRewind = true; if (player.tick == Long.MIN_VALUE) { player.tick = Math.max(0, packet.getTick()) - 1; handleRewind = false; } player.tick++; if (packet.getTick() != player.tick || packet.getTick() < 0) { player.postTick(); player.kick("Invalid tick id=" + packet.getTick()); return; } player.sinceTeleport++; player.sinceLoadingScreen++; player.breakingValidator.handle(packet); player.tick(); if (player.inLoadingScreen || player.sinceLoadingScreen < 2) { LegacyAuthInputPackets.updateUnvalidatedPosition(player, packet); final double offset = player.unvalidatedPosition.distanceTo(player.prevUnvalidatedPosition); if (offset > 1.0E-7) { player.getTeleportUtil().teleportTo(player.getTeleportUtil().getLastKnowValid()); } return; } // This is likely the case, prediction run before teleport. LegacyAuthInputPackets.updateUnvalidatedPosition(player, packet); new PredictionRunner(player).run(player.tick); this.processQueuedTeleports(player, packet, handleRewind); player.postTick(); if (player.isAbilityExempted()) { LegacyAuthInputPackets.processAuthInput(player, packet, true); player.velocity = player.unvalidatedTickEnd.clone(); player.setPos(player.unvalidatedPosition); // Clear velocity out manually since we haven't handled em. Iterator<Map.Entry<Long, VelocityData>> iterator = player.queuedVelocities.entrySet().iterator(); Map.Entry<Long, VelocityData> entry; while (iterator.hasNext() && (entry = iterator.next()) != null) { if (entry.getKey() >= player.receivedStackId.get()) { break; } else { iterator.remove(); } } return; } LegacyAuthInputPackets.doPostPrediction(player, packet); } private void processQueuedTeleports(final BoarPlayer player, final PlayerAuthInputPacket packet, boolean doRewind) { final Queue<TeleportCache> queuedTeleports = player.getTeleportUtil().getQueuedTeleports(); if (queuedTeleports.isEmpty()) { return; } TeleportCache cache; while ((cache = queuedTeleports.peek()) != null) { if (player.receivedStackId.get() < cache.getStackId()) { break; } queuedTeleports.poll(); // Bedrock don't reply to teleport individually using a separate tick packet instead it just simply set its position to // the teleported position and then let us know the *next tick*, so we do the same! if (cache instanceof TeleportCache.Normal normal) { this.processTeleport(player, normal, packet); } else if (cache instanceof TeleportCache.Rewind rewind) { if (doRewind) { this.processRewind(player, rewind, packet); } } else { throw new RuntimeException("Failed to process queued teleports, invalid teleport=" + cache); } } } private void processTeleport(final BoarPlayer player, final TeleportCache.Normal normal, final PlayerAuthInputPacket packet) { double distance = packet.getPosition().distance(normal.getPosition().toVector3f()); // I think I'm being a bit lenient but on Bedrock the position error seems to be a bit high. if ((packet.getInputData().contains(PlayerAuthInputData.HANDLE_TELEPORT) || normal.isKeepVelocity() || normal.isRespawn()) && distance <= 1.0E-3F) { player.setPos(new Vec3(packet.getPosition().sub(0, player.getYOffset(), 0))); player.unvalidatedPosition = player.prevUnvalidatedPosition = player.position.clone(); if (!normal.isKeepVelocity()) { player.velocity = Vec3.ZERO.clone(); } player.sinceTeleport = 0; } else { // Player rejected teleport OR this is not the latest teleport. if (!player.getTeleportUtil().isTeleporting()) { player.getTeleportUtil().teleportTo(normal); } } } private void processRewind(final BoarPlayer player, final TeleportCache.Rewind rewind, final PlayerAuthInputPacket packet) { if (player.isAbilityExempted()) { // Fully exempted from rewind teleport. return; } long tickDistance = player.tick - rewind.getTick(); player.onGround = rewind.isOnGround(); player.velocity = rewind.getTickEnd(); player.setPos(rewind.getPosition().subtract(0, player.getYOffset(), 0)); player.prevUnvalidatedPosition = player.unvalidatedPosition = player.position.clone(); player.getTeleportUtil().cachePosition(rewind.getTick(), rewind.getPosition().toVector3f()); if (GlobalSetting.RESEND_POSITION_DURING_REWIND) { final TickData data = player.getTeleportUtil().getAuthInputHistory().get(rewind.getTick()); if (data != null) { LegacyAuthInputPackets.correctInputData(player, data.packet()); player.downstreamPacketHandler.getOldHandler().handle(data.packet()); } } // Keep running prediction until we catch up with the player current tick. long currentTick = rewind.getTick(); for (int i = 0; i < tickDistance; i++) { if (currentTick != rewind.getTick() && player.position.distanceTo(player.unvalidatedPosition) > player.getMaxOffset()) { player.unvalidatedPosition = player.position.clone(); } PlayerAuthInputPacket authInputPacket = null; currentTick++; if (currentTick == player.tick) { LegacyAuthInputPackets.processAuthInput(player, packet, true); LegacyAuthInputPackets.updateUnvalidatedPosition(player, packet); } else if (player.getTeleportUtil().getAuthInputHistory().containsKey(currentTick)) { final TickData data = player.getTeleportUtil().getAuthInputHistory().get(currentTick); LegacyAuthInputPackets.processAuthInput(player, data.packet(), false); LegacyAuthInputPackets.updateUnvalidatedPosition(player, packet); // Reverted back to the old flags. player.getFlagTracker().set(data.flags(), false); authInputPacket = data.packet(); } else { throw new RuntimeException("Failed find auth input history for rewind."); } new PredictionRunner(player).run(currentTick); if (currentTick != player.tick && authInputPacket != null && GlobalSetting.RESEND_POSITION_DURING_REWIND) { authInputPacket.setPosition(player.position.toVector3f()); LegacyAuthInputPackets.correctInputData(player, authInputPacket); player.downstreamPacketHandler.getOldHandler().handle(authInputPacket); } } } @Override public void onPacketSend(final CloudburstPacketEvent event, final boolean immediate) { if (!(event.getPacket() instanceof MovePlayerPacket packet)) { return; } final BoarPlayer player = event.getPlayer(); if (packet.getMode() == MovePlayerPacket.Mode.HEAD_ROTATION) { return; } if (player.runtimeEntityId != packet.getRuntimeEntityId()) { return; } player.getTeleportUtil().queueTeleport(new Vec3(packet.getPosition()), immediate, packet.getMode()); } }
1
0.961023
1
0.961023
game-dev
MEDIA
0.82824
game-dev,networking
0.979638
1
0.979638
SkyFangames/La-Base-de-Sky
9,846
LA BASE DE SKY/Data/Scripts/056_Battle Frontier generator/002_ChallengeGenerator_Data.rb
#=============================================================================== # #=============================================================================== class BaseStatRestriction def initialize(mn, mx) @mn = mn @mx = mx end def isValid?(pkmn) bst = baseStatTotal(pkmn.species) return bst >= @mn && bst <= @mx end end #=============================================================================== # #=============================================================================== class NonlegendaryRestriction def isValid?(pkmn) return true if !pkmn.genderless? return false if pkmn.species_data.egg_groups.include?(:Undiscovered) return true end end #=============================================================================== # #=============================================================================== class InverseRestriction def initialize(r) @r = r end def isValid?(pkmn) return !@r.isValid?(pkmn) end end #=============================================================================== # #=============================================================================== # [3/10] # 0-266 - 0-500 # [106] # 267-372 - 380-500 # [95] # 373-467 - 400-555 (nonlegendary) # 468-563 - 400-555 (nonlegendary) # 564-659 - 400-555 (nonlegendary) # 660-755 - 400-555 (nonlegendary) # 756-799 - 580-600 [legendary] (compat1==15 or compat2==15, genderbyte=255) # 800-849 - 500- # 850-881 - 580- def withRestr(_rule, minbs, maxbs, legendary) ret = PokemonChallengeRules.new.addPokemonRule(BaseStatRestriction.new(minbs, maxbs)) case legendary when 0 ret.addPokemonRule(NonlegendaryRestriction.new) when 1 ret.addPokemonRule(InverseRestriction.new(NonlegendaryRestriction.new)) end return ret end def pbArrangeByTier(pokemonlist, rule) tiers = [ withRestr(rule, 0, 500, 0), withRestr(rule, 380, 500, 0), withRestr(rule, 400, 555, 0), withRestr(rule, 400, 555, 0), withRestr(rule, 400, 555, 0), withRestr(rule, 400, 555, 0), withRestr(rule, 580, 680, 1), withRestr(rule, 500, 680, 0), withRestr(rule, 580, 680, 2) ] tierPokemon = [] tiers.length.times do tierPokemon.push([]) end # Sort each Pokémon into tiers. Which tier a Pokémon is put in deoends on the # Pokémon's position within pokemonlist (later = higher tier). pokemonlist is # already roughly arranged by rank from weakest to strongest. pokemonlist.length.times do |i| next if !rule.ruleset.isPokemonValid?(pokemonlist[i]) validtiers = [] tiers.length.times do |j| validtiers.push(j) if tiers[j].ruleset.isPokemonValid?(pokemonlist[i]) end if validtiers.length > 0 vt = validtiers.length * i / pokemonlist.length tierPokemon[validtiers[vt]].push(pokemonlist[i]) end end # Now for each tier, sort the Pokemon in that tier by their BST (lowest first). ret = [] tiers.length.times do |i| tierPokemon[i].sort! do |a, b| bstA = baseStatTotal(a.species) bstB = baseStatTotal(b.species) (bstA == bstB) ? a.species <=> b.species : bstA <=> bstB end ret.concat(tierPokemon[i]) end return ret end #=============================================================================== # #=============================================================================== def pbReplenishBattlePokemon(party, rule) while party.length < 20 pkmn = pbRandomPokemonFromRule(rule, nil) found = false party.each do |pk| next if !isBattlePokemonDuplicate(pkmn, pk) found = true break end party.push(pkmn) if !found end end def isBattlePokemonDuplicate(pk, pk2) return false if pk.species != pk2.species moves1 = [] moves2 = [] Pokemon::MAX_MOVES.times do |i| moves1.push((pk.moves[i]) ? pk.moves[i].id : nil) moves2.push((pk2.moves[i]) ? pk2.moves[i].id : nil) end moves1.compact.sort moves2.compact.sort # Accept as same if moves are same and there are MAX_MOVES number of moves each return true if moves1 == moves2 && moves1.length == Pokemon::MAX_MOVES same_evs = true GameData::Stat.each_main { |s| same_evs = false if pk.ev[s.id] != pk2.ev[s.id] } return pk.item_id == pk2.item_id && pk.nature_id == pk2.nature_id && same_evs end def pbRemoveDuplicates(party) ret = [] party.each do |pk| found = false count = 0 firstIndex = -1 ret.length.times do |i| pk2 = ret[i] if isBattlePokemonDuplicate(pk, pk2) found = true break end if pk.species == pk2.species firstIndex = i if count == 0 count += 1 end end if !found ret.delete_at(firstIndex) if count >= 10 ret.push(pk) end end return ret end #=============================================================================== # #=============================================================================== def pbGenerateChallenge(rule, tag) oldrule = rule yield(_INTL("Preparándose para generar los equipos")) rule = rule.copy.setNumber(2) yield(nil) party = load_data(tag + ".rxdata") rescue [] teams = load_data(tag + "_teams.rxdata") rescue [] if teams.length < 10 btpokemon = pbGetBTPokemon(tag) if btpokemon && btpokemon.length != 0 suggestedLevel = rule.ruleset.suggestedLevel btpokemon.each do |pk| pkmn = pk.createPokemon(suggestedLevel, 31, nil) party.push(pkmn) if rule.ruleset.isPokemonValid?(pkmn) end end end yield(nil) party = pbRemoveDuplicates(party) yield(nil) maxteams = 600 cutoffrating = 65 toolowrating = 40 iterations = 11 iterations.times do |iter| save_data(party, tag + ".rxdata") yield(_INTL("Generando equipos ({1} de {2})", iter + 1, iterations)) i = 0 while i < teams.length yield(nil) if i % 10 == 0 pbReplenishBattlePokemon(party, rule) if teams[i].rating < cutoffrating && teams[i].totalGames >= 80 teams[i] = RuledTeam.new(party, rule) elsif teams[i].length < 2 teams[i] = RuledTeam.new(party, rule) elsif i >= maxteams teams.delete_at(i) elsif teams[i].totalGames >= 250 # retire teams[i].length.times do |j| party.push(teams[i][j]) end teams[i] = RuledTeam.new(party, rule) elsif teams[i].rating < toolowrating teams[i] = RuledTeam.new(party, rule) end i += 1 end save_data(teams, tag + "_teams.rxdata") yield(nil) while teams.length < maxteams yield(nil) if teams.length % 10 == 0 pbReplenishBattlePokemon(party, rule) teams.push(RuledTeam.new(party, rule)) end save_data(party, tag + ".rxdata") teams = teams.sort { |a, b| b.rating <=> a.rating } yield(_INTL("Simulando combates ({1} de {2})", iter + 1, iterations)) i = 0 loop do changed = false teams.length.times do |j| yield(nil) other = j 5.times do other = rand(teams.length) next if other == j end next if other == j changed = true pbRuledBattle(teams[j], teams[other], rule) end i += 1 gameCount = 0 teams.each { |team| gameCount += team.games } yield(nil) next if gameCount / teams.length < 12 teams.each { |team| team.updateRating } break end teams.sort! { |a, b| b.rating <=> a.rating } save_data(teams, tag + "_teams.rxdata") end party = [] yield(nil) teams.sort! { |a, b| a.rating <=> b.rating } teams.each do |team| next if team.rating <= cutoffrating team.length.times do |i| party.push(team[i]) end end rule = oldrule yield(nil) party = pbRemoveDuplicates(party) yield(_INTL("Escribiendo resultados")) party = pbArrangeByTier(party, rule) yield(nil) pbTrainerInfo(party, tag, rule) { yield(nil) } yield(nil) end #=============================================================================== # #=============================================================================== def pbWriteCup(id, rules) return if !$DEBUG trlists = (load_data("Data/trainer_lists.dat") rescue []) list = [] trlists.length.times do |i| tr = trlists[i] if tr[5] list.push("*" + (tr[3].sub(/\.txt$/, ""))) else list.push((tr[3].sub(/\.txt$/, ""))) end end cmd = 0 if trlists.length == 0 cmd = pbMessage(_INTL("¿Generar equipos de Pokémon para este reto?"), [_INTL("SÍ"), _INTL("NO")], 2) case cmd when 0 cmd = 2 when 1 cmd = 0 end else cmd = pbMessage(_INTL("¿Generar equipos de Pokémon para este reto?"), [_INTL("NO"), _INTL("SÍ, USAR EXISTENTE"), _INTL("SÍ, USAR NUEVO")], 1) end return if cmd == 0 # No case cmd when 1 # Yes, use existing cmd = pbMessage(_INTL("Elige un reto."), list, -1) if cmd >= 0 pbMessage(_INTL("Este reto usará la lista de Pokémon de {1}.", list[cmd])) trlists.length.times do |i| tr = trlists[i] while !tr[5] && tr[2].include?(id) tr[2].delete(id) end end trlists[cmd][2].push(id) if !trlists[cmd][5] save_data(trlists, "Data/trainer_lists.dat") Graphics.update Compiler.write_trainer_lists end return when 2 # Yes, use new return if !pbConfirmMessage(_INTL("Esto puede llevar un buen rato. ¿Estás seguro?")) mw = pbCreateMessageWindow t = System.uptime pbGenerateChallenge(rules, id) do |message| if System.uptime - t >= 5 t += 5 Graphics.update end if message pbMessageDisplay(mw, message, false) t = System.uptime Graphics.update end end pbDisposeMessageWindow(mw) pbMessage(_INTL("Generación de equipo completada.")) end end
1
0.895808
1
0.895808
game-dev
MEDIA
0.88653
game-dev
0.886846
1
0.886846
eloqdata/eloqdoc
4,691
src/third_party/s2/s2r2rect.cc
// Copyright 2005 Google Inc. All Rights Reserved. #include "s2r2rect.h" #include "base/logging.h" #include "r1interval.h" #include "s2.h" #include "s2cap.h" #include "s2cell.h" #include "s2latlngrect.h" S2R2Rect S2R2Rect::FromCell(S2Cell const& cell) { // S2Cells have a more efficient GetSizeST() method than S2CellIds. double size = cell.GetSizeST(); return FromCenterSize(cell.id().GetCenterST(), R2Point(size, size)); } S2R2Rect S2R2Rect::FromCellId(S2CellId const& id) { double size = id.GetSizeST(); return FromCenterSize(id.GetCenterST(), R2Point(size, size)); } S2R2Rect S2R2Rect::FromCenterSize(R2Point const& center, R2Point const& size) { return S2R2Rect(R1Interval(center.x() - 0.5 * size.x(), center.x() + 0.5 * size.x()), R1Interval(center.y() - 0.5 * size.y(), center.y() + 0.5 * size.y())); } S2R2Rect S2R2Rect::FromPoint(R2Point const& p) { return S2R2Rect(p, p); } S2R2Rect S2R2Rect::FromPointPair(R2Point const& p1, R2Point const& p2) { return S2R2Rect(R1Interval::FromPointPair(p1.x(), p2.x()), R1Interval::FromPointPair(p1.y(), p2.y())); } S2R2Rect* S2R2Rect::Clone() const { return new S2R2Rect(*this); } R2Point S2R2Rect::GetVertex(int k) const { // Twiddle bits to return the points in CCW order (SW, SE, NE, NW). return R2Point(x_.bound((k>>1) ^ (k&1)), y_.bound(k>>1)); } R2Point S2R2Rect::GetCenter() const { return R2Point(x_.GetCenter(), y_.GetCenter()); } R2Point S2R2Rect::GetSize() const { return R2Point(x_.GetLength(), y_.GetLength()); } bool S2R2Rect::Contains(R2Point const& p) const { return x_.Contains(p.x()) && y_.Contains(p.y()); } bool S2R2Rect::InteriorContains(R2Point const& p) const { return x_.InteriorContains(p.x()) && y_.InteriorContains(p.y()); } bool S2R2Rect::Contains(S2R2Rect const& other) const { return x_.Contains(other.x_) && y_.Contains(other.y_); } bool S2R2Rect::InteriorContains(S2R2Rect const& other) const { return x_.InteriorContains(other.x_) && y_.InteriorContains(other.y_); } bool S2R2Rect::Intersects(S2R2Rect const& other) const { return x_.Intersects(other.x_) && y_.Intersects(other.y_); } bool S2R2Rect::InteriorIntersects(S2R2Rect const& other) const { return x_.InteriorIntersects(other.x_) && y_.InteriorIntersects(other.y_); } void S2R2Rect::AddPoint(R2Point const& p) { x_.AddPoint(p.x()); y_.AddPoint(p.y()); } S2R2Rect S2R2Rect::Expanded(R2Point const& margin) const { DCHECK_GE(margin.x(), 0); DCHECK_GE(margin.y(), 0); return S2R2Rect(x_.Expanded(margin.x()), y_.Expanded(margin.y())); } S2R2Rect S2R2Rect::Union(S2R2Rect const& other) const { return S2R2Rect(x_.Union(other.x_), y_.Union(other.y_)); } S2R2Rect S2R2Rect::Intersection(S2R2Rect const& other) const { R1Interval x = x_.Intersection(other.x_); R1Interval y = y_.Intersection(other.y_); if (x.is_empty() || y.is_empty()) { // The x/y ranges must either be both empty or both non-empty. return Empty(); } return S2R2Rect(x, y); } bool S2R2Rect::ApproxEquals(S2R2Rect const& other, double max_error) const { return (x_.ApproxEquals(other.x_, max_error) && y_.ApproxEquals(other.y_, max_error)); } S2Point S2R2Rect::ToS2Point(R2Point const& p) { return S2::FaceUVtoXYZ(0, S2::STtoUV(p.x()), S2::STtoUV(p.y())).Normalize(); } S2Cap S2R2Rect::GetCapBound() const { if (is_empty()) return S2Cap::Empty(); // The rectangle is a convex polygon on the sphere, since it is a subset of // one cube face. Its bounding cap is also a convex region on the sphere, // and therefore we can bound the rectangle by just bounding its vertices. // We use the rectangle's center in (s,t)-space as the cap axis. This // doesn't yield the minimal cap but it's pretty close. S2Cap cap = S2Cap::FromAxisHeight(ToS2Point(GetCenter()), 0); for (int k = 0; k < 4; ++k) { cap.AddPoint(ToS2Point(GetVertex(k))); } return cap; } S2LatLngRect S2R2Rect::GetRectBound() const { // This is not very tight but hopefully good enough. return GetCapBound().GetRectBound(); } bool S2R2Rect::Contains(S2Point const& p) const { S2CellId cellid = S2CellId::FromPoint(p); if (cellid.face() != 0) return false; return Contains(cellid.GetCenterST()); } bool S2R2Rect::Contains(S2Cell const& cell) const { if (cell.face() != 0) return false; return Contains(S2R2Rect::FromCell(cell)); } bool S2R2Rect::MayIntersect(S2Cell const& cell) const { if (cell.face() != 0) return false; return Intersects(S2R2Rect::FromCell(cell)); } ostream& operator<<(ostream& os, S2R2Rect const& r) { return os << "[Lo" << r.lo() << ", Hi" << r.hi() << "]"; }
1
0.893635
1
0.893635
game-dev
MEDIA
0.294933
game-dev
0.937943
1
0.937943
magefree/mage
1,484
Mage.Sets/src/mage/cards/o/OrneryDilophosaur.java
package mage.cards.o; import mage.MageInt; import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.condition.common.FerociousCondition; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.hint.common.FerociousHint; import mage.abilities.keyword.DeathtouchAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class OrneryDilophosaur extends CardImpl { public OrneryDilophosaur(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}"); this.subtype.add(SubType.DINOSAUR); this.power = new MageInt(2); this.toughness = new MageInt(2); // Deathtouch this.addAbility(DeathtouchAbility.getInstance()); // Whenever Ornery Dilophosaur attacks, if you control a creature with power 4 or greater, Ornery Dilophosaur gets +2/+2 until end of turn. this.addAbility(new AttacksTriggeredAbility(new BoostSourceEffect(2, 2, Duration.EndOfTurn)) .withInterveningIf(FerociousCondition.instance).addHint(FerociousHint.instance)); } private OrneryDilophosaur(final OrneryDilophosaur card) { super(card); } @Override public OrneryDilophosaur copy() { return new OrneryDilophosaur(this); } }
1
0.932588
1
0.932588
game-dev
MEDIA
0.938255
game-dev
0.985566
1
0.985566
hengband/hengband
12,607
src/window/main-window-left-frame.cpp
#include "window/main-window-left-frame.h" #include "floor/dungeon-feeling.h" #include "game-option/special-options.h" #include "game-option/text-display-options.h" #include "player-base/player-race.h" #include "player-info/class-info.h" #include "player-info/mimic-info-table.h" #include "player/player-status-table.h" #include "system/floor/floor-info.h" #include "system/monrace/monrace-definition.h" #include "system/monster-entity.h" #include "system/player-type-definition.h" #include "term/gameterm.h" #include "term/screen-processor.h" #include "term/z-form.h" #include "timed-effect/timed-effects.h" #include "tracking/health-bar-tracker.h" #include "util/string-processor.h" #include "window/main-window-row-column.h" #include "window/main-window-stat-poster.h" #include "window/main-window-util.h" #include "world/world.h" #include <fmt/format.h> /*! * @brief ターゲットしているモンスターの情報部に表示する状態異常と文字色の対応を保持する構造体 */ struct condition_layout_info { std::string label; TERM_COLOR color; }; /*! * @brief プレイヤーの称号を表示する / Prints "title", including "wizard" or "winner" as needed. */ void print_title(PlayerType *player_ptr) { std::string p; const auto &world = AngbandWorld::get_instance(); if (world.wizard) { p = _("[ウィザード]", "[=-WIZARD-=]"); } else if (world.total_winner) { if (world.is_player_true_winner()) { p = _("*真・勝利者*", "*TRUEWINNER*"); } else { p = _("***勝利者***", "***WINNER***"); } } else { p = player_titles.at(player_ptr->pclass).at((player_ptr->lev - 1) / 5); } print_field(p, ROW_TITLE, COL_TITLE); } /*! * @brief プレイヤーのレベルを表示する / Prints level */ void print_level(PlayerType *player_ptr) { const auto tmp = format("%5d", player_ptr->lev); if (player_ptr->lev >= player_ptr->max_plv) { put_str(_("レベル ", "LEVEL "), ROW_LEVEL, 0); c_put_str(TERM_L_GREEN, tmp, ROW_LEVEL, COL_LEVEL + 7); } else { put_str(_("xレベル", "Level "), ROW_LEVEL, 0); c_put_str(TERM_YELLOW, tmp, ROW_LEVEL, COL_LEVEL + 7); } } /*! * @brief プレイヤーの経験値を表示する / Display the experience */ void print_exp(PlayerType *player_ptr) { std::string out_val; PlayerRace pr(player_ptr); if ((!exp_need) || pr.equals(PlayerRaceType::ANDROID)) { out_val = format("%8d", player_ptr->exp); } else { if (player_ptr->lev >= PY_MAX_LEVEL) { out_val = "********"; } else { out_val = format("%8d", player_exp[player_ptr->lev - 1] * player_ptr->expfact / 100 - player_ptr->exp); } } if (player_ptr->exp >= player_ptr->max_exp) { if (pr.equals(PlayerRaceType::ANDROID)) { put_str(_("強化 ", "Cst "), ROW_EXP, 0); } else { put_str(_("経験 ", "EXP "), ROW_EXP, 0); } c_put_str(TERM_L_GREEN, out_val, ROW_EXP, COL_EXP + 4); } else { put_str(_("x経験", "Exp "), ROW_EXP, 0); c_put_str(TERM_YELLOW, out_val, ROW_EXP, COL_EXP + 4); } } /*! * @brief プレイヤーのACを表示する / Prints current AC */ void print_ac(PlayerType *player_ptr) { /* AC の表示方式を変更している */ put_str(_(" AC( )", "Cur AC "), ROW_AC, COL_AC); c_put_str(TERM_L_GREEN, format("%5d", player_ptr->dis_ac + player_ptr->dis_to_a), ROW_AC, COL_AC + _(6, 7)); } /*! * @brief プレイヤーのHPを表示する / Prints Cur/Max hit points */ void print_hp(PlayerType *player_ptr) { put_str("HP", ROW_CURHP, COL_CURHP); TERM_COLOR color; if (player_ptr->chp >= player_ptr->mhp) { color = TERM_L_GREEN; } else if (player_ptr->chp > (player_ptr->mhp * hitpoint_warn) / 10) { color = TERM_YELLOW; } else { color = TERM_RED; } c_put_str(color, format("%4d", player_ptr->chp), ROW_CURHP, COL_CURHP + 3); put_str("/", ROW_CURHP, COL_CURHP + 7); color = TERM_L_GREEN; c_put_str(color, format("%4d", player_ptr->mhp), ROW_CURHP, COL_CURHP + 8); } /*! * @brief プレイヤーのMPを表示する / Prints players max/cur spell points */ void print_sp(PlayerType *player_ptr) { if ((mp_ptr->spell_book == ItemKindType::NONE) && mp_ptr->spell_first == SPELL_FIRST_NO_SPELL) { return; } put_str(_("MP", "SP"), ROW_CURSP, COL_CURSP); byte color; if (player_ptr->csp >= player_ptr->msp) { color = TERM_L_GREEN; } else if (player_ptr->csp > (player_ptr->msp * mana_warn) / 10) { color = TERM_YELLOW; } else { color = TERM_RED; } c_put_str(color, format("%4d", player_ptr->csp), ROW_CURSP, COL_CURSP + 3); put_str("/", ROW_CURSP, COL_CURSP + 7); color = TERM_L_GREEN; c_put_str(color, format("%4d", player_ptr->msp), ROW_CURSP, COL_CURSP + 8); } /*! * @brief プレイヤーの所持金を表示する / Prints current gold * @param player_ptr プレイヤーへの参照ポインタ */ void print_gold(PlayerType *player_ptr) { put_str(_("$ ", "AU "), ROW_GOLD, COL_GOLD); c_put_str(TERM_L_GREEN, format("%9d", player_ptr->au), ROW_GOLD, COL_GOLD + 3); } /*! * @brief 現在のフロアの深さを表示する / Prints depth in stat area * @param player_ptr プレイヤーへの参照ポインタ */ void print_depth(PlayerType *player_ptr) { TERM_COLOR attr = TERM_WHITE; const auto &[wid, hgt] = term_get_size(); const auto col_depth = wid + COL_DEPTH; const auto row_depth = hgt + ROW_DEPTH; const auto &floor = *player_ptr->current_floor_ptr; if (!floor.is_underground()) { c_prt(attr, format("%7s", _("地上", "Surf.")), row_depth, col_depth); return; } std::string depths; if (depth_in_feet) { depths = fmt::format(_("{} ft", "{} ft"), floor.dun_level * 50); } else { depths = fmt::format(_("{} 階", "Lev {}"), floor.dun_level); } switch (DungeonFeeling::get_instance().get_feeling()) { case 0: attr = TERM_SLATE; break; /* Unknown */ case 1: attr = TERM_L_BLUE; break; /* Special */ case 2: attr = TERM_VIOLET; break; /* Horrible visions */ case 3: attr = TERM_RED; break; /* Very dangerous */ case 4: attr = TERM_L_RED; break; /* Very bad feeling */ case 5: attr = TERM_ORANGE; break; /* Bad feeling */ case 6: attr = TERM_YELLOW; break; /* Nervous */ case 7: attr = TERM_L_UMBER; break; /* Luck is turning */ case 8: attr = TERM_L_WHITE; break; /* Don't like */ case 9: attr = TERM_WHITE; break; /* Reasonably safe */ case 10: attr = TERM_WHITE; break; /* Boring place */ } c_prt(attr, format("%7s", depths.data()), row_depth, col_depth); } /*! * @brief プレイヤーのステータスを一括表示する(左側部分) / Display basic info (mostly left of map) * @param player_ptr プレイヤーへの参照ポインタ */ void print_frame_basic(PlayerType *player_ptr) { const auto &title = player_ptr->mimic_form == MimicKindType::NONE ? rp_ptr->title : mimic_info.at(player_ptr->mimic_form).title; print_field(str_substr(title, 0, 12), ROW_RACE, COL_RACE); print_title(player_ptr); print_level(player_ptr); print_exp(player_ptr); for (int i = 0; i < A_MAX; i++) { print_stat(player_ptr, i); } print_ac(player_ptr); print_hp(player_ptr); print_sp(player_ptr); print_gold(player_ptr); print_depth(player_ptr); print_health(player_ptr, true); print_health(player_ptr, false); } /*! * @brief wizardモード中の闘技場情報を表示する * @param player_ptr プレイヤーへの参照ポインタ */ static void print_health_monster_in_arena_for_wizard(PlayerType *player_ptr) { int row = ROW_INFO - 1; int col = COL_INFO + 2; const int max_num_of_monster_in_arena = 4; for (int i = 0; i < max_num_of_monster_in_arena; i++) { auto row_offset = i; auto monster_list_index = i + 1; // m_listの1-4に闘技場のモンスターデータが入っている term_putstr(col - 2, row + row_offset, 12, TERM_WHITE, " / "); auto &monster = player_ptr->current_floor_ptr->m_list[monster_list_index]; if (monster.is_valid()) { const auto &monrace = monster.get_monrace(); const auto &symbol_config = monrace.symbol_config; term_putstr(col - 2, row + row_offset, 2, symbol_config.color, format("%c", symbol_config.character)); term_putstr(col - 1, row + row_offset, 5, TERM_WHITE, format("%5d", monster.hp)); term_putstr(col + 5, row + row_offset, 6, TERM_WHITE, format("%5d", monster.max_maxhp)); } } } /*! * @brief 対象のモンスターからcondition_layout_infoのリストを生成して返す * @param monster 対象のモンスター * @return condition_layout_infoのリスト */ static std::vector<condition_layout_info> get_condition_layout_info(const MonsterEntity &monster) { std::vector<condition_layout_info> result; if (monster.is_invulnerable()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::INVULNERABILITY), TERM_WHITE }); } if (monster.is_accelerated()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::FAST), TERM_L_GREEN }); } if (monster.is_decelerated()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::SLOW), TERM_UMBER }); } if (monster.is_fearful()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::FEAR), TERM_SLATE }); } if (monster.is_confused()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::CONFUSION), TERM_L_UMBER }); } if (monster.is_asleep()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::SLEEP), TERM_BLUE }); } if (monster.is_stunned()) { result.push_back({ effect_type_to_label.at(MonsterTimedEffect::STUN), TERM_ORANGE }); } return result; } /*! * @brief モンスターの体力ゲージを表示する * @param riding TRUEならば騎乗中のモンスターの体力、FALSEならターゲットモンスターの体力を表示する。表示位置は固定。 * @details * <pre> * Redraw the "monster health bar" -DRS- * Rather extensive modifications by -BEN- * * The "monster health bar" provides visual feedback on the "health" * of the monster currently being "tracked". There are several ways * to "track" a monster, including targetting it, attacking it, and * affecting it (and nobody else) with a ranged attack. * * Display the monster health bar (affectionately known as the * "health-o-meter"). Clear health bar if nothing is being tracked. * Auto-track current target monster when bored. Note that the * health-bar stops tracking any monster that "disappears". * </pre> */ void print_health(PlayerType *player_ptr, bool riding) { tl::optional<short> monster_idx; int row, col; if (riding) { if (player_ptr->riding > 0) { monster_idx = player_ptr->riding; } row = ROW_RIDING_INFO; col = COL_RIDING_INFO; } else { // ウィザードモードで闘技場観戦時の表示 if (AngbandWorld::get_instance().wizard && AngbandSystem::get_instance().is_phase_out()) { print_health_monster_in_arena_for_wizard(player_ptr); return; } auto &tracker = HealthBarTracker::get_instance(); if (tracker.is_tracking()) { monster_idx = tracker.get_trackee(); } row = ROW_INFO; col = COL_INFO; } const auto max_width = 12; // 表示幅 const auto &[wid, hgt] = term_get_size(); const auto extra_line_count = riding ? 0 : hgt - MAIN_TERM_MIN_ROWS; for (auto y = row; y < row + extra_line_count + 1; ++y) { term_erase(col, y, max_width); } if (!monster_idx) { return; } const auto &monster = player_ptr->current_floor_ptr->m_list[*monster_idx]; if ((!monster.ml) || (player_ptr->effects()->hallucination().is_hallucinated()) || monster.is_dead()) { term_putstr(col, row, max_width, TERM_WHITE, "[----------]"); return; } const auto &[hit_point_bar_color, len] = monster.get_hp_bar_data(); term_putstr(col, row, max_width, TERM_WHITE, "[----------]"); term_putstr(col + 1, row, len, hit_point_bar_color, "**********"); // 騎乗中のモンスターの状態異常は表示しない if (riding) { return; } int col_offset = 0; int row_offset = 1; // 一時的状態異常 // MAX_WIDTHを超えたら次の行に移動する for (const auto &info : get_condition_layout_info(monster)) { if (row_offset > extra_line_count) { break; } if (col_offset + info.label.length() > max_width) { // 改行が必要かどうかチェック col_offset = 0; row_offset++; } term_putstr(col + col_offset, row + row_offset, max_width, info.color, info.label); col_offset += info.label.length() + 1; // 文字数と空白の分だけoffsetを加算 } }
1
0.983971
1
0.983971
game-dev
MEDIA
0.747019
game-dev
0.996201
1
0.996201
cmss13-devs/cmss13
1,949
code/modules/admin/verbs/shakeshipverb.dm
/client/proc/shakeshipverb() set name = "Shake Shipmap" set category = "Admin.Ship" var/drop = FALSE var/delayt var/whattoannounce var/sstrength = tgui_input_number(src, "How Strong?", "Don't go overboard.", 0, 10) if(!sstrength) return var/stime = tgui_input_number(src, "Time Between Shakes?", "Don't make it too long", 0, 30) if(!stime) return var/prompt = tgui_alert(src, "Drop people?", "Confirmation", list("Yes", "No"), 20 SECONDS) if(prompt == "Yes") drop = TRUE var/delayed var/announce prompt = tgui_alert(src, "Delay it?", "Confirmation", list("Yes", "No"), 20 SECONDS) if(prompt == "Yes") delayed = TRUE delayt = tgui_input_number(src, "How much delay?", "60 secs maximum", 0, 60, 0) if(!delayt) return prompt = tgui_alert(src, "Alert people?", "Confirmation", list("Yes", "No"), 20 SECONDS) if(prompt == "Yes") announce = TRUE whattoannounce = tgui_input_text(src, "Please enter announcement text. Keep it empty to keep the default.", "what?") if(!whattoannounce) if(sstrength <= 7) whattoannounce = "WARNING, IMPACT IMMINENT. ETA: [delayt] SECONDS. BRACE BRACE BRACE." if(sstrength > 7) whattoannounce = "DANGER, DANGER! HIGH ENERGY IMPACT IMMINENT. ETA: [delayt] SECONDS. BRACE BRACE BRACE." prompt = tgui_alert(src, "Are you sure you want to shake the shipmap?", "Rock the ship!", list("Yes", "No"), 20 SECONDS) if(prompt != "Yes") return else message_admins("[key_name_admin(src)] rocked the ship! with the strength of [sstrength], and duration of [stime]") if(delayed) if(announce) if(sstrength <= 5) shipwide_ai_announcement(whattoannounce, MAIN_AI_SYSTEM, 'sound/effects/alert.ogg') if(sstrength > 5) shipwide_ai_announcement(whattoannounce, MAIN_AI_SYSTEM, 'sound/effects/ob_alert.ogg') addtimer(CALLBACK(GLOBAL_PROC, GLOBAL_PROC_REF(shakeship), sstrength, stime, drop), delayt * 10) else shakeship(sstrength, stime, drop)
1
0.878349
1
0.878349
game-dev
MEDIA
0.451119
game-dev
0.88829
1
0.88829
vlad250906/Create-UfoPort
2,301
modules/create/src/main/java/com/simibubi/create/content/kinetics/base/HorizontalKineticBlock.java
package com.simibubi.create.content.kinetics.base; import com.simibubi.create.foundation.utility.Iterate; import net.minecraft.core.Direction; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.Property; public abstract class HorizontalKineticBlock extends KineticBlock { public static final Property<Direction> HORIZONTAL_FACING = BlockStateProperties.HORIZONTAL_FACING; public HorizontalKineticBlock(Properties properties) { super(properties); } @Override protected void createBlockStateDefinition(Builder<Block, BlockState> builder) { builder.add(HORIZONTAL_FACING); super.createBlockStateDefinition(builder); } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() .setValue(HORIZONTAL_FACING, context.getHorizontalDirection() .getOpposite()); } public Direction getPreferredHorizontalFacing(BlockPlaceContext context) { Direction prefferedSide = null; for (Direction side : Iterate.horizontalDirections) { BlockState blockState = context.getLevel() .getBlockState(context.getClickedPos() .relative(side)); if (blockState.getBlock() instanceof IRotate) { if (((IRotate) blockState.getBlock()).hasShaftTowards(context.getLevel(), context.getClickedPos() .relative(side), blockState, side.getOpposite())) if (prefferedSide != null && prefferedSide.getAxis() != side.getAxis()) { prefferedSide = null; break; } else { prefferedSide = side; } } } return prefferedSide; } @Override public BlockState rotate(BlockState state, Rotation rot) { return state.setValue(HORIZONTAL_FACING, rot.rotate(state.getValue(HORIZONTAL_FACING))); } @Override @SuppressWarnings("deprecation") public BlockState mirror(BlockState state, Mirror mirrorIn) { return state.rotate(mirrorIn.getRotation(state.getValue(HORIZONTAL_FACING))); } }
1
0.898824
1
0.898824
game-dev
MEDIA
0.986146
game-dev
0.938642
1
0.938642
GlowskiBroski/PhoenixClient
2,555
src/main/java/com/phoenixclient/mixin/mixins/MixinGameRenderer.java
package com.phoenixclient.mixin.mixins; import com.llamalad7.mixinextras.sugar.Local; import com.mojang.blaze3d.vertex.PoseStack; import com.phoenixclient.event.Event; import com.phoenixclient.mixin.MixinHooks; import net.minecraft.client.Camera; import net.minecraft.client.DeltaTracker; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(GameRenderer.class) public abstract class MixinGameRenderer { @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;renderItemActivationAnimation(Lnet/minecraft/client/gui/GuiGraphics;F)V")) private void onRender(CallbackInfo ci, @Local(ordinal = 0) GuiGraphics guiGraphics, @Local(ordinal = 0) int i, @Local(ordinal = 1) int j) { Event.EVENT_RENDER_HUD.post(guiGraphics,i,j); } //TODO: Please add guiGraphics as a parameter for the post @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/Screen;handleDelayedNarration()V"), cancellable = true) private void onRenderScreen(DeltaTracker deltaTracker, boolean bl, CallbackInfo ci, @Local(ordinal = 0) GuiGraphics guiGraphics, @Local(ordinal = 0) int i, @Local(ordinal = 1) int j) { Event.EVENT_RENDER_SCREEN.post(guiGraphics, i, j); } @Inject(method = "renderLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/renderer/GameRenderer;renderHand:Z"), cancellable = true) private void onRenderLevel(DeltaTracker deltaTracker, CallbackInfo ci, @Local(ordinal = 1) Matrix4f matrix4f2, @Local(ordinal = 1) float tickDelta) { PoseStack poseStack = new PoseStack(); poseStack.mulPose(matrix4f2); //Matrix4f2 is the POSITION MATRIX Event.EVENT_RENDER_LEVEL.post(poseStack, tickDelta); } @Inject(method = "bobHurt", at = @At(value = "HEAD"), cancellable = true) private void onHurt(PoseStack poseStack, float f, CallbackInfo ci) { if (MixinHooks.noHurtCam) ci.cancel(); } @Inject(method = "bobView", at = @At(value = "HEAD"), cancellable = true) private void onBob(PoseStack poseStack, float f, CallbackInfo ci) { if (MixinHooks.noCameraBob) ci.cancel(); } }
1
0.825124
1
0.825124
game-dev
MEDIA
0.835316
game-dev,graphics-rendering
0.87804
1
0.87804
Benimatic/twilightforest
1,821
src/main/java/twilightforest/entity/ai/EntityAITFRedcapPlantTNT.java
package twilightforest.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import twilightforest.entity.EntityTFRedcap; public class EntityAITFRedcapPlantTNT extends EntityAITFRedcapBase { public EntityAITFRedcapPlantTNT(EntityTFRedcap entityTFRedcap) { this.entityObj = entityTFRedcap; } @Override public boolean shouldExecute() { EntityLivingBase attackTarget = this.entityObj.getAttackTarget(); if (attackTarget != null && entityObj.getTntLeft() > 0 && entityObj.getDistanceSqToEntity(attackTarget) < 25 && !isTargetLookingAtMe(attackTarget) && !isLitTNTNearby(8) && findBlockTNTNearby(5) == null) { //System.out.println("Redcap can plant TNT"); return true; } else { return false; } } /** * Execute a one shot task or start executing a continuous task */ @Override public void startExecuting() { int entityPosX = MathHelper.floor_double(this.entityObj.posX); int entityPosY = MathHelper.floor_double(this.entityObj.posY); int entityPosZ = MathHelper.floor_double(this.entityObj.posZ); //System.out.println("Redcap trying to plant TNT"); this.entityObj.setCurrentItemOrArmor(0, EntityTFRedcap.heldTNT); if (this.entityObj.worldObj.isAirBlock(entityPosX, entityPosY, entityPosZ)) { entityObj.setTntLeft(entityObj.getTntLeft() - 1); entityObj.playLivingSound(); entityObj.worldObj.setBlock(entityPosX, entityPosY, entityPosZ, Blocks.tnt, 0, 3); } } /** * Resets the task */ @Override public void resetTask() { this.entityObj.setCurrentItemOrArmor(0, entityObj.getPick()); } }
1
0.820009
1
0.820009
game-dev
MEDIA
0.988653
game-dev
0.832526
1
0.832526
mouredev/retos-programacion-2023
2,065
Retos/Reto #13 - ADIVINA LA PALABRA [Media]/typescript/chintoz.ts
import readLine from "readline-sync"; let attempts = 10 function selectWordToPlay(): string { // This dictionary could be retrieved from any API let dictionary = ["computacion", "lenguaje", "bucle", "iterador", "patron", "incidente"] let index = Math.ceil(Math.random() * 10000 % dictionary.length) - 1 return dictionary[index]; } function readInput(): string { return readLine.question("Numero de intentos restantes: " + attempts + ". Que valor quieres introducir: ") } function manageWordSelection(word: string, playerInput: string): boolean { if (playerInput === word) { console.log("Has ganado la partida. La palabra seleccionada es la correcta: " + playerInput) return true; } else { console.log("La palabra introducida no es la correcta. Intentalo de nuevo. Número de intentos restantes " + attempts) return false; } } export function playGame() { let word: string = selectWordToPlay() let playerWord = word.split("").map(c => Math.random() <= 0.4 ? c : "*").join("") console.log("Comienza el juego. Tienes " + attempts + " intentos para averiguar la palabra: " + playerWord); while (attempts > 0) { // Introduce un caracter o una palabra let playerInput = readInput(); if (playerInput.length > 1) { if (manageWordSelection(word, playerInput)) { break } } else { playerWord = word.split("") .map((c: string, index: number) => c === playerInput || playerWord[index] !== "*" ? c : "*") .join("") if (playerWord.indexOf("*") < 0) { console.log("Has ganado. Has completado la palabra: " + word) break } else { console.log("Sigue intentandolo. Tienes " + attempts + " intentos para completar la palabra:" + playerWord) } } attempts-- } if (attempts == 0) { console.log("Has perdido. Vuelve a intentarlo cuando quieras.") } } playGame()
1
0.596418
1
0.596418
game-dev
MEDIA
0.533554
game-dev
0.643359
1
0.643359
ppy/osu
1,473
osu.Game.Rulesets.Catch/Edit/PositionRange.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Rulesets.Catch.Edit { /// <summary> /// Represents either the empty range or a closed interval of horizontal positions in the playfield. /// A <see cref="PositionRange"/> represents a closed interval if it is <see cref="Min"/> &lt;= <see cref="Max"/>, and represents the empty range otherwise. /// </summary> public readonly struct PositionRange { public readonly float Min; public readonly float Max; public float Length => Math.Max(0, Max - Min); public PositionRange(float value) : this(value, value) { } public PositionRange(float min, float max) { Min = min; Max = max; } public static PositionRange Union(PositionRange a, PositionRange b) => new PositionRange(Math.Min(a.Min, b.Min), Math.Max(a.Max, b.Max)); /// <summary> /// Get the given position flipped (mirrored) for the axis at the center of this range. /// Returns the given position unchanged if the range was empty. /// </summary> public float GetFlippedPosition(float x) => Min <= Max ? Max - (x - Min) : x; public static readonly PositionRange EMPTY = new PositionRange(float.PositiveInfinity, float.NegativeInfinity); } }
1
0.890569
1
0.890569
game-dev
MEDIA
0.720633
game-dev
0.977788
1
0.977788
CombatExtended-Continued/CombatExtended
4,129
ModPatches/Mechadroids/Patches/Mechadroids/Race_Mechadroids.xml
<?xml version="1.0" encoding="utf-8"?> <Patch> <Operation Class="PatchOperationAddModExtension"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]</xpath> <value> <li Class="CombatExtended.RacePropertiesExtensionCE"> <bodyShape>Humanoid</bodyShape> </li> </value> </Operation> <Operation Class="PatchOperationConditional"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]/comps</xpath> <nomatch Class="PatchOperationAdd"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]</xpath> <value> <comps/> </value> </nomatch> </Operation> <Operation Class="PatchOperationAdd"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]/statBases</xpath> <value> <MeleeDodgeChance>0.9</MeleeDodgeChance> <MeleeCritChance>1</MeleeCritChance> <MeleeParryChance>1</MeleeParryChance> <SmokeSensitivity>0.00</SmokeSensitivity> </value> </Operation> <Operation Class="PatchOperationReplace"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]/statBases/ArmorRating_Sharp</xpath> <value> <ArmorRating_Sharp>1</ArmorRating_Sharp> </value> </Operation> <Operation Class="PatchOperationReplace"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]/statBases/ArmorRating_Blunt</xpath> <value> <ArmorRating_Blunt>2.5</ArmorRating_Blunt> </value> </Operation> <Operation Class="PatchOperationReplace"> <xpath>Defs/AlienRace.ThingDef_AlienRace[defName="O21_Alien_MechadroidAlpha" or defName="O21_Alien_MechadroidGamma"]/tools</xpath> <value> <tools> <li Class="CombatExtended.ToolCE"> <label>left fist</label> <capacities> <li>Blunt</li> </capacities> <power>1</power> <cooldownTime>1.26</cooldownTime> <linkedBodyPartsGroup>LeftHand</linkedBodyPartsGroup> <armorPenetrationBlunt>0.250</armorPenetrationBlunt> </li> <li Class="CombatExtended.ToolCE"> <label>right fist</label> <capacities> <li>Blunt</li> </capacities> <power>1</power> <cooldownTime>1.26</cooldownTime> <linkedBodyPartsGroup>RightHand</linkedBodyPartsGroup> <armorPenetrationBlunt>0.250</armorPenetrationBlunt> </li> <li Class="CombatExtended.ToolCE"> <label>head</label> <capacities> <li>Blunt</li> </capacities> <power>2</power> <cooldownTime>4.49</cooldownTime> <linkedBodyPartsGroup>HeadAttackTool</linkedBodyPartsGroup> <chanceFactor>0.2</chanceFactor> <armorPenetrationBlunt>0.625</armorPenetrationBlunt> </li> </tools> </value> </Operation> <Operation Class="PatchOperationReplace"> <xpath>Defs/AlienRace.ThingDef_AlienRace[defName="O21_Alien_MechadroidDelta"]/tools</xpath> <value> <tools> <li Class="CombatExtended.ToolCE"> <label>left fist</label> <capacities> <li>Blunt</li> </capacities> <power>3</power> <cooldownTime>1.56</cooldownTime> <linkedBodyPartsGroup>LeftHand</linkedBodyPartsGroup> <armorPenetrationBlunt>0.550</armorPenetrationBlunt> </li> <li Class="CombatExtended.ToolCE"> <label>right fist</label> <capacities> <li>Blunt</li> </capacities> <power>3</power> <cooldownTime>1.56</cooldownTime> <linkedBodyPartsGroup>RightHand</linkedBodyPartsGroup> <armorPenetrationBlunt>0.550</armorPenetrationBlunt> </li> <li Class="CombatExtended.ToolCE"> <label>head</label> <capacities> <li>Blunt</li> </capacities> <power>4</power> <cooldownTime>4.89</cooldownTime> <linkedBodyPartsGroup>HeadAttackTool</linkedBodyPartsGroup> <chanceFactor>0.2</chanceFactor> <armorPenetrationBlunt>1.250</armorPenetrationBlunt> </li> </tools> </value> </Operation> <Operation Class="PatchOperationAdd"> <xpath>Defs/AlienRace.ThingDef_AlienRace[@Name="O21_BaseMechadroid"]/comps</xpath> <value> <li> <compClass>CombatExtended.CompPawnGizmo</compClass> </li> <li Class="CombatExtended.CompProperties_Suppressable"/> </value> </Operation> </Patch>
1
0.86032
1
0.86032
game-dev
MEDIA
0.985675
game-dev
0.696059
1
0.696059
Mercurows/SuperbWarfare
3,490
src/main/java/com/atsuishio/superbwarfare/client/model/item/M870ItemModel.java
package com.atsuishio.superbwarfare.client.model.item; import com.atsuishio.superbwarfare.Mod; import com.atsuishio.superbwarfare.client.overlay.CrossHairOverlay; import com.atsuishio.superbwarfare.data.gun.GunData; import com.atsuishio.superbwarfare.event.ClientEventHandler; import com.atsuishio.superbwarfare.item.gun.shotgun.M870Item; import net.minecraft.client.Minecraft; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import software.bernie.geckolib.core.animatable.model.CoreGeoBone; import software.bernie.geckolib.core.animation.AnimationState; public class M870ItemModel extends CustomGunModel<M870Item> { @Override public ResourceLocation getAnimationResource(M870Item animatable) { return Mod.loc("animations/m_870.animation.json"); } @Override public ResourceLocation getModelResource(M870Item animatable) { return Mod.loc("geo/m_870.geo.json"); } @Override public ResourceLocation getTextureResource(M870Item animatable) { return Mod.loc("textures/item/m_870.png"); } @Override public ResourceLocation getLODModelResource(M870Item animatable) { return Mod.loc("geo/lod/m_870.geo.json"); } @Override public ResourceLocation getLODTextureResource(M870Item animatable) { return Mod.loc("textures/item/lod/m_870.png"); } @Override public void setCustomAnimations(M870Item animatable, long instanceId, AnimationState<M870Item> animationState) { Player player = Minecraft.getInstance().player; if (player == null) return; ItemStack stack = player.getMainHandItem(); if (shouldCancelRender(stack, animationState)) return; CoreGeoBone gun = getAnimationProcessor().getBone("bone"); CoreGeoBone shen = getAnimationProcessor().getBone("shen"); double zt = ClientEventHandler.zoomTime; double zp = ClientEventHandler.zoomPos; double zpz = ClientEventHandler.zoomPosZ; gun.setPosX(1.7f * (float) zp); gun.setPosY(1.12f * (float) zp - (float) (0.2f * zpz)); gun.setPosZ(1.5f * (float) zp + (float) (0.9f * zpz)); gun.setRotZ((float) (0.02f * zpz)); gun.setScaleZ(1f - (0.2f * (float) zp)); ClientEventHandler.handleShootAnimation(shen, 1.25f, 4f, 3f, 2.5f, 1.3f, 1f, 0.4f, 0.6f); CrossHairOverlay.gunRot = shen.getRotZ(); ClientEventHandler.gunRootMove(getAnimationProcessor(), -2, 0, 0, false); CoreGeoBone camera = getAnimationProcessor().getBone("camera"); CoreGeoBone main = getAnimationProcessor().getBone("main"); float numR = (float) (1 - 0.72 * zt); float numP = (float) (1 - 0.82 * zt); if (GunData.from(stack).reloading()) { main.setRotX(numR * main.getRotX()); main.setRotY(numR * main.getRotY()); main.setRotZ(numR * main.getRotZ()); main.setPosX(numP * main.getPosX()); main.setPosY(numP * main.getPosY()); main.setPosZ(numP * main.getPosZ()); camera.setRotX(numR * camera.getRotX()); camera.setRotY(numR * camera.getRotY()); camera.setRotZ(numR * camera.getRotZ()); } ClientEventHandler.handleReloadShake(Mth.RAD_TO_DEG * camera.getRotX(), Mth.RAD_TO_DEG * camera.getRotY(), Mth.RAD_TO_DEG * camera.getRotZ()); } }
1
0.767037
1
0.767037
game-dev
MEDIA
0.979241
game-dev
0.86418
1
0.86418
larpon/DeadAscend
1,414
App/qml/AnimatedArea.qml
import QtQuick 2.0 import Qak 1.0 import Qak.Tools 1.0 import "." ImageAnimation { id: area clickable: description !== "" visible: running running: run property bool ready: store.isLoaded && balanced property bool run: false property string name: "" property string description: "" property real margins: core.defaultMargins onInputChanged: { if(input) input.anchors.margins = margins } onMarginsChanged: { if(input) input.anchors.margins = margins } property alias store: store property bool stateless: name == "" function save() { if(!stateless) store.save() } function load() { store.load() } Store { id: store name: area.name !== "" ? "area/"+area.name : "" property alias _x: area.x property alias _y: area.y property alias _state: area.state property alias run: area.run property alias description: area.description } Component.onCompleted: load() Component.onDestruction: save() onClicked: { autoDescription() } function autoDescription() { description = App.eTr(description) if(Aid.isString(description) && description !== "") game.setText(description) if(Aid.isArray(description) && description.length > 0) game.setText.apply(this, description) } }
1
0.714003
1
0.714003
game-dev
MEDIA
0.652837
game-dev
0.943375
1
0.943375
richardbiely/gaia-ecs
4,490
include/gaia/ecs/chunk_header.h
#pragma once #include "../config/config.h" #include <cstdint> #include "../cnt/bitset.h" #include "../core/utility.h" #include "archetype_common.h" #include "chunk_allocator.h" #include "component.h" #include "id.h" namespace gaia { namespace ecs { class World; class ComponentCache; struct ComponentCacheItem; struct ChunkDataOffsets { //! Byte at which the first version number is located ChunkDataVersionOffset firstByte_Versions{}; //! Byte at which the first entity id is located ChunkDataOffset firstByte_CompEntities{}; //! Byte at which the first component id is located ChunkDataOffset firstByte_Records{}; //! Byte at which the first entity is located ChunkDataOffset firstByte_EntityData{}; }; struct ComponentRecord { //! Component id Component comp; //! Pointer to where the first instance of the component is stored uint8_t* pData; //! Pointer to component cache record const ComponentCacheItem* pItem; }; struct ChunkRecords { //! Pointer to where component versions are stored ComponentVersion* pVersions{}; //! Pointer to where (component) entities are stored Entity* pCompEntities{}; //! Pointer to the array of component records ComponentRecord* pRecords{}; //! Pointer to the array of entities Entity* pEntities{}; }; struct ChunkHeader final { static constexpr uint32_t MAX_COMPONENTS_BITS = 5U; //! Maximum number of components on archetype static constexpr uint32_t MAX_COMPONENTS = 1U << MAX_COMPONENTS_BITS; //! Maximum number of entities per chunk. //! Defined as sizeof(big_chunk) / sizeof(entity) static constexpr uint16_t MAX_CHUNK_ENTITIES = (mem_block_size(1) - 64) / sizeof(Entity); static constexpr uint16_t MAX_CHUNK_ENTITIES_BITS = (uint16_t)core::count_bits(MAX_CHUNK_ENTITIES); static constexpr uint16_t CHUNK_LIFESPAN_BITS = 4; //! Number of ticks before empty chunks are removed static constexpr uint16_t MAX_CHUNK_LIFESPAN = (1 << CHUNK_LIFESPAN_BITS) - 1; //! Parent world const World* world; //! Component cache reference const ComponentCache* cc; //! Chunk index in its archetype list uint32_t index; //! Total number of entities in the chunk. uint16_t count; //! Number of enabled entities in the chunk. uint16_t countEnabled; //! Capacity (copied from the owner archetype). uint16_t capacity; //! Index of the first enabled entity in the chunk uint16_t rowFirstEnabledEntity: MAX_CHUNK_ENTITIES_BITS; //! True if there's any generic component that requires custom construction uint16_t hasAnyCustomGenCtor : 1; //! True if there's any unique component that requires custom construction uint16_t hasAnyCustomUniCtor : 1; //! True if there's any generic component that requires custom destruction uint16_t hasAnyCustomGenDtor : 1; //! True if there's any unique component that requires custom destruction uint16_t hasAnyCustomUniDtor : 1; //! Chunk size type. This tells whether it's 8K or 16K uint16_t sizeType : 1; //! When it hits 0 the chunk is scheduled for deletion uint16_t lifespanCountdown: CHUNK_LIFESPAN_BITS; //! True if deleted, false otherwise uint16_t dead : 1; //! Empty space for future use uint16_t unused : 11; //! Number of generic entities/components uint8_t genEntities; //! Number of components on the archetype uint8_t cntEntities; //! Version of the world (stable pointer to parent world's world version) uint32_t& worldVersion; static inline uint32_t s_worldVersionDummy = 0; ChunkHeader(): worldVersion(s_worldVersionDummy) {} ChunkHeader( const World& wld, const ComponentCache& compCache, uint32_t chunkIndex, uint16_t cap, uint8_t genEntitiesCnt, uint16_t st, uint32_t& version): world(&wld), cc(&compCache), index(chunkIndex), count(0), countEnabled(0), capacity(cap), // rowFirstEnabledEntity(0), hasAnyCustomGenCtor(0), hasAnyCustomUniCtor(0), hasAnyCustomGenDtor(0), hasAnyCustomUniDtor(0), sizeType(st), lifespanCountdown(0), dead(0), unused(0), // genEntities(genEntitiesCnt), cntEntities(0), worldVersion(version) { // Make sure the alignment is right GAIA_ASSERT(uintptr_t(this) % (sizeof(size_t)) == 0); } bool has_disabled_entities() const { return rowFirstEnabledEntity > 0; } bool has_enabled_entities() const { return countEnabled > 0; } }; } // namespace ecs } // namespace gaia
1
0.915388
1
0.915388
game-dev
MEDIA
0.223592
game-dev
0.544435
1
0.544435
BigheadSMZ/Zelda-LA-DX-HD-Updated
12,328
ladxhd_game_source_code/InGame/GameObjects/NPCs/ObjDog.cs
using System; using Microsoft.Xna.Framework; using ProjectZ.InGame.GameObjects.Base; using ProjectZ.InGame.GameObjects.Base.CObjects; using ProjectZ.InGame.GameObjects.Base.Components; using ProjectZ.InGame.GameObjects.Base.Components.AI; using ProjectZ.InGame.GameObjects.Base.Systems; using ProjectZ.InGame.GameObjects.Things; using ProjectZ.InGame.Map; using ProjectZ.InGame.SaveLoad; using ProjectZ.InGame.Things; namespace ProjectZ.InGame.GameObjects.NPCs { internal class ObjDog : GameObject { private readonly BodyComponent _body; private readonly AiComponent _aiComponent; private readonly AiDamageState _damageState; private readonly AiTriggerSwitch _changeDirectionSwitch; private readonly Animator _animator; private readonly HittableComponent _hitComponent; private readonly PushableComponent _pushComponent; private readonly InteractComponent _interactComponent; private readonly KeyChangeListenerComponent _listenerComponent; private readonly DamageFieldComponent _damageField; private Vector2 _marinPosition; private int _direction; public ObjDog() : base("dog") { } public ObjDog(Map.Map map, int posX, int posY) : base(map) { EntityPosition = new CPosition(posX + 8, posY + 16, 0); EntitySize = new Rectangle(-8, -16, 16, 16); _body = new BodyComponent(EntityPosition, -6, -8, 12, 8, 8) { MoveCollision = OnCollision, Gravity = -0.15f, Drag = 0.75f, DragAir = 0.95f, AvoidTypes = Values.CollisionTypes.Hole | Values.CollisionTypes.NPCWall, }; _animator = AnimatorSaveLoad.LoadAnimator("NPCs/dog"); var sprite = new CSprite(EntityPosition); var animationComponent = new AnimationComponent(_animator, sprite, Vector2.Zero); var stateIdle = new AiState() { Init = InitIdle }; stateIdle.Trigger.Add(new AiTriggerRandomTime(() => _aiComponent.ChangeState("walking"), 500, 1500)); var stateWalking = new AiState(UpdateWalking) { Init = InitWalking }; stateWalking.Trigger.Add(new AiTriggerRandomTime(() => _aiComponent.ChangeState("idle"), 750, 1500)); stateWalking.Trigger.Add(_changeDirectionSwitch = new AiTriggerSwitch(250)); var stateListening = new AiState(UpdateListening); var statePreAttack = new AiState(); statePreAttack.Trigger.Add(new AiTriggerCountdown(500, null, () => _aiComponent.ChangeState("attack"))); var stateAttack = new AiState(UpdateAttack) { Init = InitAttack }; _aiComponent = new AiComponent(); _aiComponent.States.Add("idle", stateIdle); _aiComponent.States.Add("walking", stateWalking); _aiComponent.States.Add("listening", stateListening); _aiComponent.States.Add("preAttack", statePreAttack); _aiComponent.States.Add("attack", stateAttack); _damageState = new AiDamageState(this, _body, _aiComponent, sprite, 2) { OnBurn = OnBurn }; _aiComponent.ChangeState(Game1.RandomNumber.Next(0, 10) < 5 ? "idle" : "walking"); var box = new CBox(EntityPosition, -7, -14, 14, 14, 8); AddComponent(KeyChangeListenerComponent.Index, _listenerComponent = new KeyChangeListenerComponent(OnKeyChange)); AddComponent(DamageFieldComponent.Index, _damageField = new DamageFieldComponent(box, HitType.Enemy, 2) { IsActive = false }); AddComponent(HittableComponent.Index, _hitComponent = new HittableComponent(box, OnHit)); AddComponent(BodyComponent.Index, _body); AddComponent(AiComponent.Index, _aiComponent); AddComponent(BaseAnimationComponent.Index, animationComponent); AddComponent(PushableComponent.Index, _pushComponent = new PushableComponent(_body.BodyBox, OnPush)); AddComponent(DrawComponent.Index, new BodyDrawComponent(_body, sprite, Values.LayerPlayer)); AddComponent(DrawShadowComponent.Index, new BodyDrawShadowComponent(_body, sprite) { ShadowWidth = 10 }); AddComponent(InteractComponent.Index, _interactComponent = new InteractComponent(_body.BodyBox, Interact)); new ObjSpriteShadow("sprshadowm", this, Values.LayerPlayer, map); } private void OnKeyChange() { var marinPosition = Game1.GameManager.SaveManager.GetString("marin_sing_position"); if (!string.IsNullOrEmpty(marinPosition)) { var splitString = marinPosition.Split(','); if (splitString.Length == 2) { int.TryParse(splitString[0], out int posX); int.TryParse(splitString[1], out int posY); _marinPosition = new Vector2(posX, posY); } } else { _marinPosition = Vector2.Zero; } } private void InitIdle() { // stop and wait _body.VelocityTarget.X = 0; _body.VelocityTarget.Y = 0; _body.CollisionTypes = Values.CollisionTypes.Normal | Values.CollisionTypes.NPCWall; _animator.Play("idle_" + _direction); } private void InitWalking() { // change the direction var rotation = Game1.RandomNumber.Next(0, 628) / 100f; var speed = Game1.RandomNumber.Next(40, 55) / 100f; _body.VelocityTarget = new Vector2((float)Math.Sin(rotation), (float)Math.Cos(rotation)) * speed; UpdateAnimation(); } private void UpdateWalking() { // jump up and down while walking if (_body.IsGrounded) { _body.Velocity.Z = 0.85f; if (_marinPosition != Vector2.Zero) { var direction = _marinPosition - EntityPosition.Position; var distance = direction.Length(); if (distance < 24) { _body.Velocity.Z = 0; _body.VelocityTarget = Vector2.Zero; _direction = direction.X < 0 ? 0 : 1; _animator.Play("idle_" + _direction); _aiComponent.ChangeState("listening"); } else if (distance < 64) { if (direction != Vector2.Zero) direction.Normalize(); _body.VelocityTarget = direction * 0.5f; UpdateAnimation(); } } } } private void OnBurn() { _damageField.IsActive = false; _hitComponent.IsActive = false; _pushComponent.IsActive = false; _interactComponent.IsActive = false; if (_listenerComponent != null) RemoveComponent(KeyChangeListenerComponent.Index); _animator.Pause(); } private void UpdateListening() { if (_marinPosition == Vector2.Zero) _aiComponent.ChangeState("walking"); } private void InitAttack() { var playerDirection = MapManager.ObjLink.EntityPosition.Position - EntityPosition.Position; if (playerDirection != Vector2.Zero) playerDirection.Normalize(); _body.VelocityTarget = playerDirection * 3; _body.CollisionTypes = Values.CollisionTypes.Normal | Values.CollisionTypes.NPCWall; _body.IsGrounded = false; _body.Velocity.Z = 1.45f; _damageField.IsActive = true; UpdateAnimation(); } private void UpdateAttack() { // finished attacking? if (_body.IsGrounded) { _damageField.IsActive = false; _aiComponent.ChangeState("idle"); } } private void UpdateAnimation() { _direction = _body.VelocityTarget.X < 0 ? 0 : 1; _animator.Play("idle_" + _direction); } private bool OnPush(Vector2 direction, PushableComponent.PushType type) { if (_aiComponent.CurrentStateId == "preAttack" || _aiComponent.CurrentStateId == "attack") return false; if (type == PushableComponent.PushType.Continues) { // push the dog away SystemBody.MoveBody(_body, new Vector2(direction.X, direction.Y) * 0.33f * Game1.TimeMultiplier, _body.CollisionTypes, false, false, false); _body.Position.NotifyListeners(); if (_aiComponent.CurrentStateId == "walking") return true; // start moving away from the pusher _aiComponent.ChangeState("walking"); var offsetAngle = MathHelper.ToRadians(Game1.RandomNumber.Next(55, 85) * (Game1.RandomNumber.Next(0, 2) * 2 - 1)); var newDirection = new Vector2( direction.X * (float)Math.Cos(offsetAngle) - direction.Y * (float)Math.Sin(offsetAngle), direction.X * (float)Math.Sin(offsetAngle) + direction.Y * (float)Math.Cos(offsetAngle)) * 0.5f; _body.VelocityTarget = newDirection; UpdateAnimation(); } else if (type == PushableComponent.PushType.Impact) { _aiComponent.ChangeState("idle"); _body.VelocityTarget = Vector2.Zero; _body.Velocity = new Vector3(direction.X, direction.Y, 0.25f); } return true; } private void OnCollision(Values.BodyCollision moveCollision) { if (_aiComponent.CurrentStateId == "attack") return; // rotate after wall collision // horizontal collision if ((moveCollision & Values.BodyCollision.Horizontal) != 0) { if (!_changeDirectionSwitch.State) return; _changeDirectionSwitch.Reset(); _body.VelocityTarget.X = -_body.VelocityTarget.X; UpdateAnimation(); } // vertical collision else if ((moveCollision & Values.BodyCollision.Vertical) != 0) { _body.VelocityTarget.Y = -_body.VelocityTarget.Y; } } private Values.HitCollision OnHit(GameObject originObject, Vector2 direction, HitType type, int damage, bool pieceOfPower) { if (GameSettings.NoAnimalDamage) return Values.HitCollision.None; if (type == HitType.MagicPowder || type == HitType.MagicRod) { if (_aiComponent.CurrentStateId != "burning") { _aiComponent.ChangeState("burning"); var speedMultiply = (type == HitType.MagicPowder ? 0.125f : 0.5f); Game1.GameManager.PlaySoundEffect("D378-18-12"); return Values.HitCollision.Enemy; } } if (_aiComponent.CurrentStateId == "idle" || _aiComponent.CurrentStateId == "walking") { Game1.GameManager.PlaySoundEffect("D360-03-03"); _aiComponent.ChangeState("preAttack"); _damageState.SetDamageState(); _body.Velocity = new Vector3(direction * 1.5f, 0); return Values.HitCollision.Enemy; } return Values.HitCollision.None; } private bool Interact() { if (_aiComponent.CurrentStateId == "listening") Game1.GameManager.StartDialogPath("animals_absorbed"); else Game1.GameManager.StartDialogPath("dog"); return true; } } }
1
0.884537
1
0.884537
game-dev
MEDIA
0.987783
game-dev
0.979986
1
0.979986
v3921358/MapleRoot
15,626
MapleRoot/scripts/npc/1032001.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> 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 version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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/>. */ /* Grendel the Really Old Magician Job Advancement Victoria Road : Magic Library (101000003) Custom Quest 100006, 100008, 100100, 100101 */ status = -1; actionx = {"1stJob": false, "2ndjob": false, "3thJobI": false, "3thJobC": false}; job = 210; spawnPnpc = false; spawnPnpcFee = 7000000; jobType = 2; function start() { const GameConstants = Java.type('constants.game.GameConstants'); if (parseInt(cm.getJobId() / 100) == jobType && cm.canSpawnPlayerNpc(GameConstants.getHallOfFameMapid(cm.getJob()))) { spawnPnpc = true; var sendStr = "You have walked a long way to reach the power, wisdom and courage you hold today, haven't you? What do you say about having right now #ra NPC on the Hall of Fame holding the current image of your character#k? Do you like it?"; if (spawnPnpcFee > 0) { sendStr += " I can do it for you, for the fee of #b " + cm.numberWithCommas(spawnPnpcFee) + " mesos.#k"; } cm.sendYesNo(sendStr); } else { if (cm.getJobId() == 0) { actionx["1stJob"] = true; cm.sendNext("Want to be a #rmagician#k? There are some standards to meet. because we can't just accept EVERYONE in... #bYour level should be at least 8#k, with getting " + cm.getFirstJobStatRequirement(jobType) + " as your top priority. Let's see."); // thanks Vcoc for noticing a need to state and check requirements on first job adv starting message } else if (cm.getLevel() >= 30 && cm.getJobId() == 200) { actionx["2ndJob"] = true; if (cm.haveItem(4031012)) { cm.sendNext("I see you have done well. I will allow you to take the next step on your long road."); } else if (cm.haveItem(4031009)) { cm.sendOk("Go and see the #b#p1072001##k."); cm.dispose(); } else { cm.sendNext("The progress you have made is astonishing."); } } else if (actionx["3thJobI"] || (cm.getPlayer().gotPartyQuestItem("JB3") && cm.getLevel() >= 70 && cm.getJobId() % 10 == 0 && parseInt(cm.getJobId() / 100) == 2 && !cm.getPlayer().gotPartyQuestItem("JBP"))) { actionx["3thJobI"] = true; cm.sendNext("There you are. A few days ago, #b#p2020009##k of Ossyria talked to me about you. I see that you are interested in making the leap to the enlightened of the third job advancement for magicians. To archieve that goal, I will have to test your strength in order to see whether you are worthy of the advancement. There is an opening in the middle of a deep forest of evil in Victoria Island, where it'll lead you to a secret passage. Once inside, you'll face a clone of myself. Your task is to defeat him and bring #b#t4031059##k back with you."); } else if (cm.getPlayer().gotPartyQuestItem("JBP") && !cm.haveItem(4031059)) { cm.sendNext("Please, bring me the #b#t4031059##k from my clone. You can find him inside a hole in space which is deep in a forest of evil."); cm.dispose(); } else if (cm.haveItem(4031059) && cm.getPlayer().gotPartyQuestItem("JBP")) { actionx["3thJobC"] = true; cm.sendNext("Nice work. You have defeated my clone and brought #b#t4031059##k back safely. You have now proven yourself worthy of the 3rd job advancement from the physical standpoint. Now you should give this necklace to #b#p2020011##k in Ossyria to take on the second part of the test. Good luck. You'll need it."); } else { cm.sendOk("You have chosen wisely."); cm.dispose(); } } } function action(mode, type, selection) { status++; if (mode == -1 && selection == -1) { cm.dispose(); return; } else if (mode == 0 && type == 0) { status -= 2; } if (status == -1) { start(); return; } else { if (spawnPnpc) { if (mode > 0) { if (cm.getMeso() < spawnPnpcFee) { cm.sendOk("Sorry, you don't have enough mesos to purchase your place on the Hall of Fame."); cm.dispose(); return; } const PlayerNPC = Java.type('server.life.PlayerNPC'); const GameConstants = Java.type('constants.game.GameConstants'); if (PlayerNPC.spawnPlayerNPC(GameConstants.getHallOfFameMapid(cm.getJob()), cm.getPlayer())) { cm.sendOk("There you go! Hope you will like it."); cm.gainMeso(-spawnPnpcFee); } else { cm.sendOk("Sorry, the Hall of Fame is currently full..."); } } cm.dispose(); return; } else { if (mode != 1 || status == 7 || (actionx["1stJob"] && status == 4) || (cm.haveItem(4031008) && status == 2) || (actionx["3thJobI"] && status == 1)) { if (mode == 0 && status == 2 && type == 1) { cm.sendOk("You know there is no other choice..."); } if (!(mode == 0 && type == 0)) { cm.dispose(); return; } } } } if (actionx["1stJob"]) { if (status == 0) { if (cm.getLevel() >= 8 && cm.getPlayer().getSkillLevel(1051) == 0 && cm.canGetFirstJob(jobType)) { cm.sendYesNo("Oh...! You look like someone that can definitely be a part of us... all you need is a little sinister mind, and... yeah... so, what do you think? Wanna be the Magician?"); } else { cm.sendOk("Train a bit more until you reach the base requirements and I can show you the way of the #rMagician#k."); cm.dispose(); } } else if (status == 1) { if (cm.canHold(1372043)) { if (cm.getJobId() == 0) { cm.changeJobById(200); cm.gainItem(1372043, 1); cm.resetStats(); } cm.sendNext("Alright, from here out, you are a part of us! You'll be living the life of a wanderer at ..., but just be patient as soon, you'll be living the high life. Alright, it ain't much, but I'll give you some of my abilities... HAAAHHH!!!"); } else { cm.sendNext("Make some room in your inventory and talk back to me."); cm.dispose(); } } else if (status == 2) { cm.sendNextPrev("You've gotten much stronger now. Plus every single one of your inventories have added slots. A whole row, to be exact. Go see for it yourself. I just gave you a little bit of #bSP#k. When you open up the #bSkill#k menu on the lower left corner of the screen, there are skills you can learn by using SP's. One warning, though: You can't raise it all together all at once. There are also skills you can acquire only after having learned a couple of skills first."); } else if (status == 3) { cm.sendNextPrev("But remember, skills aren't everything. Your stats should support your skills as a Magician, also. Magicians use INT as their main stat, and LUK as their secondary stat. If raising stats is difficult, just use #bAuto-Assign#k"); } else if (status == 4) { cm.sendNextPrev("Now, one more word of warning to you. If you fail in battle from this point on, you will lose a portion of your total EXP. Be extra mindful of this, since you have less HP than most."); } else if (status == 5) { cm.sendNextPrev("This is all I can teach you. Good luck on your journey, young Magician."); } else { cm.dispose(); } } else if (actionx["2ndJob"]) { if (status == 0) { if (cm.haveItem(4031012)) { cm.sendSimple("Alright, when you have made your decision, click on [I'll choose my occupation] at the bottom.#b\r\n#L0#Please explain to me what being the Wizard (Fire / Poison) is all about.\r\n#L1#Please explain to me what being the Wizard (Ice / Lighting) is all about.\r\n#L2#Please explain to me what being the Cleric is all about.\r\n#L3#I'll choose my occupation!"); } else { cm.sendNext("Good decision. You look strong, but I need to see if you really are strong enough to pass the test, it's not a difficult test, so you'll do just fine. Here, take my letter first... make sure you don't lose it!"); if (!cm.isQuestStarted(100006)) { cm.startQuest(100006); } } } else if (status == 1) { if (!cm.haveItem(4031012)) { if (cm.canHold(4031009)) { if (!cm.haveItem(4031009)) { cm.gainItem(4031009, 1); } cm.sendNextPrev("Please get this letter to #b#p1072001##k who's around #b#m101020000##k near Ellinia. He is taking care of the job of an instructor in place of me. Give him the letter and he'll test you in place of me. Best of luck to you."); } else { cm.sendNext("Please, make some space in your inventory."); cm.dispose(); } } else { if (selection < 3) { if (selection == 0) { cm.sendNext("Magicians that master #rFire/Poison-based magic#k.\r\n\r\n#bWizards#k are a active class that deal magical, elemental damage. These abilities grants them a significant advantage against enemies weak to their element. With their skills #rMeditation#k and #rSlow#k, #bWizards#k can increase their magic attack and reduce the opponent's mobility. #bFire/Poison Wizards#k contains a powerful flame arrow attack and poison attack."); //f/p mage } else if (selection == 1) { cm.sendNext("Magicians that master #rIce/Lightning-based magic#k.\r\n\r\n#bWizards#k are a active class that deal magical, elemental damage. These abilities grants them a significant advantage against enemies weak to their element. With their skills #rMeditation#k and #rSlow#k, #bWizards#k can increase their magic attack and reduce the opponent's mobility. #bIce/Lightning Wizards#k have a freezing ice attack and a striking lightning attack."); //i/l mage } else { cm.sendNext("Magicians that master #rHoly magic#k.\r\n\r\n#bClerics#k are a powerful supportive class, bound to be accepted into any Party. That's because the have the power to #rHeal#k themselves and others in their party. Using #rBless#k, #bClerics#k can buff the attributes and reduce the amount of damage taken. This class is on worth going for if you find it hard to survive. #bClerics#k are especially effective against undead monsters."); //cleric } status -= 2; } else { cm.sendSimple("Now... have you made up your mind? Please choose the job you'd like to select for your 2nd job advancement. #b\r\n#L0#Wizard (Fire / Poison)\r\n#L1#Wizard (Ice / Lighting)\r\n#L2#Cleric"); } } } else if (status == 2) { if (cm.haveItem(4031009)) { cm.dispose(); return; } job += selection * 10; cm.sendYesNo("So you want to make the second job advancement as the " + (job == 210 ? "#bWizard (Fire / Poison)#k" : job == 220 ? "#bWizard (Ice / Lighting)#k" : "#bCleric#k") + "? You know you won't be able to choose a different job for the 2nd job advancement once you make your desicion here, right?"); } else if (status == 3) { if (cm.haveItem(4031012)) { cm.gainItem(4031012, -1); } cm.completeQuest(100008); cm.sendNext("Alright, you're the " + (job == 210 ? "#bWizard (Fire / Poison)#k" : job == 220 ? "#bWizard (Ice / Lighting)#k" : "#bCleric#k") + " from here on out. Mages and wizards are the intelligent bunch with incredible magical prowess, able to pierce the mind and the psychological structure of the monsters with ease... please train yourself each and everyday. I'll help you become even stronger than you already are."); if (cm.getJobId() != job) { cm.changeJobById(job); } } else if (status == 4) { cm.sendNextPrev("I have just given you a book that gives you the list of skills you can acquire as a " + (job == 210 ? "#bWizard (Fire / Poison)#k" : job == 220 ? "#bWizard (Ice / Lighting)#k" : "#bCleric#k") + ". Also your etc inventory has expanded by adding another row to it. Your max HP and MP have increased, too. Go check and see for it yourself."); } else if (status == 5) { cm.sendNextPrev("I have also given you a little bit of #bSP#k. Open the #bSkill Menu#k located at the bottomleft corner. you'll be able to boost up the newer acquired 2nd level skills. A word of warning, though. You can't boost them up all at once. Some of the skills are only available after you have learned other skills. Make sure you remember that."); } else if (status == 6) { cm.sendNextPrev((job == 210 ? "Wizard (Fire / Poison)" : job == 220 ? "Wizard (Ice / Lighting)" : "Cleric") + " need to be strong. But remember that you can't abuse that power and use it on a weakling. Please use your enormous power the right way, because... for you to use that the right way, that is much harden than just getting stronger. Please find me after you have advanced much further. I'll be waiting for you."); } } else if (actionx["3thJobI"]) { if (status == 0) { if (cm.getPlayer().gotPartyQuestItem("JB3")) { cm.getPlayer().removePartyQuestItem("JB3"); cm.getPlayer().removePartyQuestItem("JB3"); cm.getPlayer().setPartyQuestItemObtained("JBP"); } cm.sendNextPrev("Since he is a clone of myself, you can expect a tough battle ahead. He uses a number of special attacking skills unlike any you have ever seen, and it is your task to successfully take him one on one. There is a time limit in the secret passage, so it is crucial that you defeat him within the time limit. I wish you the best of luck, and I hope you bring the #b#t4031059##k with you."); } } else if (actionx["3thJobC"]) { cm.getPlayer().removePartyQuestItem("JBP"); cm.gainItem(4031059, -1); cm.gainItem(4031057, 1); cm.dispose(); } }
1
0.776779
1
0.776779
game-dev
MEDIA
0.957762
game-dev
0.824831
1
0.824831
LeoMinecraftModding/eternal-starlight
3,422
common/src/main/java/cn/leolezury/eternalstarlight/common/block/SimpleMultifaceBlock.java
package cn.leolezury.eternalstarlight.common.block; import com.mojang.serialization.MapCodec; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; public class SimpleMultifaceBlock extends MultifaceBlock implements BonemealableBlock, SimpleWaterloggedBlock { public static final MapCodec<SimpleMultifaceBlock> CODEC = simpleCodec(SimpleMultifaceBlock::new); private static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; private final MultifaceSpreader spreader = new MultifaceSpreader(this); @Override protected MapCodec<? extends SimpleMultifaceBlock> codec() { return CODEC; } public SimpleMultifaceBlock(BlockBehaviour.Properties properties) { super(properties); this.registerDefaultState(this.defaultBlockState().setValue(WATERLOGGED, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(WATERLOGGED); } @Override public BlockState updateShape(BlockState state, Direction direction, BlockState state1, LevelAccessor level, BlockPos pos, BlockPos pos1) { if (state.getValue(WATERLOGGED)) { level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); } return super.updateShape(state, direction, state1, level, pos, pos1); } @Override protected boolean canBeReplaced(BlockState state, BlockPlaceContext context) { return !(context.getItemInHand().getItem() instanceof BlockItem item && item.getBlock() == this) || super.canBeReplaced(state, context); } @Override public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state) { return Direction.stream().anyMatch((direction) -> this.spreader.canSpreadInAnyDirection(state, level, pos, direction.getOpposite())); } @Override public boolean isBonemealSuccess(Level level, RandomSource randomSource, BlockPos pos, BlockState state) { return true; } @Override public void performBonemeal(ServerLevel level, RandomSource randomSource, BlockPos pos, BlockState state) { this.spreader.spreadFromRandomFaceTowardRandomDirection(state, level, pos, randomSource); } @Override public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override public boolean propagatesSkylightDown(BlockState state, BlockGetter blockGetter, BlockPos pos) { return state.getFluidState().isEmpty(); } @Override public MultifaceSpreader getSpreader() { return this.spreader; } }
1
0.756319
1
0.756319
game-dev
MEDIA
0.99858
game-dev
0.913106
1
0.913106
ReikaKalseki/ChromatiCraft
3,947
Block/Dye/BlockDyeSapling.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ChromatiCraft.Block.Dye; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockSapling; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import Reika.ChromatiCraft.ChromatiCraft; import Reika.ChromatiCraft.World.TreeShaper; import Reika.DragonAPI.Libraries.Registry.ReikaDyeHelper; import Reika.DragonAPI.Libraries.Registry.ReikaItemHelper; import Reika.DragonAPI.Libraries.Registry.ReikaPlantHelper; import Reika.DragonAPI.Libraries.World.ReikaBlockHelper; import Reika.DragonAPI.Libraries.World.ReikaWorldHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockDyeSapling extends BlockSapling { private IIcon icon; private static Random r = new Random(); public BlockDyeSapling() { super(); this.setCreativeTab(ChromatiCraft.tabChromaGen); this.setStepSound(soundTypeGrass); } @Override public void func_149878_d(World world, int x, int y, int z, Random r) { if (this.canGrowAt(world, x, y, z, false)) this.func_149878_d(world, x, y, z, this.getGrowthHeight()); } private int getGrowthHeight() { return 5+r.nextInt(3); } public void func_149878_d(World world, int x, int y, int z, int h) { if (world.isRemote) return; int meta = world.getBlockMetadata(x, y, z); TreeShaper.getInstance().generateRandomWeightedTree(world, x, y, z, world.rand, ReikaDyeHelper.dyes[meta], true, 0.25F, 0); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer ep, int p6, float a, float b, float c) { ItemStack is = ep.getCurrentEquippedItem(); if (is == null) return false; if (!ReikaItemHelper.matchStacks(is, ReikaDyeHelper.WHITE.getStackOf())) return false; int color = world.getBlockMetadata(x, y, z); if (this.canGrowAt(world, x, y, z, true)) this.func_149878_d(world, x, y, z, ep.isSneaking() ? 7 : this.getGrowthHeight()); else world.spawnParticle("happyVillager", x+r.nextDouble(), y+r.nextDouble(), z+r.nextDouble(), 0, 0, 0); if (!ep.capabilities.isCreativeMode) is.stackSize--; return true; } @Override public IIcon getIcon(int par1, int par2) { return icon; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister ico) { icon = ico.registerIcon("ChromatiCraft:dye/sapling"); } @Override public int getRenderColor(int dmg) { return ReikaDyeHelper.dyes[dmg].getColor(); } @Override public int colorMultiplier(IBlockAccess iba, int x, int y, int z) { int dmg = iba.getBlockMetadata(x, y, z); return ReikaDyeHelper.dyes[dmg].getJavaColor().brighter().getRGB(); } public static boolean canGrowAt(World world, int x, int y, int z, boolean ignoreLight) { Block id = world.getBlock(x, y, z); if (!ReikaPlantHelper.SAPLING.canPlantAt(world, x, y, z)) return false; if (ReikaBlockHelper.isLiquid(id)) return false; for (int i = 1; i < 6; i++) { id = world.getBlock(x, y+i, z); if (!ReikaWorldHelper.softBlocks(world, x, y+i, z)) return false; if (ReikaBlockHelper.isLiquid(id)) return false; } return ignoreLight || world.getBlockLightValue(x, y, z) >= 9; } @Override public void func_149879_c(World par1World, int par2, int par3, int par4, Random par5Random) { this.func_149878_d(par1World, par2, par3, par4, par5Random); } @Override public int damageDropped(int par1) { return par1; } }
1
0.546027
1
0.546027
game-dev
MEDIA
0.974496
game-dev
0.799159
1
0.799159
lurenpluto/BOLT_SDK
5,171
boltsdk_2008/samples/BoltFox/xar/BoltFox/layout/MainMenu.xml.lua
function CreateMenuItemContainer(self,...) local itemContainer = {} itemContainer.items = {...} itemContainer.hoveringItem = nil itemContainer.enteredItem = nil itemContainer.ChangeEnteredItem = function(self2,enteredItem) if self2.enteredItem then self2.enteredItem:SetEntered(false) end if enteredItem then enteredItem:SetEntered(true) end self2.enteredItem = enteredItem end itemContainer.GetHoveringItem = function(self2) return self2.hoveringItem end itemContainer.ChangeHoveringItem = function(self2,hoveringItem) if hoveringItem and self2.hoveringItem then if hoveringItem:GetID() == self2.hoveringItem:GetID() then return end end if hoveringItem then if not hoveringItem:PopupSubMenu() then hoveringItem = nil end end if self2.hoveringItem then self2.hoveringItem:DestroySubMenu() end self2.hoveringItem = hoveringItem end return itemContainer end function MainMenu_Item_OnInitControl(self) local attr = self:GetAttribute() self:SetText(attr.Text) if attr.SubMenuTemplate then local tosubObj = self:GetControlObject("tosub") tosubObj:SetVisible(true) end end function MainMenu_Item_OnLButtonDown(self) local attr = self:GetAttribute() if not attr.SubMenuTemplate then self:FireExtEvent("OnSelected") self:GetOwner():GetBindHostWnd():EndMenu() end end function MainMenu_Item_SetEntered(self,entered) local hoverBkg = self:GetControlObject("hoverBkg") hoverBkg:SetVisible(entered) end function MainMenu_Item_OnMouseLeave(self) local attr = self:GetAttribute() attr.mouseHovering = false local hoveringItem = attr.itemContainer:GetHoveringItem() if hoveringItem and hoveringItem:GetID() == self:GetID() then return end self:SetEntered(false) end function MainMenu_Item_OnMouseEnter(self) local attr = self:GetAttribute() attr.itemContainer:ChangeEnteredItem(self) attr.mouseHovering = true SetOnceTimer(function() if attr.mouseHovering then attr.itemContainer:ChangeHoveringItem(self) end end, 500) end function MainMenu_Item_SetContainer(self,itemContainer) local attr = self:GetAttribute() attr.itemContainer = itemContainer end function MainMenu_Item_PopupSubMenu(self) local attr = self:GetAttribute() if attr.SubMenuTemplate then local templateMananger = XLGetObject("Xunlei.UIEngine.TemplateManager") local subMenuTemplate = templateMananger:GetTemplate(attr.SubMenuTemplate,"ObjectTemplate") local controlId = self:GetID() if not attr.subMenuObj then local subMenuObj = subMenuTemplate:CreateInstance(controlId.."."..attr.SubMenuTemplate) if subMenuObj then self:AddChild(subMenuObj) subMenuObj:SetZorder(500) local left, top ,right , bottom = subMenuObj:GetObjPos() subMenuObj:SetObjPos("father.width-5", "5", right - left, bottom - top) attr.subMenuObj = subMenuObj end end return true end return false end function MainMenu_Item_DestroySubMenu(self) local attr = self:GetAttribute() if attr.SubMenuTemplate then local controlId = self:GetID() if attr.subMenuObj then self:RemoveChild(attr.subMenuObj) attr.subMenuObj = nil end return true end return false end function MainMenu_Item_SetText(self,text) local attr = self:GetAttribute() attr.Text = text local textObj = self:GetControlObject("text") textObj:SetText(attr.Text) end function MainMenu_Item_GetText(self) local attr = self:GetAttribute() return attr.Text end function MainMenu_SubMenu_RecentUrls_Item_OnSelected(self) local url = self:GetText() ---- open url here ----- XLGetGlobal("BoltFox.UIHelper"):NavigateToUrl(url, true) end function MainMenu_SubMenu_RecentUrls_OnBind(self) local history = XLGetGlobal("BoltFox.History") local recentUrls = history:GetRecentUrls() --recentUrls = {"xunlei.com", "163.com"} local templateMananger = XLGetObject("Xunlei.UIEngine.TemplateManager") local bkgObj = self:GetChildByIndex(0) local itemTop = 0 local urlCnt = table.maxn(recentUrls) local blankItem = bkgObj:GetChildByIndex(0) local itemContainer = CreateMenuItemContainer() if urlCnt ~= 0 then bkgObj:RemoveChild(blankItem) local itemTemplate = templateMananger:GetTemplate("BoltFox.MainMenu.SubMenu.RecentUrls.Item","ObjectTemplate") XLLog("renct urls has "..urlCnt) for i=1, urlCnt do local itemObj = itemTemplate:CreateInstance("RecentUrls.item."..i) itemObj:SetContainer(itemContainer) itemTop = 21 * (i - 1) itemObj:SetObjPos("0", tostring(itemTop) , "father.width", tostring(itemTop + 20)) itemObj:SetText(recentUrls[i]) bkgObj:AddChild(itemObj) end else blankItem:SetContainer(itemContainer) end itemTop = itemTop + 21 bkgObj:SetObjPos("0","0","father.width",tostring(itemTop)) end function MainMenu_OnInitControl(self) local menuItem1 = self:GetOwner():GetUIObject("item.RecentUrls") local menuItem2 = self:GetOwner():GetUIObject("item.Quit") local itemContainer = CreateMenuItemContainer(menuItem1, menuItem2) menuItem1:SetContainer(itemContainer) menuItem2:SetContainer(itemContainer) end function MainMenu_item_Quit_OnSelected(self) local uiHelper = XLGetGlobal("BoltFox.UIHelper") uiHelper:QuitApp() end function OnPopupMenu() end
1
0.909505
1
0.909505
game-dev
MEDIA
0.737066
game-dev
0.935919
1
0.935919
terrarium-earth/Ad-Astra
19,810
neoforge/src/main/java/earth/terrarium/adastra/datagen/provider/server/tags/ModItemTagProvider.java
package earth.terrarium.adastra.datagen.provider.server.tags; import com.teamresourceful.resourcefullib.common.registry.RegistryEntry; import earth.terrarium.adastra.AdAstra; import earth.terrarium.adastra.common.registry.ModBlocks; import earth.terrarium.adastra.common.registry.ModItems; import earth.terrarium.adastra.common.tags.ModItemTags; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; import net.minecraft.data.tags.TagsProvider; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.neoforged.neoforge.common.data.ExistingFileHelper; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CompletableFuture; @SuppressWarnings("deprecation") public class ModItemTagProvider extends TagsProvider<Item> { public ModItemTagProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> completableFuture, ExistingFileHelper existingFileHelper) { super(output, Registries.ITEM, completableFuture, AdAstra.MOD_ID, existingFileHelper); } @Override protected void addTags(HolderLookup.Provider provider) { ModItems.GLOBES.stream().map(RegistryEntry::get).forEach(b -> tag(ModItemTags.GLOBES).add(element(b))); ModItems.FLAGS.stream().map(RegistryEntry::get).forEach(b -> tag(ModItemTags.FLAGS).add(element(b))); ModItems.SLIDING_DOORS.stream().map(RegistryEntry::get).forEach(b -> tag(ModItemTags.SLIDING_DOORS).add(element(b))); ModItems.VEHICLES.stream().map(RegistryEntry::get).forEach(b -> tag(ModItemTags.HELD_OVER_HEAD).add(element(b))); add(ModItemTags.SPACE_SUITS, ModItems.SPACE_HELMET.get()); add(ModItemTags.SPACE_SUITS, ModItems.SPACE_SUIT.get()); add(ModItemTags.SPACE_SUITS, ModItems.SPACE_PANTS.get()); add(ModItemTags.SPACE_SUITS, ModItems.SPACE_BOOTS.get()); tag(ModItemTags.SPACE_SUITS).add(TagEntry.tag(ModItemTags.NETHERITE_SPACE_SUITS.location())); tag(ModItemTags.SPACE_SUITS).add(TagEntry.tag(ModItemTags.JET_SUITS.location())); add(ModItemTags.NETHERITE_SPACE_SUITS, ModItems.NETHERITE_SPACE_HELMET.get()); add(ModItemTags.NETHERITE_SPACE_SUITS, ModItems.NETHERITE_SPACE_SUIT.get()); add(ModItemTags.NETHERITE_SPACE_SUITS, ModItems.NETHERITE_SPACE_PANTS.get()); add(ModItemTags.NETHERITE_SPACE_SUITS, ModItems.NETHERITE_SPACE_BOOTS.get()); tag(ModItemTags.NETHERITE_SPACE_SUITS).add(TagEntry.tag(ModItemTags.JET_SUITS.location())); add(ModItemTags.JET_SUITS, ModItems.JET_SUIT_HELMET.get()); add(ModItemTags.JET_SUITS, ModItems.JET_SUIT.get()); add(ModItemTags.JET_SUITS, ModItems.JET_SUIT_PANTS.get()); add(ModItemTags.JET_SUITS, ModItems.JET_SUIT_BOOTS.get()); tag(ModItemTags.FREEZE_RESISTANT_ARMOR).add(TagEntry.tag(ModItemTags.SPACE_SUITS.location())); tag(ModItemTags.HEAT_RESISTANT_ARMOR).add(TagEntry.tag(ModItemTags.NETHERITE_SPACE_SUITS.location())); add(ModItemTags.HELD_OVER_HEAD, ModItems.LAUNCH_PAD.get()); add(ModItemTags.CABLE_DUCTS, ModItems.CABLE_DUCT.get()); add(ModItemTags.FLUID_PIPE_DUCTS, ModItems.FLUID_PIPE_DUCT.get()); add(ModItemTags.IRON_PLATES, ModItems.IRON_PLATE.get(), "iron_plates", "plates/iron"); add(ModItemTags.IRON_RODS, ModItems.IRON_ROD.get(), "iron_rods", "rods/iron"); Arrays.asList(ModItems.MOON_ICE_SHARD_ORE.get(), ModItems.MARS_ICE_SHARD_ORE.get(), ModItems.GLACIO_ICE_SHARD_ORE.get(), ModItems.DEEPSLATE_ICE_SHARD_ORE.get()).forEach(item -> add(ModItemTags.ICE_SHARD_ORES, item, "ice_shard_ores", "ores/ice_shard")); add(ModItemTags.STEEL_INGOTS, ModItems.STEEL_INGOT.get(), "steel_ingots", "ingots/steel"); add(ModItemTags.STEEL_NUGGETS, ModItems.STEEL_NUGGET.get(), "steel_nuggets", "nuggets/steel"); add(ModItemTags.STEEL_PLATES, ModItems.STEEL_PLATE.get(), "steel_plates", "plates/steel"); add(ModItemTags.STEEL_RODS, ModItems.STEEL_ROD.get(), "steel_rods", "rods/steel"); add(ModItemTags.STEEL_BLOCKS, ModItems.STEEL_BLOCK.get(), "steel_blocks", "storage_blocks/steel"); add(ModItemTags.DESH_INGOTS, ModItems.DESH_INGOT.get(), "desh_ingots", "ingots/desh"); add(ModItemTags.DESH_NUGGETS, ModItems.DESH_NUGGET.get(), "desh_nuggets", "nuggets/desh"); add(ModItemTags.DESH_PLATES, ModItems.DESH_PLATE.get(), "desh_plates", "plates/desh"); add(ModItemTags.RAW_DESH, ModItems.RAW_DESH.get(), "raw_desh", "raw_materials/desh"); add(ModItemTags.DESH_BLOCKS, ModItems.DESH_BLOCK.get(), "desh_blocks", "storage_blocks/desh"); add(ModItemTags.RAW_DESH_BLOCKS, ModItems.RAW_DESH_BLOCK.get(), "raw_desh_blocks", "storage_blocks/raw_desh"); Arrays.asList(ModItems.MOON_DESH_ORE.get(), ModItems.DEEPSLATE_DESH_ORE.get()).forEach(item -> add(ModItemTags.DESH_ORES, item, "desh_ores", "ores/desh")); add(ModItemTags.OSTRUM_INGOTS, ModItems.OSTRUM_INGOT.get(), "ostrum_ingots", "ingots/ostrum"); add(ModItemTags.OSTRUM_NUGGETS, ModItems.OSTRUM_NUGGET.get(), "ostrum_nuggets", "nuggets/ostrum"); add(ModItemTags.OSTRUM_PLATES, ModItems.OSTRUM_PLATE.get(), "ostrum_plates", "plates/ostrum"); add(ModItemTags.RAW_OSTRUM, ModItems.RAW_OSTRUM.get(), "raw_ostrum", "raw_materials/ostrum"); add(ModItemTags.OSTRUM_BLOCKS, ModItems.OSTRUM_BLOCK.get(), "ostrum_blocks", "storage_blocks/ostrum"); add(ModItemTags.RAW_OSTRUM_BLOCKS, ModItems.RAW_OSTRUM_BLOCK.get(), "raw_ostrum_blocks", "storage_blocks/raw_ostrum"); Arrays.asList(ModItems.MARS_OSTRUM_ORE.get(), ModItems.DEEPSLATE_OSTRUM_ORE.get()).forEach(item -> add(ModItemTags.OSTRUM_ORES, item, "ostrum_ores", "ores/ostrum")); add(ModItemTags.CALORITE_INGOTS, ModItems.CALORITE_INGOT.get(), "calorite_ingots", "ingots/calorite"); add(ModItemTags.CALORITE_NUGGETS, ModItems.CALORITE_NUGGET.get(), "calorite_nuggets", "nuggets/calorite"); add(ModItemTags.CALORITE_PLATES, ModItems.CALORITE_PLATE.get(), "calorite_plates", "plates/calorite"); add(ModItemTags.RAW_CALORITE, ModItems.RAW_CALORITE.get(), "raw_calorite", "raw_materials/calorite"); add(ModItemTags.CALORITE_BLOCKS, ModItems.CALORITE_BLOCK.get(), "calorite_blocks", "storage_blocks/calorite"); add(ModItemTags.RAW_CALORITE_BLOCKS, ModItems.RAW_CALORITE_BLOCK.get(), "raw_calorite_blocks", "storage_blocks/raw_calorite"); Arrays.asList(ModItems.VENUS_CALORITE_ORE.get(), ModItems.DEEPSLATE_CALORITE_ORE.get()).forEach(item -> add(ModItemTags.CALORITE_ORES, item, "calorite_ores", "ores/calorite")); add(ModItemTags.GLACIAN_LOGS, ModItems.GLACIAN_LOG.get()); add(ModItemTags.GLACIAN_LOGS, ModItems.STRIPPED_GLACIAN_LOG.get()); add(ModItemTags.AERONOS_CAPS, ModItems.AERONOS_CAP.get()); add(ModItemTags.AERONOS_CAPS, ModItems.AERONOS_STEM.get()); add(ModItemTags.STROPHAR_CAPS, ModItems.STROPHAR_CAP.get()); add(ModItemTags.STROPHAR_CAPS, ModItems.STROPHAR_STEM.get()); tag(ModItemTags.DESTROYED_IN_SPACE) .addTag(ItemTags.SAPLINGS) .addTag(ItemTags.LEAVES) .addTag(ItemTags.FLOWERS) .addTag(ItemTags.CANDLES) .add(element(Items.TORCH)) .add(element(Items.LANTERN)) .add(element(Items.CAMPFIRE)) .add(element(Items.JACK_O_LANTERN)) .add(element(Items.COCOA_BEANS)) .add(element(Items.VINE)) .add(element(Items.BROWN_MUSHROOM_BLOCK)) .add(element(Items.RED_MUSHROOM_BLOCK)) .add(element(Items.BIG_DRIPLEAF)) .add(element(Items.SMALL_DRIPLEAF)) .add(element(Items.SHORT_GRASS)) .add(element(Items.TALL_GRASS)) .add(element(Items.TALL_GRASS)) .add(element(Items.SWEET_BERRIES)) .add(element(Items.BAMBOO)); addVanillaTags(); } private void addVanillaTags() { ModBlocks.STAIRS.stream().map(RegistryEntry::get).forEach(b -> tag(ItemTags.STAIRS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(b)))); ModBlocks.SLABS.stream().map(RegistryEntry::get).forEach(b -> tag(ItemTags.SLABS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(b)))); ModBlocks.BUTTONS.stream().map(RegistryEntry::get).forEach(b -> tag(ItemTags.BUTTONS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(b)))); ModBlocks.WALLS.stream().map(RegistryEntry::get).forEach(b -> tag(ItemTags.WALLS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(b)))); tag(ItemTags.BEACON_PAYMENT_ITEMS).add(element(ModItems.STEEL_INGOT.get())); tag(ItemTags.BEACON_PAYMENT_ITEMS).add(element(ModItems.ETRIUM_INGOT.get())); tag(ItemTags.BEACON_PAYMENT_ITEMS).add(element(ModItems.DESH_INGOT.get())); tag(ItemTags.BEACON_PAYMENT_ITEMS).add(element(ModItems.OSTRUM_INGOT.get())); tag(ItemTags.BEACON_PAYMENT_ITEMS).add(element(ModItems.CALORITE_INGOT.get())); tag(ItemTags.COAL_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_COAL_ORE.get()))); tag(ItemTags.COAL_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_COAL_ORE.get()))); tag(ItemTags.COPPER_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_COPPER_ORE.get()))); tag(ItemTags.DIAMOND_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_DIAMOND_ORE.get()))); tag(ItemTags.DIAMOND_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_DIAMOND_ORE.get()))); tag(ItemTags.DOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STEEL_DOOR.get()))); tag(ItemTags.WOODEN_DOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_DOOR.get()))); tag(ItemTags.WOODEN_DOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_DOOR.get()))); tag(ItemTags.WOODEN_DOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_DOOR.get()))); tag(ItemTags.WOODEN_FENCES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_FENCE.get()))); tag(ItemTags.WOODEN_FENCES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_FENCE.get()))); tag(ItemTags.WOODEN_FENCES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_FENCE.get()))); tag(ItemTags.FENCE_GATES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_FENCE_GATE.get()))); tag(ItemTags.FENCE_GATES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_FENCE_GATE.get()))); tag(ItemTags.FENCE_GATES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_FENCE_GATE.get()))); tag(ItemTags.GOLD_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_GOLD_ORE.get()))); tag(ItemTags.IRON_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_IRON_ORE.get()))); tag(ItemTags.IRON_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_IRON_ORE.get()))); tag(ItemTags.IRON_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MERCURY_IRON_ORE.get()))); tag(ItemTags.IRON_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_IRON_ORE.get()))); tag(ItemTags.LAPIS_ORES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_LAPIS_ORE.get()))); tag(ItemTags.LEAVES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_LEAVES.get()))); tag(ItemTags.LOGS_THAT_BURN).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_LOG.get()))); tag(ItemTags.PIGLIN_LOVED).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_GOLD_ORE.get()))); tag(ItemTags.PLANKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_PLANKS.get()))); tag(ItemTags.PLANKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_PLANKS.get()))); tag(ItemTags.PLANKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_PLANKS.get()))); tag(ItemTags.SAND).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_SAND.get()))); tag(ItemTags.SAND).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_SAND.get()))); tag(ItemTags.SAND).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_SAND.get()))); tag(ItemTags.SMELTS_TO_GLASS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_SAND.get()))); tag(ItemTags.SMELTS_TO_GLASS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_SAND.get()))); tag(ItemTags.SMELTS_TO_GLASS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_SAND.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CRACKED_MOON_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CHISELED_MOON_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CRACKED_MARS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CHISELED_MARS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CRACKED_VENUS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CHISELED_VENUS_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MERCURY_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CRACKED_MERCURY_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CHISELED_MERCURY_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CRACKED_GLACIO_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.CHISELED_GLACIO_STONE_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.PERMAFROST_BRICKS.get()))); tag(ItemTags.STONE_BRICKS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.PERMAFROST_TILES.get()))); tag(ItemTags.STONE_CRAFTING_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_COBBLESTONE.get()))); tag(ItemTags.STONE_CRAFTING_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_COBBLESTONE.get()))); tag(ItemTags.STONE_CRAFTING_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_COBBLESTONE.get()))); tag(ItemTags.STONE_CRAFTING_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MERCURY_COBBLESTONE.get()))); tag(ItemTags.STONE_CRAFTING_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_COBBLESTONE.get()))); tag(ItemTags.STONE_TOOL_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MOON_COBBLESTONE.get()))); tag(ItemTags.STONE_TOOL_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MARS_COBBLESTONE.get()))); tag(ItemTags.STONE_TOOL_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.VENUS_COBBLESTONE.get()))); tag(ItemTags.STONE_TOOL_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.MERCURY_COBBLESTONE.get()))); tag(ItemTags.STONE_TOOL_MATERIALS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIO_COBBLESTONE.get()))); tag(ItemTags.TRAPDOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STEEL_TRAPDOOR.get()))); tag(ItemTags.WOODEN_TRAPDOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_TRAPDOOR.get()))); tag(ItemTags.WOODEN_TRAPDOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_TRAPDOOR.get()))); tag(ItemTags.WOODEN_TRAPDOORS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_TRAPDOOR.get()))); tag(ItemTags.WOODEN_BUTTONS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_BUTTON.get()))); tag(ItemTags.WOODEN_PRESSURE_PLATES).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_PRESSURE_PLATE.get()))); tag(ItemTags.WOODEN_SLABS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_SLAB.get()))); tag(ItemTags.WOODEN_SLABS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_SLAB.get()))); tag(ItemTags.WOODEN_SLABS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_SLAB.get()))); tag(ItemTags.WOODEN_STAIRS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.AERONOS_STAIRS.get()))); tag(ItemTags.WOODEN_STAIRS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.STROPHAR_STAIRS.get()))); tag(ItemTags.WOODEN_STAIRS).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_STAIRS.get()))); tag(ItemTags.WOOL).add(TagEntry.element(BuiltInRegistries.BLOCK.getKey(ModBlocks.GLACIAN_FUR.get()))); } private void add(TagKey<Item> tag, Item item) { tag(tag).add(element(item)); } private void add(TagKey<Item> tag, Item item, String fabricCommonTag, String forgeCommonTag) { add(tag, item); addFabricTag(item, tag, fabricCommonTag); addForgeTag(item, tag, forgeCommonTag); } private void addFabricTag(Item item, TagKey<Item> tag, String fabricCommonTag) { tag(tag).add(TagEntry.optionalTag(new ResourceLocation("c", fabricCommonTag))); var commonTag = TagKey.create(Registries.ITEM, new ResourceLocation("c", fabricCommonTag)); tag(commonTag).add(element(item)); } private void addForgeTag(Item item, TagKey<Item> tag, String forgeCommonTag) { tag(tag).add(TagEntry.optionalTag(new ResourceLocation("forge", forgeCommonTag))); var commonTag = TagKey.create(Registries.ITEM, new ResourceLocation("forge", forgeCommonTag)); tag(commonTag).add(element(item)); var folderTag = TagKey.create(Registries.ITEM, new ResourceLocation("forge", forgeCommonTag.split("/")[0])); tag(folderTag).add(TagEntry.tag(commonTag.location())); } private static TagEntry element(Item item) { return TagEntry.element(loc(item)); } private static ResourceLocation loc(Item item) { return BuiltInRegistries.ITEM.getKey(item); } }
1
0.876684
1
0.876684
game-dev
MEDIA
0.997816
game-dev
0.848707
1
0.848707
matsim-org/matsim-libs
15,378
matsim/src/main/java/org/matsim/core/utils/collections/ArrayMap.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2012 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * 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. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.core.utils.collections; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; /** * Memory-optimized map, backed by a simple array, for storing a <b>small</b> number of entries. * Many operations (like {@link #get(Object)}) have a runtime of <code>O(n)</code>, so this map implementation * should only be used to store a small number of elements in it. But for small number of elements, * this implementation performs very well, especially because of its very low memory overhead. * * Internally, this implementation uses a single array which stores boths keys and values in sequential order * (data[i * 2] contains the keys, data[i * 2 + 1] contains the values). * * @author mrieser / Simunto GmbH */ public class ArrayMap<K, V> implements Map<K, V> { private final static Object[] EMPTY = new Object[0]; private Object[] data = EMPTY; public ArrayMap() { } public ArrayMap(Map<K, V> map) { this.data = new Object[map.size() * 2]; int i = 0; for (Map.Entry<K, V> e : map.entrySet()) { this.data[i] = e.getKey(); this.data[i + 1] = e.getValue(); i += 2; } } @Override public int size() { return this.data.length / 2; } @Override public boolean isEmpty() { return this.data.length == 0; } @Override public boolean containsKey(Object key) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { return true; } } return false; } @Override public boolean containsValue(Object value) { for (int i = 1, n = this.data.length; i < n; i += 2) { Object v = this.data[i]; if (Objects.equals(v, value)) { return true; } } return false; } @SuppressWarnings("unchecked") @Override public V get(Object key) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { return (V) this.data[i + 1]; } } return null; } public V put(K key, V value) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { V oldValue = (V) this.data[i + 1]; this.data[i + 1] = value; return oldValue; } } int oldLength = this.data.length; this.data = Arrays.copyOf(this.data, oldLength + 2); this.data[oldLength] = key; this.data[oldLength + 1] = value; return null; } @Override public V replace(K key, V value) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { V oldValue = (V) this.data[i + 1]; this.data[i + 1] = value; return oldValue; } } return null; } @SuppressWarnings("unchecked") @Override public V remove(final Object key) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { V oldValue = (V) this.data[i + 1]; removeIndex(i); return oldValue; } } return null; } @Override public boolean remove(Object key, Object value) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { V v = (V) this.data[i + 1]; if (Objects.equals(v, value)) { removeIndex(i); return true; } } } return false; } public boolean removeKey(final Object key) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object k = this.data[i]; if (Objects.equals(k, key)) { removeIndex(i); return true; } } return false; } public boolean removeValue(final Object value) { for (int i = 0, n = this.data.length; i < n; i += 2) { Object v = this.data[i + 1]; if (Objects.equals(v, value)) { removeIndex(i); return true; } } return false; } private void removeIndex(int i) { Object[] tmp = new Object[this.data.length - 2]; if (i > 0) { System.arraycopy(this.data, 0, tmp, 0, i); } if (i + 2 < this.data.length) { System.arraycopy(this.data, i + 2, tmp, i, this.data.length - 2 - i); } this.data = tmp; } @Override public void putAll(final Map<? extends K, ? extends V> m) { m.forEach(this::put); } @Override public void clear() { this.data = EMPTY; } @Override public Set<K> keySet() { return new KeySetView<>(this); } @Override public Collection<V> values() { return new ValuesView(this); } @SuppressWarnings("unchecked") @Override public Set<java.util.Map.Entry<K, V>> entrySet() { return new EntrySetView(this); } private static class Entry<K, V> implements Map.Entry<K, V> { private final K k; private final V v; public Entry(K k, V v) { this.k = k; this.v = v; } @Override public K getKey() { return this.k; } @Override public V getValue() { return this.v; } @Override public V setValue(final V value) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry<?, ?> entry = (Entry<?, ?>) o; return Objects.equals(this.k, entry.k) && Objects.equals(this.v, entry.v); } @Override public int hashCode() { return Objects.hash(this.k, this.v); } } private static class KeySetView<K, V> implements Set<K> { private final ArrayMap<K, V> map; KeySetView(ArrayMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public boolean isEmpty() { return this.map.isEmpty(); } @Override public boolean contains(Object o) { return this.map.containsKey(o); } @Override public Iterator<K> iterator() { return new KeyIterator<K, V>(this.map); } @Override public Object[] toArray() { Object[] data = this.map.data; Object[] result = new Object[data.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = data[i * 2]; } return result; } @Override public <T> T[] toArray(T[] a) { Object[] data = this.map.data; int resultLength = data.length / 2; Object[] result = a; if (result == null) { result = new Object[resultLength]; } else if (result.length != resultLength) { result = Arrays.copyOf(a, resultLength); } for (int i = 0; i < result.length; i++) { result[i] = data[i * 2]; } return (T[]) result; } @Override public boolean add(K k) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { return this.map.removeKey(o); } @Override public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!this.map.containsKey(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends K> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { boolean modified = false; Object[] data = this.map.data; for (int i = 0, n = data.length; i < n; i += 2) { Object key = data[i]; if (!c.contains(key)) { this.map.remove(key); modified = true; } } return modified; } @Override public boolean removeAll(Collection<?> c) { boolean modified = false; for (Object o : c) { if (this.map.removeKey(o)) { modified = true; } } return modified; } @Override public void clear() { this.map.clear(); } } private static class KeyIterator<K, V> implements Iterator<K> { private final ArrayMap<K, V> map; private int nextIndex; KeyIterator(ArrayMap<K, V> map) { this.map = map; } @Override public boolean hasNext() { return this.map.data.length > this.nextIndex; } @Override public K next() { if (hasNext()) { K key = (K) this.map.data[this.nextIndex]; this.nextIndex += 2; return key; } throw new NoSuchElementException(); } @Override public void remove() { this.nextIndex -= 2; this.map.removeIndex(this.nextIndex); } } private static class ValuesView<K, V> implements Collection<V> { private final ArrayMap<K, V> map; public ValuesView(ArrayMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public boolean isEmpty() { return this.map.isEmpty(); } @Override public boolean contains(Object o) { return this.map.containsValue(o); } @Override public Iterator<V> iterator() { return new ValueIterator<>(this.map); } @Override public Object[] toArray() { Object[] data = this.map.data; Object[] result = new Object[data.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = data[i * 2 + 1]; } return result; } @Override public <T> T[] toArray(T[] a) { Object[] data = this.map.data; int resultLength = data.length / 2; Object[] result = a; if (result == null) { result = new Object[resultLength]; } else if (result.length != resultLength) { result = Arrays.copyOf(a, resultLength); } for (int i = 0; i < result.length; i++) { result[i] = data[i * 2 + 1]; } return (T[]) result; } @Override public boolean add(V v) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { return this.map.removeValue(o); } @Override public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!this.map.containsValue(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends V> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { boolean modified = false; for (Object o : c) { if (this.map.removeValue(o)) { modified = true; } } return modified; } @Override public boolean retainAll(Collection<?> c) { boolean modified = false; Object[] data = this.map.data; for (int i = 0, n = data.length; i < n; i += 2) { Object value = data[i + 1]; if (!c.contains(value)) { this.map.removeValue(value); modified = true; } } return modified; } @Override public void clear() { this.map.clear(); } } private static class ValueIterator<K, V> implements Iterator<V> { private final ArrayMap<K, V> map; private int nextIndex; ValueIterator(ArrayMap<K, V> map) { this.map = map; } @Override public boolean hasNext() { return this.map.data.length > this.nextIndex; } @Override public V next() { if (hasNext()) { V value = (V) this.map.data[this.nextIndex + 1]; this.nextIndex += 2; return value; } throw new NoSuchElementException(); } @Override public void remove() { this.nextIndex -= 2; this.map.removeIndex(this.nextIndex); } } private static class EntrySetView<K, V> implements Set<java.util.Map.Entry<K, V>> { private final ArrayMap<K, V> map; EntrySetView(ArrayMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public boolean isEmpty() { return this.map.isEmpty(); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry e = (Entry) o; return Objects.equals(e.v, this.map.get(e.k)); } return false; } @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator<>(this.map); } @Override public Object[] toArray() { Object[] data = this.map.data; Object[] result = new Object[data.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = new Entry<>(data[i * 2], data[i * 2 + 1]); } return result; } @Override public <T> T[] toArray(T[] a) { Object[] data = this.map.data; int resultLength = data.length / 2; Object[] result = a; if (result == null) { result = new Object[resultLength]; } else if (result.length != resultLength) { result = Arrays.copyOf(a, resultLength); } for (int i = 0; i < result.length; i++) { result[i] = new Entry<>(data[i * 2], data[i * 2 + 1]); } return (T[]) result; } @Override public boolean add(Map.Entry<K, V> kvEntry) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { if (o instanceof Entry) { Entry e = (Entry) o; return this.map.remove(e.k, e.v); } return false; } @Override public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!this.contains(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends Map.Entry<K, V>> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { boolean modified = false; Object[] data = this.map.data; for (int i = 0, n = data.length; i < n; i += 2) { Object key = data[i]; Object value = data[i + 1]; if (!c.contains(new Entry<>(key, value))) { this.map.remove(key, value); modified = true; } } return modified; } @Override public boolean removeAll(Collection<?> c) { boolean modified = false; for (Object o : c) { if (o instanceof Entry) { Entry e = (Entry) o; if (this.map.remove(e.k, e.v)) { modified = true; } } } return modified; } @Override public void clear() { this.map.clear(); } } private static class EntryIterator<K, V> implements Iterator<java.util.Map.Entry<K, V>> { private final ArrayMap<K, V> map; private int nextIndex; EntryIterator(ArrayMap<K, V> map) { this.map = map; } @Override public boolean hasNext() { return this.map.data.length > this.nextIndex; } @Override public java.util.Map.Entry<K, V> next() { K key = (K) this.map.data[this.nextIndex]; V value = (V) this.map.data[this.nextIndex + 1]; this.nextIndex += 2; return new Entry<>(key, value); } } }
1
0.929051
1
0.929051
game-dev
MEDIA
0.224342
game-dev
0.964199
1
0.964199
Aizistral-Studios/Enigmatic-Legacy
1,276
src/main/java/com/aizistral/enigmaticlegacy/items/generic/GenericBlockItem.java
package com.aizistral.enigmaticlegacy.items.generic; import java.util.function.Supplier; import org.jetbrains.annotations.Nullable; import com.aizistral.enigmaticlegacy.api.items.ICreativeTabMember; import com.aizistral.enigmaticlegacy.registries.EnigmaticTabs; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.Rarity; import net.minecraft.world.level.block.Block; public class GenericBlockItem extends BlockItem implements ICreativeTabMember { private final Supplier<CreativeModeTab> tab; // supplier cuz weird shit happens otherwise public GenericBlockItem(Block blockIn) { this(blockIn, GenericBlockItem.getDefaultProperties()); } public GenericBlockItem(Block blockIn, Properties props) { this(blockIn, props, () -> EnigmaticTabs.MAIN); } public GenericBlockItem(Block blockIn, Properties props, Supplier<@Nullable CreativeModeTab> tab) { super(blockIn, props); this.tab = tab; } @Override public CreativeModeTab getCreativeTab() { return this.tab.get(); } public static Properties getDefaultProperties() { Properties props = new Item.Properties(); props.stacksTo(64); props.rarity(Rarity.COMMON); return props; } }
1
0.731046
1
0.731046
game-dev
MEDIA
0.993238
game-dev
0.71938
1
0.71938
CmST0us/tspi-linux-sdk
13,684
kernel/arch/x86/crypto/serpent-sse2-i586-asm_32.S
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Serpent Cipher 4-way parallel algorithm (i586/SSE2) * * Copyright (C) 2011 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * Based on crypto/serpent.c by * Copyright (C) 2002 Dag Arne Osvik <osvik@ii.uib.no> * 2003 Herbert Valerio Riedel <hvr@gnu.org> */ #include <linux/linkage.h> .file "serpent-sse2-i586-asm_32.S" .text #define arg_ctx 4 #define arg_dst 8 #define arg_src 12 #define arg_xor 16 /********************************************************************** 4-way SSE2 serpent **********************************************************************/ #define CTX %edx #define RA %xmm0 #define RB %xmm1 #define RC %xmm2 #define RD %xmm3 #define RE %xmm4 #define RT0 %xmm5 #define RT1 %xmm6 #define RNOT %xmm7 #define get_key(i, j, t) \ movd (4*(i)+(j))*4(CTX), t; \ pshufd $0, t, t; #define K(x0, x1, x2, x3, x4, i) \ get_key(i, 0, x4); \ get_key(i, 1, RT0); \ get_key(i, 2, RT1); \ pxor x4, x0; \ pxor RT0, x1; \ pxor RT1, x2; \ get_key(i, 3, x4); \ pxor x4, x3; #define LK(x0, x1, x2, x3, x4, i) \ movdqa x0, x4; \ pslld $13, x0; \ psrld $(32 - 13), x4; \ por x4, x0; \ pxor x0, x1; \ movdqa x2, x4; \ pslld $3, x2; \ psrld $(32 - 3), x4; \ por x4, x2; \ pxor x2, x1; \ movdqa x1, x4; \ pslld $1, x1; \ psrld $(32 - 1), x4; \ por x4, x1; \ movdqa x0, x4; \ pslld $3, x4; \ pxor x2, x3; \ pxor x4, x3; \ movdqa x3, x4; \ pslld $7, x3; \ psrld $(32 - 7), x4; \ por x4, x3; \ movdqa x1, x4; \ pslld $7, x4; \ pxor x1, x0; \ pxor x3, x0; \ pxor x3, x2; \ pxor x4, x2; \ movdqa x0, x4; \ get_key(i, 1, RT0); \ pxor RT0, x1; \ get_key(i, 3, RT0); \ pxor RT0, x3; \ pslld $5, x0; \ psrld $(32 - 5), x4; \ por x4, x0; \ movdqa x2, x4; \ pslld $22, x2; \ psrld $(32 - 22), x4; \ por x4, x2; \ get_key(i, 0, RT0); \ pxor RT0, x0; \ get_key(i, 2, RT0); \ pxor RT0, x2; #define KL(x0, x1, x2, x3, x4, i) \ K(x0, x1, x2, x3, x4, i); \ movdqa x0, x4; \ psrld $5, x0; \ pslld $(32 - 5), x4; \ por x4, x0; \ movdqa x2, x4; \ psrld $22, x2; \ pslld $(32 - 22), x4; \ por x4, x2; \ pxor x3, x2; \ pxor x3, x0; \ movdqa x1, x4; \ pslld $7, x4; \ pxor x1, x0; \ pxor x4, x2; \ movdqa x1, x4; \ psrld $1, x1; \ pslld $(32 - 1), x4; \ por x4, x1; \ movdqa x3, x4; \ psrld $7, x3; \ pslld $(32 - 7), x4; \ por x4, x3; \ pxor x0, x1; \ movdqa x0, x4; \ pslld $3, x4; \ pxor x4, x3; \ movdqa x0, x4; \ psrld $13, x0; \ pslld $(32 - 13), x4; \ por x4, x0; \ pxor x2, x1; \ pxor x2, x3; \ movdqa x2, x4; \ psrld $3, x2; \ pslld $(32 - 3), x4; \ por x4, x2; #define S0(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ por x0, x3; \ pxor x4, x0; \ pxor x2, x4; \ pxor RNOT, x4; \ pxor x1, x3; \ pand x0, x1; \ pxor x4, x1; \ pxor x0, x2; \ pxor x3, x0; \ por x0, x4; \ pxor x2, x0; \ pand x1, x2; \ pxor x2, x3; \ pxor RNOT, x1; \ pxor x4, x2; \ pxor x2, x1; #define S1(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x0, x1; \ pxor x3, x0; \ pxor RNOT, x3; \ pand x1, x4; \ por x1, x0; \ pxor x2, x3; \ pxor x3, x0; \ pxor x3, x1; \ pxor x4, x3; \ por x4, x1; \ pxor x2, x4; \ pand x0, x2; \ pxor x1, x2; \ por x0, x1; \ pxor RNOT, x0; \ pxor x2, x0; \ pxor x1, x4; #define S2(x0, x1, x2, x3, x4) \ pxor RNOT, x3; \ pxor x0, x1; \ movdqa x0, x4; \ pand x2, x0; \ pxor x3, x0; \ por x4, x3; \ pxor x1, x2; \ pxor x1, x3; \ pand x0, x1; \ pxor x2, x0; \ pand x3, x2; \ por x1, x3; \ pxor RNOT, x0; \ pxor x0, x3; \ pxor x0, x4; \ pxor x2, x0; \ por x2, x1; #define S3(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x3, x1; \ por x0, x3; \ pand x0, x4; \ pxor x2, x0; \ pxor x1, x2; \ pand x3, x1; \ pxor x3, x2; \ por x4, x0; \ pxor x3, x4; \ pxor x0, x1; \ pand x3, x0; \ pand x4, x3; \ pxor x2, x3; \ por x1, x4; \ pand x1, x2; \ pxor x3, x4; \ pxor x3, x0; \ pxor x2, x3; #define S4(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pand x0, x3; \ pxor x4, x0; \ pxor x2, x3; \ por x4, x2; \ pxor x1, x0; \ pxor x3, x4; \ por x0, x2; \ pxor x1, x2; \ pand x0, x1; \ pxor x4, x1; \ pand x2, x4; \ pxor x3, x2; \ pxor x0, x4; \ por x1, x3; \ pxor RNOT, x1; \ pxor x0, x3; #define S5(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ por x0, x1; \ pxor x1, x2; \ pxor RNOT, x3; \ pxor x0, x4; \ pxor x2, x0; \ pand x4, x1; \ por x3, x4; \ pxor x0, x4; \ pand x3, x0; \ pxor x3, x1; \ pxor x2, x3; \ pxor x1, x0; \ pand x4, x2; \ pxor x2, x1; \ pand x0, x2; \ pxor x2, x3; #define S6(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x0, x3; \ pxor x2, x1; \ pxor x0, x2; \ pand x3, x0; \ por x3, x1; \ pxor RNOT, x4; \ pxor x1, x0; \ pxor x2, x1; \ pxor x4, x3; \ pxor x0, x4; \ pand x0, x2; \ pxor x1, x4; \ pxor x3, x2; \ pand x1, x3; \ pxor x0, x3; \ pxor x2, x1; #define S7(x0, x1, x2, x3, x4) \ pxor RNOT, x1; \ movdqa x1, x4; \ pxor RNOT, x0; \ pand x2, x1; \ pxor x3, x1; \ por x4, x3; \ pxor x2, x4; \ pxor x3, x2; \ pxor x0, x3; \ por x1, x0; \ pand x0, x2; \ pxor x4, x0; \ pxor x3, x4; \ pand x0, x3; \ pxor x1, x4; \ pxor x4, x2; \ pxor x1, x3; \ por x0, x4; \ pxor x1, x4; #define SI0(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pxor x0, x1; \ por x1, x3; \ pxor x1, x4; \ pxor RNOT, x0; \ pxor x3, x2; \ pxor x0, x3; \ pand x1, x0; \ pxor x2, x0; \ pand x3, x2; \ pxor x4, x3; \ pxor x3, x2; \ pxor x3, x1; \ pand x0, x3; \ pxor x0, x1; \ pxor x2, x0; \ pxor x3, x4; #define SI1(x0, x1, x2, x3, x4) \ pxor x3, x1; \ movdqa x0, x4; \ pxor x2, x0; \ pxor RNOT, x2; \ por x1, x4; \ pxor x3, x4; \ pand x1, x3; \ pxor x2, x1; \ pand x4, x2; \ pxor x1, x4; \ por x3, x1; \ pxor x0, x3; \ pxor x0, x2; \ por x4, x0; \ pxor x4, x2; \ pxor x0, x1; \ pxor x1, x4; #define SI2(x0, x1, x2, x3, x4) \ pxor x1, x2; \ movdqa x3, x4; \ pxor RNOT, x3; \ por x2, x3; \ pxor x4, x2; \ pxor x0, x4; \ pxor x1, x3; \ por x2, x1; \ pxor x0, x2; \ pxor x4, x1; \ por x3, x4; \ pxor x3, x2; \ pxor x2, x4; \ pand x1, x2; \ pxor x3, x2; \ pxor x4, x3; \ pxor x0, x4; #define SI3(x0, x1, x2, x3, x4) \ pxor x1, x2; \ movdqa x1, x4; \ pand x2, x1; \ pxor x0, x1; \ por x4, x0; \ pxor x3, x4; \ pxor x3, x0; \ por x1, x3; \ pxor x2, x1; \ pxor x3, x1; \ pxor x2, x0; \ pxor x3, x2; \ pand x1, x3; \ pxor x0, x1; \ pand x2, x0; \ pxor x3, x4; \ pxor x0, x3; \ pxor x1, x0; #define SI4(x0, x1, x2, x3, x4) \ pxor x3, x2; \ movdqa x0, x4; \ pand x1, x0; \ pxor x2, x0; \ por x3, x2; \ pxor RNOT, x4; \ pxor x0, x1; \ pxor x2, x0; \ pand x4, x2; \ pxor x0, x2; \ por x4, x0; \ pxor x3, x0; \ pand x2, x3; \ pxor x3, x4; \ pxor x1, x3; \ pand x0, x1; \ pxor x1, x4; \ pxor x3, x0; #define SI5(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ por x2, x1; \ pxor x4, x2; \ pxor x3, x1; \ pand x4, x3; \ pxor x3, x2; \ por x0, x3; \ pxor RNOT, x0; \ pxor x2, x3; \ por x0, x2; \ pxor x1, x4; \ pxor x4, x2; \ pand x0, x4; \ pxor x1, x0; \ pxor x3, x1; \ pand x2, x0; \ pxor x3, x2; \ pxor x2, x0; \ pxor x4, x2; \ pxor x3, x4; #define SI6(x0, x1, x2, x3, x4) \ pxor x2, x0; \ movdqa x0, x4; \ pand x3, x0; \ pxor x3, x2; \ pxor x2, x0; \ pxor x1, x3; \ por x4, x2; \ pxor x3, x2; \ pand x0, x3; \ pxor RNOT, x0; \ pxor x1, x3; \ pand x2, x1; \ pxor x0, x4; \ pxor x4, x3; \ pxor x2, x4; \ pxor x1, x0; \ pxor x0, x2; #define SI7(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pand x0, x3; \ pxor x2, x0; \ por x4, x2; \ pxor x1, x4; \ pxor RNOT, x0; \ por x3, x1; \ pxor x0, x4; \ pand x2, x0; \ pxor x1, x0; \ pand x2, x1; \ pxor x2, x3; \ pxor x3, x4; \ pand x3, x2; \ por x0, x3; \ pxor x4, x1; \ pxor x4, x3; \ pand x0, x4; \ pxor x2, x4; #define transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ movdqa x0, t2; \ punpckldq x1, x0; \ punpckhdq x1, t2; \ movdqa x2, t1; \ punpckhdq x3, x2; \ punpckldq x3, t1; \ movdqa x0, x1; \ punpcklqdq t1, x0; \ punpckhqdq t1, x1; \ movdqa t2, x3; \ punpcklqdq x2, t2; \ punpckhqdq x2, x3; \ movdqa t2, x2; #define read_blocks(in, x0, x1, x2, x3, t0, t1, t2) \ movdqu (0*4*4)(in), x0; \ movdqu (1*4*4)(in), x1; \ movdqu (2*4*4)(in), x2; \ movdqu (3*4*4)(in), x3; \ \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) #define write_blocks(out, x0, x1, x2, x3, t0, t1, t2) \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ \ movdqu x0, (0*4*4)(out); \ movdqu x1, (1*4*4)(out); \ movdqu x2, (2*4*4)(out); \ movdqu x3, (3*4*4)(out); #define xor_blocks(out, x0, x1, x2, x3, t0, t1, t2) \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ \ movdqu (0*4*4)(out), t0; \ pxor t0, x0; \ movdqu x0, (0*4*4)(out); \ movdqu (1*4*4)(out), t0; \ pxor t0, x1; \ movdqu x1, (1*4*4)(out); \ movdqu (2*4*4)(out), t0; \ pxor t0, x2; \ movdqu x2, (2*4*4)(out); \ movdqu (3*4*4)(out), t0; \ pxor t0, x3; \ movdqu x3, (3*4*4)(out); SYM_FUNC_START(__serpent_enc_blk_4way) /* input: * arg_ctx(%esp): ctx, CTX * arg_dst(%esp): dst * arg_src(%esp): src * arg_xor(%esp): bool, if true: xor output */ pcmpeqd RNOT, RNOT; movl arg_ctx(%esp), CTX; movl arg_src(%esp), %eax; read_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); K(RA, RB, RC, RD, RE, 0); S0(RA, RB, RC, RD, RE); LK(RC, RB, RD, RA, RE, 1); S1(RC, RB, RD, RA, RE); LK(RE, RD, RA, RC, RB, 2); S2(RE, RD, RA, RC, RB); LK(RB, RD, RE, RC, RA, 3); S3(RB, RD, RE, RC, RA); LK(RC, RA, RD, RB, RE, 4); S4(RC, RA, RD, RB, RE); LK(RA, RD, RB, RE, RC, 5); S5(RA, RD, RB, RE, RC); LK(RC, RA, RD, RE, RB, 6); S6(RC, RA, RD, RE, RB); LK(RD, RB, RA, RE, RC, 7); S7(RD, RB, RA, RE, RC); LK(RC, RA, RE, RD, RB, 8); S0(RC, RA, RE, RD, RB); LK(RE, RA, RD, RC, RB, 9); S1(RE, RA, RD, RC, RB); LK(RB, RD, RC, RE, RA, 10); S2(RB, RD, RC, RE, RA); LK(RA, RD, RB, RE, RC, 11); S3(RA, RD, RB, RE, RC); LK(RE, RC, RD, RA, RB, 12); S4(RE, RC, RD, RA, RB); LK(RC, RD, RA, RB, RE, 13); S5(RC, RD, RA, RB, RE); LK(RE, RC, RD, RB, RA, 14); S6(RE, RC, RD, RB, RA); LK(RD, RA, RC, RB, RE, 15); S7(RD, RA, RC, RB, RE); LK(RE, RC, RB, RD, RA, 16); S0(RE, RC, RB, RD, RA); LK(RB, RC, RD, RE, RA, 17); S1(RB, RC, RD, RE, RA); LK(RA, RD, RE, RB, RC, 18); S2(RA, RD, RE, RB, RC); LK(RC, RD, RA, RB, RE, 19); S3(RC, RD, RA, RB, RE); LK(RB, RE, RD, RC, RA, 20); S4(RB, RE, RD, RC, RA); LK(RE, RD, RC, RA, RB, 21); S5(RE, RD, RC, RA, RB); LK(RB, RE, RD, RA, RC, 22); S6(RB, RE, RD, RA, RC); LK(RD, RC, RE, RA, RB, 23); S7(RD, RC, RE, RA, RB); LK(RB, RE, RA, RD, RC, 24); S0(RB, RE, RA, RD, RC); LK(RA, RE, RD, RB, RC, 25); S1(RA, RE, RD, RB, RC); LK(RC, RD, RB, RA, RE, 26); S2(RC, RD, RB, RA, RE); LK(RE, RD, RC, RA, RB, 27); S3(RE, RD, RC, RA, RB); LK(RA, RB, RD, RE, RC, 28); S4(RA, RB, RD, RE, RC); LK(RB, RD, RE, RC, RA, 29); S5(RB, RD, RE, RC, RA); LK(RA, RB, RD, RC, RE, 30); S6(RA, RB, RD, RC, RE); LK(RD, RE, RB, RC, RA, 31); S7(RD, RE, RB, RC, RA); K(RA, RB, RC, RD, RE, 32); movl arg_dst(%esp), %eax; cmpb $0, arg_xor(%esp); jnz .L__enc_xor4; write_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); RET; .L__enc_xor4: xor_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); RET; SYM_FUNC_END(__serpent_enc_blk_4way) SYM_FUNC_START(serpent_dec_blk_4way) /* input: * arg_ctx(%esp): ctx, CTX * arg_dst(%esp): dst * arg_src(%esp): src */ pcmpeqd RNOT, RNOT; movl arg_ctx(%esp), CTX; movl arg_src(%esp), %eax; read_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); K(RA, RB, RC, RD, RE, 32); SI7(RA, RB, RC, RD, RE); KL(RB, RD, RA, RE, RC, 31); SI6(RB, RD, RA, RE, RC); KL(RA, RC, RE, RB, RD, 30); SI5(RA, RC, RE, RB, RD); KL(RC, RD, RA, RE, RB, 29); SI4(RC, RD, RA, RE, RB); KL(RC, RA, RB, RE, RD, 28); SI3(RC, RA, RB, RE, RD); KL(RB, RC, RD, RE, RA, 27); SI2(RB, RC, RD, RE, RA); KL(RC, RA, RE, RD, RB, 26); SI1(RC, RA, RE, RD, RB); KL(RB, RA, RE, RD, RC, 25); SI0(RB, RA, RE, RD, RC); KL(RE, RC, RA, RB, RD, 24); SI7(RE, RC, RA, RB, RD); KL(RC, RB, RE, RD, RA, 23); SI6(RC, RB, RE, RD, RA); KL(RE, RA, RD, RC, RB, 22); SI5(RE, RA, RD, RC, RB); KL(RA, RB, RE, RD, RC, 21); SI4(RA, RB, RE, RD, RC); KL(RA, RE, RC, RD, RB, 20); SI3(RA, RE, RC, RD, RB); KL(RC, RA, RB, RD, RE, 19); SI2(RC, RA, RB, RD, RE); KL(RA, RE, RD, RB, RC, 18); SI1(RA, RE, RD, RB, RC); KL(RC, RE, RD, RB, RA, 17); SI0(RC, RE, RD, RB, RA); KL(RD, RA, RE, RC, RB, 16); SI7(RD, RA, RE, RC, RB); KL(RA, RC, RD, RB, RE, 15); SI6(RA, RC, RD, RB, RE); KL(RD, RE, RB, RA, RC, 14); SI5(RD, RE, RB, RA, RC); KL(RE, RC, RD, RB, RA, 13); SI4(RE, RC, RD, RB, RA); KL(RE, RD, RA, RB, RC, 12); SI3(RE, RD, RA, RB, RC); KL(RA, RE, RC, RB, RD, 11); SI2(RA, RE, RC, RB, RD); KL(RE, RD, RB, RC, RA, 10); SI1(RE, RD, RB, RC, RA); KL(RA, RD, RB, RC, RE, 9); SI0(RA, RD, RB, RC, RE); KL(RB, RE, RD, RA, RC, 8); SI7(RB, RE, RD, RA, RC); KL(RE, RA, RB, RC, RD, 7); SI6(RE, RA, RB, RC, RD); KL(RB, RD, RC, RE, RA, 6); SI5(RB, RD, RC, RE, RA); KL(RD, RA, RB, RC, RE, 5); SI4(RD, RA, RB, RC, RE); KL(RD, RB, RE, RC, RA, 4); SI3(RD, RB, RE, RC, RA); KL(RE, RD, RA, RC, RB, 3); SI2(RE, RD, RA, RC, RB); KL(RD, RB, RC, RA, RE, 2); SI1(RD, RB, RC, RA, RE); KL(RE, RB, RC, RA, RD, 1); SI0(RE, RB, RC, RA, RD); K(RC, RD, RB, RE, RA, 0); movl arg_dst(%esp), %eax; write_blocks(%eax, RC, RD, RB, RE, RT0, RT1, RA); RET; SYM_FUNC_END(serpent_dec_blk_4way)
1
0.862891
1
0.862891
game-dev
MEDIA
0.453645
game-dev
0.788106
1
0.788106
osgcc/ryzom
15,151
ryzom/common/data_common/r2/r2_features_ambush.lua
r2.Features.Ambush = {} local feature = r2.Features.Ambush feature.Name="Ambush" feature.Description="" feature.Components = {} local classAmbushVersion = 1 feature.Components.Ambush = { --PropertySheetHeader = r2.getDisplayButtonHeader("r2.events:openEditor()", "uiR2EdEditEventsButton"), BaseClass="LogicEntity", Name="Ambush", InEventUI = true, Menu="ui:interface:r2ed_feature_menu", Version=classAmbushVersion , DisplayerProperties = "R2::CDisplayerLua", DisplayerPropertiesParams = "ambushDisplayer", DisplayerUI = "R2::CDisplayerLua", DisplayerUIParams = "defaultUIDisplayer", DisplayerVisual = "R2::CDisplayerVisualEntity", ----------------------------------------------------------------------------------------------- Parameters = {}, ApplicableActions = {"activate", "deactivate", "trigger"}, Events = {"activation", "deactivation", "trigger"}, Conditions = {"is active", "is inactive"}, TextContexts = {}, TextParameters = {}, LiveParameters = {}, ----------------------------------------------------------------------------------------------- Prop = { {Name="InstanceId", Type="String", WidgetStyle="StaticText", Visible = false}, {Name="Name", Type="String", MaxNumChar="32"}, {Name="Active", Type="Number", WidgetStyle="Boolean", DefaultValue="1"}, {Name="MobNumber", Type="Number", Category="uiR2EDRollout_Mobs", WidgetStyle="EnumDropDown", Enum={"1", "2", "3", "4", "5"}, }, {Name="Mob1Id", Type="RefId", Category="uiR2EDRollout_Mobs",PickFunction="r2:canPickNpcOrGroup", SetRefIdFunction="r2:setNpcOrGroupRefIdTarget", Visible= function(this) return this:displayRefId(1) end}, {Name="Mob2Id", Type="RefId", Category="uiR2EDRollout_Mobs",PickFunction="r2:canPickNpcOrGroup", SetRefIdFunction="r2:setNpcOrGroupRefIdTarget", Visible= function(this) return this:displayRefId(2) end}, {Name="Mob3Id", Type="RefId", Category="uiR2EDRollout_Mobs",PickFunction="r2:canPickNpcOrGroup", SetRefIdFunction="r2:setNpcOrGroupRefIdTarget", Visible= function(this) return this:displayRefId(3) end}, {Name="Mob4Id", Type="RefId", Category="uiR2EDRollout_Mobs",PickFunction="r2:canPickNpcOrGroup", SetRefIdFunction="r2:setNpcOrGroupRefIdTarget", Visible= function(this) return this:displayRefId(4) end}, {Name="Mob5Id", Type="RefId", Category="uiR2EDRollout_Mobs",PickFunction="r2:canPickNpcOrGroup", SetRefIdFunction="r2:setNpcOrGroupRefIdTarget", Visible= function(this) return this:displayRefId(5) end}, {Name="TriggerOn", Type="Number", WidgetStyle="EnumDropDown", Enum={"Leaves the zone", "Enters the zone"}, }, {Name="Components", Type="Table"}, }, ----------------------------------------------------------------------------------------------- -- from base class getParentTreeNode = function(this) return this:getFeatureParentTreeNode() end, --------------------------------------------------------------------------------------------------------- -- from base class appendInstancesByType = function(this, destTable, kind) assert(type(kind) == "string") --this:delegate():appendInstancesByType(destTable, kind) r2.Classes.LogicEntity.appendInstancesByType(this, destTable, kind) for k, component in specPairs(this.Components) do component:appendInstancesByType(destTable, kind) end end, --------------------------------------------------------------------------------------------------------- -- from base class getSelectBarSons = function(this) return Components end, --------------------------------------------------------------------------------------------------------- -- from base class canHaveSelectBarSons = function(this) return false; end, onPostCreate = function(this) --this:createGhostComponents() if this.User.DisplayProp and this.User.DisplayProp == 1 then r2:setSelectedInstanceId(this.InstanceId) r2:showProperties(this) this.User.DisplayProp = nil end end, pretranslate = function(this, context) r2.Translator.createAiGroup(this, context) end, translate = function(this, context) r2.Translator.translateAiGroup(this, context) r2.Translator.translateFeatureActivation(this, context) end, updateVersion = function(this, scenarioValue, currentValue ) end, } local component = feature.Components.Ambush function component:displayRefId(index) local nbMobs = self.MobNumber + 1 if index <= nbMobs then return true end return false end ------------------------------------------------------------------------------------------------------------------ local ambushDisplayerTable = clone(r2:propertySheetDisplayer()) -- -- If the message is received by a client that didn't request the modification, we must make sure this client -- doesn't modify the data because it has already been performed by the initial client. -- local function checkPickedEntity(this, instanceId, attributeName) if instanceId == "" then return false end local tmpInstance = r2:getInstanceFromId(instanceId) assert(tmpInstance) local i = 1 while i < 6 do local attrName = "Mob" ..i.. "Id" if attrName ~= attributeName and this[attrName] == tmpInstance.InstanceId then return false end i = i + 1 end return true end function ambushDisplayerTable:onAttrModified(instance, attributeName) if attributeName == "MobNumber" then local propertySheet = r2:getPropertySheet(instance) local nbMobs = instance.MobNumber + 1 local i = 1 while i <= 5 do if i > nbMobs then local name = "Mob"..tostring(i).."Id" local refId = propertySheet:find(name) local refIdName = refId:find("name") refIdName.hardtext = "NONE" r2.requestSetNode(instance.InstanceId, name, "") end i = i + 1 end propertySheet.Env.updatePropVisibility() return end if string.find(attributeName, "Id") == nil or attributeName == "InstanceId" then return end local propertySheet = r2:getPropertySheet(instance) local refId = propertySheet:find(attributeName) if refId == nil then return end local refIdName = refId:find("name") local instanceId = instance[attributeName] if instanceId == "" then refIdName.hardtext = "NONE" return end local inserted = checkPickedEntity(instance, instanceId, attributeName) if inserted == true then local tmpInstance = r2:getInstanceFromId(instanceId) refIdName.hardtext = tmpInstance.Name else r2.requestSetNode(instance.InstanceId, attributeName, "") end instance.User.onHrcMove = false end function ambushDisplayerTable:onSelect(instance, isSelected) r2:logicEntityPropertySheetDisplayer():onSelect(instance, isSelected) end function component:onTargetInstancePreHrcMove(targetAttr, targetIndexInArray) local targetId = self[targetAttr] local tmpInstance = r2:getInstanceFromId(targetId) tmpInstance.User.SelfModified = true end local function reattributeIdOnHrcMove(ambush, group, targetAttr) local propertySheet = r2:getPropertySheet(ambush) local refId = propertySheet:find(targetAttr) local refIdName = refId:find("name") r2.requestSetNode(ambush.InstanceId, targetAttr, group.InstanceId) refIdName.hardtext = group.Name ambush.User.onHrcMove = true end function component:onTargetInstancePostHrcMove(targetAttr, targetIndexInArray) local targetId = self[targetAttr] local tmpInstance = r2:getInstanceFromId(targetId) assert(tmpInstance) if tmpInstance.User.SelfModified and tmpInstance.User.SelfModified == true then local group = tmpInstance.ParentInstance if group:isKindOf("NpcGrpFeature") then reattributeIdOnHrcMove(self, group, targetAttr) end tmpInstance.User.SelfModified = false end end function r2:ambushDisplayer() return ambushDisplayerTable -- returned shared displayer to avoid wasting memory end -------------------------------------------------------------------------------------------------------------------- component.getLogicAction = function(entity, context, action) assert( action.Class == "ActionStep") local component = r2:getInstanceFromId(action.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) if (action.Action.Type == "trigger") then local i = 1 local spawnActions = {} while i <= 5 do local attrName = "Mob"..i.."Id" if component[attrName] ~= "" then local rtMobGrp = r2.Translator.getRtGroup(context, component[attrName]) local actionSpawn = r2.Translator.createAction("spawn", rtMobGrp.Id) table.insert(spawnActions, actionSpawn) end i = i + 1 end if table.getn(spawnActions) ~= 0 then local actionTrigger = r2.Translator.createAction("user_event_trigger", rtNpcGrp.Id, 6) table.insert(spawnActions, actionTrigger) local retAction = r2.Translator.createAction("condition_if", r2:getNamespace()..rtNpcGrp.Id..".Active == 1", r2.Translator.createAction("multi_actions", spawnActions) ) return retAction, retAction end return nil, nil end return r2.Translator.getFeatureActivationLogicAction(rtNpcGrp, action) end component.getLogicCondition = function(this, context, condition) assert( condition.Class == "ConditionStep") local component = r2:getInstanceFromId(condition.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) return r2.Translator.getFeatureActivationCondition(condition, rtNpcGrp) end component.getLogicEvent = function(this, context, event) assert( event.Class == "LogicEntityAction") local component = this -- r2:getInstanceFromId(event.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) if tostring(event.Event.Type) == "trigger" then return r2.Translator.getComponentUserEvent(rtNpcGrp, 6) end return r2.Translator.getFeatureActivationLogicEvent(rtNpcGrp, event) end component.createGhostComponents= function(this, act) local comp = this local nbMob = 0 for id = 1, 5 do local propertyName = "Mob"..id.."Id" if comp[propertyName] ~= nil and comp[propertyName] ~= "" then local mob = r2:getInstanceFromId(comp[propertyName]) if mob then nbMob = nbMob + 1 if mob:isKindOf("NpcGrpFeature") then local instanceId = mob.Components[0].InstanceId r2.requestSetGhostNode(instanceId, "AutoSpawn", 0) else r2.requestSetGhostNode(mob.InstanceId, "AutoSpawn", 0) end end end end if nbMob == 0 then return end local zoneTrigger = r2:getInstanceFromId(comp._ZoneId) assert(zoneTrigger) do local type = "On Player Left" if comp.TriggerOn == 1 then type = "On Player Arrived" end local eventHandler = r2.newComponent("LogicEntityAction") eventHandler.Event.Type = type eventHandler.Event.Value = "" eventHandler.Name = type local action = r2.newComponent("ActionStep") action.Entity = r2.RefId(comp.InstanceId) action.Action.Type = "trigger" action.Action.Value = "" table.insert(eventHandler.Actions, action) local behaviorId = zoneTrigger.Behavior.InstanceId assert(behaviorId) r2.requestInsertGhostNode(behaviorId, "Actions", -1, "", eventHandler) end do local eventHandler = r2.newComponent("LogicEntityAction") eventHandler.Event.Type = "activation" eventHandler.Event.Value = "" eventHandler.Name = "activation" local action = r2.newComponent("ActionStep") action.Entity = r2.RefId(zoneTrigger.InstanceId) action.Action.Type = "activate" action.Action.Value = "" table.insert(eventHandler.Actions, action) local behaviorId = this.Behavior.InstanceId assert(behaviorId) r2.requestInsertGhostNode(behaviorId, "Actions", -1, "", eventHandler) end do local eventHandler = r2.newComponent("LogicEntityAction") eventHandler.Event.Type = "deactivation" eventHandler.Event.Value = "" eventHandler.Name = "deactivation" local action = r2.newComponent("ActionStep") action.Entity = r2.RefId(zoneTrigger.InstanceId) action.Action.Type = "deactivate" action.Action.Value = "" table.insert(eventHandler.Actions, action) local behaviorId = this.Behavior.InstanceId assert(behaviorId) r2.requestInsertGhostNode(behaviorId, "Actions", -1, "", eventHandler) end end component.createComponent = function(x, y) local comp = r2.newComponent("Ambush") assert(comp) assert(comp.Position) comp.Base = r2.Translator.getDebugBase("palette.entities.botobjects.user_event") comp.Name = r2:genInstanceName(i18n.get("uiR2EdAmbush")):toUtf8() comp.Position.x = x comp.Position.y = y comp.Position.z = r2:snapZToGround(x, y) local zoneTrigger = r2.Features["ZoneTrigger"].Components.ZoneTrigger.createComponent(x + 3, y + 3) zoneTrigger.Name = comp.Name.." "..i18n.get("uiR2EDZoneTrigger"):toUtf8()--r2:genInstanceName(i18n.get("uiR2EdZoneTrigger")):toUtf8() zoneTrigger.InheritPos = 0 zoneTrigger.Deletable = false table.insert(comp.Components, zoneTrigger) comp._ZoneId = zoneTrigger.InstanceId return comp end component.create = function() if not r2:checkAiQuota() then return end local function posOk(x, y, z) debugInfo("Validate creation of an Ambush.") if r2.mustDisplayInfo("Ambush") == 1 then r2.displayFeatureHelp("Ambush") end r2.requestNewAction(i18n.get("uiR2EDNewAmbushFeatureAction")) local component = feature.Components.Ambush.createComponent( x, y) r2:setCookie(component.InstanceId, "DisplayProp", 1) r2.requestInsertNode(r2:getCurrentAct().InstanceId, "Features", -1, "", component) end local function posCancel() end local creature = r2.Translator.getDebugCreature("object_component_user_event.creature") r2:choosePos(creature, posOk, posCancel, "createFeatureAmbush") end ----------------------------------------- --- register the curent Feature to menu function component:getLogicTranslations() -- register trad local logicTranslations = { ["ApplicableActions"] = { ["activate"] = { menu=i18n.get( "uiR2AA0Activate" ):toUtf8(), text=i18n.get( "uiR2AA1Activate" ):toUtf8()}, ["deactivate"] = { menu=i18n.get( "uiR2AA0Deactivate" ):toUtf8(), text=i18n.get( "uiR2AA1Deactivate" ):toUtf8()}, ["trigger"] = { menu=i18n.get( "uiR2AA0Trigger" ):toUtf8(), text=i18n.get( "uiR2AA1Trigger" ):toUtf8()}, }, ["Events"] = { ["trigger"] = { menu=i18n.get( "uiR2Event0Trigger" ):toUtf8(), text=i18n.get( "uiR2Event1Trigger" ):toUtf8()}, ["activation"] = { menu=i18n.get( "uiR2Event0Activation" ):toUtf8(), text=i18n.get( "uiR2Event1Activation" ):toUtf8()}, ["deactivation"] = { menu=i18n.get( "uiR2Event0Deactivation" ):toUtf8(), text=i18n.get( "uiR2Event1Deactivation" ):toUtf8()}, }, ["Conditions"] = { ["is active"] = { menu=i18n.get( "uiR2Test0Active" ):toUtf8(), text=i18n.get( "uiR2Test1Active" ):toUtf8()}, ["is inactive"] = { menu=i18n.get( "uiR2Test0Inactive" ):toUtf8(), text=i18n.get( "uiR2Test1Inactive" ):toUtf8()} } } return logicTranslations end r2.Features["Ambush"] = feature
1
0.891559
1
0.891559
game-dev
MEDIA
0.925302
game-dev
0.839939
1
0.839939
MrCrayfish/ModelCreator
16,354
src/main/java/com/mrcrayfish/modelcreator/Importer.java
package com.mrcrayfish.modelcreator; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mrcrayfish.modelcreator.component.TextureManager; import com.mrcrayfish.modelcreator.display.DisplayProperties; import com.mrcrayfish.modelcreator.element.Element; import com.mrcrayfish.modelcreator.element.ElementManager; import com.mrcrayfish.modelcreator.element.Face; import com.mrcrayfish.modelcreator.texture.TextureEntry; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; public class Importer { private Map<String, String> textureMap = new HashMap<>(); private String[] faceNames = {"north", "east", "south", "west", "up", "down"}; private String[] displayNames = {"gui", "ground", "fixed", "head", "firstperson_righthand", "firstperson_lefthand", "thirdperson_righthand", "thirdperson_lefthand"}; // Input File private String inputPath; // Model Variables private ElementManager manager; public Importer(ElementManager manager, String outputPath) { this.manager = manager; this.inputPath = outputPath; } public void importFromJSON() { File path = new File(inputPath); if(path.exists() && path.isFile()) { FileReader fr; BufferedReader reader; try { fr = new FileReader(path); reader = new BufferedReader(fr); readComponents(reader, manager, path.getParentFile()); reader.close(); fr.close(); } catch(IOException e) { e.printStackTrace(); } } } private void readComponents(BufferedReader reader, ElementManager manager, File dir) throws IOException { manager.clearElements(); manager.setParticle(null); manager.setDisplayProperties(DisplayProperties.MODEL_CREATOR_BLOCK); JsonParser parser = new JsonParser(); JsonElement read = parser.parse(reader); if(read.isJsonObject()) { JsonObject obj = read.getAsJsonObject(); if(obj.has("parent") && obj.get("parent").isJsonPrimitive()) { String parent = obj.get("parent").getAsString(); File file = new File(dir, parent + ".json"); if(!file.exists()) { parent = parent.substring(parent.lastIndexOf('/') + 1, parent.length()); file = new File(dir, parent + ".json"); } if(file.exists()) { // load textures loadTextures(dir, obj); // Load Parent FileReader fr = new FileReader(file); reader = new BufferedReader(fr); readComponents(reader, manager, file.getParentFile()); reader.close(); fr.close(); } return; } // load textures loadTextures(dir, obj); // load display properties if(obj.has("display") && obj.get("display").isJsonObject()) { readDisplayProperties(obj.getAsJsonObject("display"), manager); } // load elements if(obj.has("elements") && obj.get("elements").isJsonArray()) { JsonArray elements = obj.get("elements").getAsJsonArray(); for(int i = 0; i < elements.size(); i++) { if(elements.get(i).isJsonObject()) { readElement(elements.get(i).getAsJsonObject(), manager); } } } manager.setAmbientOcc(true); if(obj.has("ambientocclusion") && obj.get("ambientocclusion").isJsonPrimitive()) { manager.setAmbientOcc(obj.get("ambientocclusion").getAsBoolean()); } } } private void loadTextures(File file, JsonObject obj) { if(obj.has("textures") && obj.get("textures").isJsonObject()) { JsonObject textures = obj.get("textures").getAsJsonObject(); for(Entry<String, JsonElement> entry : textures.entrySet()) { if(entry.getValue().isJsonPrimitive()) { String key = entry.getKey().trim().toLowerCase(Locale.ENGLISH); String value = entry.getValue().getAsString().trim().toLowerCase(Locale.ENGLISH); if(!textureMap.containsKey(key)) { if(key.equals("particle")) { manager.setParticle(this.loadTexture(file, key, value)); } else if(!value.startsWith("#")) { textureMap.put(key, value); this.loadTexture(file, key, value); } } } } } } private TextureEntry loadTexture(File project, String id, String texture) { TexturePath texturePath = new TexturePath(texture); /* Try loading textures as project format */ if(project != null) { File path = new File(project, "textures"); if(path.exists() && path.isDirectory()) { File textureFile = new File(path, texturePath.getName() + ".png"); if(textureFile.exists() && textureFile.isFile()) { return TextureManager.addImage(id, texturePath, textureFile); } } /* V2 of project file format uses assets folder */ File assets = new File(project, "assets"); if(assets.exists() && assets.isDirectory()) { File textureFile = new File(assets, texturePath.toRelativePath()); if(textureFile.exists() && textureFile.isFile()) { return TextureManager.addImage(id, texturePath, textureFile); } } } /* Try loading textures as if it was from assets */ File parent = project; if(parent != null) { while((parent = parent.getParentFile()) != null) { if(parent.getName().equals("assets")) { File textureFile = new File(parent, texturePath.toRelativePath()); if(textureFile.exists() && textureFile.isFile()) { return TextureManager.addImage(id, texturePath, textureFile); } } else if(parent.getName().equals(texturePath.getModId())) { File textureFile = new File(parent, "textures" + File.separator + texturePath.getDirectory() + File.separator + texturePath.getName() + ".png"); if(textureFile.exists() && textureFile.isFile()) { return TextureManager.addImage(id, texturePath, textureFile); } } } } /* Try loading textures from assets directory */ if(Settings.getAssetsDir() != null) { String path = Settings.getAssetsDir() + File.separator + texturePath.toRelativePath(); File textureFile = new File(path); if(textureFile.exists()) { return TextureManager.addImage(id, texturePath, textureFile); } } return null; } private void readDisplayProperties(JsonObject obj, ElementManager manager) { DisplayProperties properties = manager.getDisplayProperties(); properties.getEntries().forEach((s, entry) -> entry.setEnabled(false)); for(String displayName : displayNames) { if(obj.has(displayName) && obj.get(displayName).isJsonObject()) { readEntry(obj.getAsJsonObject(displayName), displayName, properties); } } } private void readEntry(JsonObject obj, String id, DisplayProperties properties) { DisplayProperties.Entry entry = new DisplayProperties.Entry(id, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0); if(obj.has("rotation") && obj.get("rotation").isJsonArray()) { JsonArray array = obj.get("rotation").getAsJsonArray(); if(array.size() == 3) { entry.setRotationX(array.get(0).getAsDouble()); entry.setRotationY(array.get(1).getAsDouble()); entry.setRotationZ(array.get(2).getAsDouble()); } } if(obj.has("translation") && obj.get("translation").isJsonArray()) { JsonArray array = obj.get("translation").getAsJsonArray(); if(array.size() == 3) { entry.setTranslationX(array.get(0).getAsDouble()); entry.setTranslationY(array.get(1).getAsDouble()); entry.setTranslationZ(array.get(2).getAsDouble()); } } if(obj.has("scale") && obj.get("scale").isJsonArray()) { JsonArray array = obj.get("scale").getAsJsonArray(); if(array.size() == 3) { entry.setScaleX(array.get(0).getAsDouble()); entry.setScaleY(array.get(1).getAsDouble()); entry.setScaleZ(array.get(2).getAsDouble()); } } properties.getEntries().put(id, entry); } private void readElement(JsonObject obj, ElementManager manager) { String name = "Element"; JsonArray from = null; JsonArray to = null; if(obj.has("name") && obj.get("name").isJsonPrimitive()) { name = obj.get("name").getAsString(); } else if(obj.has("comment") && obj.get("comment").isJsonPrimitive()) { name = obj.get("comment").getAsString(); } else if(obj.has("__comment") && obj.get("__comment").isJsonPrimitive()) { name = obj.get("__comment").getAsString(); } if(obj.has("from") && obj.get("from").isJsonArray()) { from = obj.get("from").getAsJsonArray(); } if(obj.has("to") && obj.get("to").isJsonArray()) { to = obj.get("to").getAsJsonArray(); } if(from != null && to != null) { double x = from.get(0).getAsDouble(); double y = from.get(1).getAsDouble(); double z = from.get(2).getAsDouble(); double w = to.get(0).getAsDouble() - x; double h = to.get(1).getAsDouble() - y; double d = to.get(2).getAsDouble() - z; Element element = new Element(w, h, d); element.setName(name); element.setStartX(x); element.setStartY(y); element.setStartZ(z); if(obj.has("rotation") && obj.get("rotation").isJsonObject()) { JsonObject rot = obj.get("rotation").getAsJsonObject(); if(rot.has("origin") && rot.get("origin").isJsonArray()) { JsonArray origin = rot.get("origin").getAsJsonArray(); double ox = origin.get(0).getAsDouble(); double oy = origin.get(1).getAsDouble(); double oz = origin.get(2).getAsDouble(); element.setOriginX(ox); element.setOriginY(oy); element.setOriginZ(oz); } if(rot.has("axis") && rot.get("axis").isJsonPrimitive()) { element.setRotationAxis(Element.parseAxisString(rot.get("axis").getAsString())); } if(rot.has("angle") && rot.get("angle").isJsonPrimitive()) { element.setRotation(rot.get("angle").getAsDouble()); } if(rot.has("rescale") && rot.get("rescale").isJsonPrimitive()) { element.setRescale(rot.get("rescale").getAsBoolean()); } } element.setShade(true); if(obj.has("shade") && obj.get("shade").isJsonPrimitive()) { element.setShade(obj.get("shade").getAsBoolean()); } for(Face face : element.getAllFaces()) { face.setEnabled(false); } if(obj.has("faces") && obj.get("faces").isJsonObject()) { JsonObject faces = obj.get("faces").getAsJsonObject(); for(String faceName : faceNames) { if(faces.has(faceName) && faces.get(faceName).isJsonObject()) { readFace(faces.get(faceName).getAsJsonObject(), faceName, element); } } } manager.addElement(element); } } private void readFace(JsonObject obj, String name, Element element) { Face face = null; for(Face f : element.getAllFaces()) { if(f.getSide() == Face.getFaceSide(name)) { face = f; } } if(face != null) { face.setEnabled(true); // automatically set uv if not specified face.setEndU(element.getFaceDimension(face.getSide()).getWidth()); face.setEndV(element.getFaceDimension(face.getSide()).getHeight()); face.setAutoUVEnabled(true); if(obj.has("uv") && obj.get("uv").isJsonArray()) { JsonArray uv = obj.get("uv").getAsJsonArray(); double uStart = uv.get(0).getAsDouble(); double vStart = uv.get(1).getAsDouble(); double uEnd = uv.get(2).getAsDouble(); double vEnd = uv.get(3).getAsDouble(); face.setStartU(uStart); face.setStartV(vStart); face.setEndU(uEnd); face.setEndV(vEnd); if(element.getFaceDimension(face.getSide()).getWidth() != face.getEndU() - face.getStartU() || element.getFaceDimension(face.getSide()).getHeight() != face.getEndV() - face.getStartV()) { face.setAutoUVEnabled(false); } } if(obj.has("texture") && obj.get("texture").isJsonPrimitive()) { String id = obj.get("texture").getAsString().replace("#", ""); TextureEntry entry = TextureManager.getTexture(id); if(entry != null) { face.setTexture(entry); } } if(obj.has("rotation") && obj.get("rotation").isJsonPrimitive()) { face.setRotation((int) obj.get("rotation").getAsDouble() / 90); } // TODO cullface with different direction than face,tintindex if(obj.has("cullface") && obj.get("cullface").isJsonPrimitive()) { String cullface = obj.get("cullface").getAsString(); if(cullface.equals(Face.getFaceName(face.getSide()))) { face.setCullface(true); } } if(obj.has("tintindex") && obj.get("tintindex").isJsonPrimitive()) { int tintIndex = obj.get("tintindex").getAsInt(); if(tintIndex >= 0) { face.setTintIndexEnabled(true); face.setTintIndex(tintIndex); } } } } }
1
0.831967
1
0.831967
game-dev
MEDIA
0.425158
game-dev,testing-qa,graphics-rendering
0.956403
1
0.956403
dotnet/runtime
67,399
src/coreclr/vm/object.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // OBJECT.CPP // // Definitions of a CLR Object // #include "common.h" #include "vars.hpp" #include "class.h" #include "object.h" #include "threads.h" #include "excep.h" #include "eeconfig.h" #include "gcheaputilities.h" #include "field.h" #include "argdestination.h" SVAL_IMPL(INT32, ArrayBase, s_arrayBoundsZero); static DWORD GetGlobalNewHashCode() { LIMITED_METHOD_CONTRACT; // Used for generating hash codes for exceptions to determine whether the // Catch_Handler_Found_Event should be reported. See Thread::GetNewHashCode. // Using linear congruential generator from Knuth Vol. 2, p. 102, line 24 static DWORD dwHashCodeSeed = 123456789U * 1566083941U + 1; const DWORD multiplier = 1*4 + 5; //same as the GetNewHashCode method dwHashCodeSeed = dwHashCodeSeed*multiplier + 1; return dwHashCodeSeed; } // follow the necessary rules to get a new valid hashcode for an object DWORD Object::ComputeHashCode() { DWORD hashCode; // note that this algorithm now uses at most HASHCODE_BITS so that it will // fit into the objheader if the hashcode has to be moved back into the objheader // such as for an object that is being frozen Thread *pThread = GetThreadNULLOk(); do { if (pThread == NULL) { hashCode = (GetGlobalNewHashCode() >> (32-HASHCODE_BITS)); } else { // we use the high order bits in this case because they're more random hashCode = pThread->GetNewHashCode() >> (32-HASHCODE_BITS); } } while (hashCode == 0); // need to enforce hashCode != 0 // verify that it really fits into HASHCODE_BITS _ASSERTE((hashCode & ((1<<HASHCODE_BITS)-1)) == hashCode); return hashCode; } DWORD Object::GetGlobalNewHashCode() { LIMITED_METHOD_CONTRACT; // Used for generating hash codes for exceptions to determine whether the // Catch_Handler_Found_Event should be reported. See Thread::GetNewHashCode. // Using linear congruential generator from Knuth Vol. 2, p. 102, line 24 static DWORD dwHashCodeSeed = 123456789U * 1566083941U + 1; const DWORD multiplier = 1*4 + 5; //same as the GetNewHashCode method dwHashCodeSeed = dwHashCodeSeed*multiplier + 1; return dwHashCodeSeed; } #ifndef DACCESS_COMPILE INT32 Object::GetHashCodeEx() { CONTRACTL { MODE_COOPERATIVE; THROWS; GC_NOTRIGGER; } CONTRACTL_END // This loop exists because we're inspecting the header dword of the object // and it may change under us because of races with other threads. // On top of that, it may have the spin lock bit set, in which case we're // not supposed to change it. // In all of these case, we need to retry the operation. DWORD iter = 0; DWORD dwSwitchCount = 0; while (true) { DWORD bits = GetHeader()->GetBits(); if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) { if (bits & BIT_SBLK_IS_HASHCODE) { // Common case: the object already has a hash code return bits & MASK_HASHCODE; } else { // We have a sync block index. This means if we already have a hash code, // it is in the sync block, otherwise we generate a new one and store it there SyncBlock *psb = GetSyncBlock(); DWORD hashCode = psb->GetHashCode(); if (hashCode != 0) return hashCode; hashCode = ComputeHashCode(); return psb->SetHashCode(hashCode); } } else { // If a thread is holding the thin lock we need a syncblock if ((bits & (SBLK_MASK_LOCK_THREADID)) != 0) { GetSyncBlock(); // No need to replicate the above code dealing with sync blocks // here - in the next iteration of the loop, we'll realize // we have a syncblock, and we'll do the right thing. } else { // We want to change the header in this case, so we have to check the BIT_SBLK_SPIN_LOCK bit first if (bits & BIT_SBLK_SPIN_LOCK) { iter++; if ((iter % 1024) != 0 && g_SystemInfo.dwNumberOfProcessors > 1) { YieldProcessorNormalized(); // indicate to the processor that we are spinning } else { __SwitchToThread(0, ++dwSwitchCount); } continue; } DWORD hashCode = ComputeHashCode(); DWORD newBits = bits | BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE | hashCode; if (GetHeader()->SetBits(newBits, bits) == bits) return hashCode; // Header changed under us - let's restart this whole thing. } } } } #endif // #ifndef DACCESS_COMPILE BOOL Object::ValidateObjectWithPossibleAV() { CANNOT_HAVE_CONTRACT; SUPPORTS_DAC; PTR_MethodTable table = GetGCSafeMethodTable(); if (table == NULL) { return FALSE; } return table->ValidateWithPossibleAV(); } #ifndef DACCESS_COMPILE // There are cases where it is not possible to get a type handle during a GC. // If we can get the type handle, this method will return it. // Otherwise, the method will return NULL. TypeHandle Object::GetGCSafeTypeHandleIfPossible() const { CONTRACTL { NOTHROW; GC_NOTRIGGER; if(!IsGCThread()) { MODE_COOPERATIVE; } } CONTRACTL_END; // Although getting the type handle is unsafe and could cause recursive type lookups // in some cases, it's always safe and straightforward to get to the MethodTable. MethodTable * pMT = GetGCSafeMethodTable(); _ASSERTE(pMT != NULL); if (pMT == g_pFreeObjectMethodTable) { return NULL; } // Don't look at types that belong to an unloading AppDomain, or else // pObj->GetGCSafeTypeHandle() can AV. For example, we encountered this AV when pObj // was an array like this: // // MyValueType1<MyValueType2>[] myArray // // where MyValueType1<T> & MyValueType2 are defined in different assemblies. In such // a case, looking up the type handle for myArray requires looking in // MyValueType1<T>'s module's m_AssemblyRefByNameTable, which is garbage if its // AppDomain is unloading. // // Another AV was encountered in a similar case, // // MyRefType1<MyRefType2>[] myArray // // where MyRefType2's module was unloaded by the time the GC occurred. In at least // one case, the GC was caused by the AD unload itself (AppDomain::Unload -> // AppDomain::Exit -> GCInterface::AddMemoryPressure -> WKS::GCHeapUtilities::GarbageCollect). // // To protect against all scenarios, verify that // // * The MT of the object is not getting unloaded, OR // * In the case of arrays (potentially of arrays of arrays of arrays ...), the // MT of the innermost element is not getting unloaded. This then ensures the // MT of the original object (i.e., array) itself must not be getting // unloaded either, since the MTs of arrays and of their elements are // allocated on the same loader allocator. Module * pLoaderModule = pMT->GetLoaderModule(); // Don't look up types that are unloading due to Collectible Assemblies. Haven't been // able to find a case where we actually encounter objects like this that can cause // problems; however, it seems prudent to add this protection just in case. LoaderAllocator * pLoaderAllocator = pLoaderModule->GetLoaderAllocator(); _ASSERTE(pLoaderAllocator != NULL); if ((pLoaderAllocator->IsCollectible()) && (ObjectHandleIsNull(pLoaderAllocator->GetLoaderAllocatorObjectHandle()))) { return NULL; } // Ok, it should now be safe to get the type handle return GetGCSafeTypeHandle(); } /* static */ BOOL Object::SupportsInterface(OBJECTREF pObj, MethodTable* pInterfaceMT) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(CheckPointer(pInterfaceMT)); PRECONDITION(pInterfaceMT->IsInterface()); } CONTRACTL_END BOOL bSupportsItf = FALSE; GCPROTECT_BEGIN(pObj) { // Make sure the interface method table has been restored. pInterfaceMT->CheckRestore(); // Check to see if the static class definition indicates we implement the interface. MethodTable * pMT = pObj->GetMethodTable(); if (pMT->CanCastToInterface(pInterfaceMT)) { bSupportsItf = TRUE; } #ifdef FEATURE_COMINTEROP else if (pMT->IsComObjectType()) { // If this is a COM object, the static class definition might not be complete so we need // to check if the COM object implements the interface. bSupportsItf = ComObject::SupportsInterface(pObj, pInterfaceMT); } #endif // FEATURE_COMINTEROP } GCPROTECT_END(); return bSupportsItf; } Assembly *AssemblyBaseObject::GetAssembly() { WRAPPER_NO_CONTRACT; return m_pAssembly; } STRINGREF AllocateString(SString sstr) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; COUNT_T length = sstr.GetCount(); // count of WCHARs excluding terminating NULL STRINGREF strObj = AllocateString(length); memcpyNoGCRefs(strObj->GetBuffer(), sstr.GetUnicode(), length*sizeof(WCHAR)); return strObj; } void Object::ValidateHeap(BOOL bDeep) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; #if defined (VERIFY_HEAP) //no need to verify next object's header in this case //since this is called in verify_heap, which will verfiy every object anyway Validate(bDeep, FALSE); #endif } void Object::SetOffsetObjectRef(DWORD dwOffset, size_t dwValue) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; OBJECTREF* location; OBJECTREF o; location = (OBJECTREF *) &GetData()[dwOffset]; o = ObjectToOBJECTREF(*(Object **) &dwValue); SetObjectReference( location, o ); } void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_CANNOT_TAKE_LOCK; // Assign value. We use casting to avoid going thru the overloaded // OBJECTREF= operator which in this case would trigger a false // write-barrier violation assert. VolatileStore((Object**)dst, OBJECTREFToObject(ref)); #ifdef _DEBUG Thread::ObjectRefAssign(dst); #endif ErectWriteBarrier(dst, ref); } void CopyValueClassUnchecked(void* dest, void* src, MethodTable *pMT) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; _ASSERTE(!pMT->IsArray()); // bunch of assumptions about arrays wrong. if (pMT->ContainsGCPointers()) { memmoveGCRefs(dest, src, pMT->GetNumInstanceFieldBytesIfContainsGCPointers()); } else { DWORD numInstanceFieldBytes = pMT->GetNumInstanceFieldBytes(); switch (numInstanceFieldBytes) { case 1: *(UINT8*)dest = *(UINT8*)src; break; #ifndef ALIGN_ACCESS // we can hit an alignment fault if the value type has multiple // smaller fields. Example: if there are two I4 fields, the // value class can be aligned to 4-byte boundaries, yet the // NumInstanceFieldBytes is 8 case 2: *(UINT16*)dest = *(UINT16*)src; break; case 4: *(UINT32*)dest = *(UINT32*)src; break; case 8: *(UINT64*)dest = *(UINT64*)src; break; #endif // !ALIGN_ACCESS default: memcpyNoGCRefs(dest, src, numInstanceFieldBytes); break; } } } // Copy value class into the argument specified by the argDest. // The destOffset is nonzero when copying values into Nullable<T>, it is the offset // of the T value inside of the Nullable<T> void CopyValueClassArgUnchecked(ArgDestination *argDest, void* src, MethodTable *pMT, int destOffset) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; #if defined(UNIX_AMD64_ABI) if (argDest->IsStructPassedInRegs()) { argDest->CopyStructToRegisters(src, pMT->GetNumInstanceFieldBytes(), destOffset); return; } #elif defined(TARGET_ARM64) if (argDest->IsHFA()) { argDest->CopyHFAStructToRegister(src, pMT->GetNumInstanceFieldBytes()); return; } #elif defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64) if (argDest->IsStructPassedInRegs()) { argDest->CopyStructToRegisters(src, pMT->GetNumInstanceFieldBytes(), destOffset); return; } #endif // UNIX_AMD64_ABI // destOffset is only valid for Nullable<T> passed in registers _ASSERTE(destOffset == 0); CopyValueClassUnchecked(argDest->GetDestinationAddress(), src, pMT); } // Initialize the value class argument to zeros void InitValueClassArg(ArgDestination *argDest, MethodTable *pMT) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; #if defined(UNIX_AMD64_ABI) if (argDest->IsStructPassedInRegs()) { argDest->ZeroStructInRegisters(pMT->GetNumInstanceFieldBytes()); return; } #endif #if defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64) if (argDest->IsStructPassedInRegs()) { *(UINT64*)(argDest->GetStructGenRegDestinationAddress()) = 0; *(UINT64*)(argDest->GetDestinationAddress()) = 0; return; } #endif InitValueClass(argDest->GetDestinationAddress(), pMT); } #if defined (VERIFY_HEAP) #include "dbginterface.h" // make the checking code goes as fast as possible! #if defined(_MSC_VER) #pragma optimize("tgy", on) #endif #define CREATE_CHECK_STRING(x) #x #define CHECK_AND_TEAR_DOWN(x) \ do{ \ if (!(x)) \ { \ _ASSERTE(!CREATE_CHECK_STRING(x)); \ EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE); \ } \ } while (0) VOID Object::Validate(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_CANNOT_TAKE_LOCK; if (g_fEEShutDown & ShutDown_Phase2) { // During second phase of shutdown the code below is not guaranteed to work. return; } #ifdef _DEBUG { Thread *pThread = GetThreadNULLOk(); if (pThread != NULL && !(pThread->PreemptiveGCDisabled())) { // Debugger helper threads are special in that they take over for // what would normally be a nonEE thread (the RCThread). If an // EE thread is doing RCThread duty, then it should be treated // as such. // // There are some GC threads in the same kind of category. Note that // GetThread() sometimes returns them, if DLL_THREAD_ATTACH notifications // have run some managed code. if (!dbgOnly_IsSpecialEEThread() && !IsGCSpecialThread()) _ASSERTE(!"OBJECTREF being accessed while thread is in preemptive GC mode."); } } #endif { // ValidateInner can throw or fault on failure which violates contract. CONTRACT_VIOLATION(ThrowsViolation | FaultViolation); // using inner helper because of TRY and stack objects with destructors. ValidateInner(bDeep, bVerifyNextHeader, bVerifySyncBlock); } } VOID Object::ValidateInner(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock) { STATIC_CONTRACT_THROWS; // See CONTRACT_VIOLATION above STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FAULT; // See CONTRACT_VIOLATION above STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_CANNOT_TAKE_LOCK; int lastTest = 0; EX_TRY { // in order to avoid contract violations in the EH code we'll allow AVs here, // they'll be handled in the catch block AVInRuntimeImplOkayHolder avOk; MethodTable *pMT = GetGCSafeMethodTable(); lastTest = 1; CHECK_AND_TEAR_DOWN(pMT && pMT->Validate()); lastTest = 2; bool noRangeChecks = (g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_NO_RANGE_CHECKS) == EEConfig::HEAPVERIFY_NO_RANGE_CHECKS; // noRangeChecks depends on initial values being FALSE BOOL bSmallObjectHeapPtr = FALSE, bLargeObjectHeapPtr = FALSE; if (!noRangeChecks) { bSmallObjectHeapPtr = GCHeapUtilities::GetGCHeap()->IsHeapPointer(this, true); if (!bSmallObjectHeapPtr) bLargeObjectHeapPtr = GCHeapUtilities::GetGCHeap()->IsHeapPointer(this); CHECK_AND_TEAR_DOWN(bSmallObjectHeapPtr || bLargeObjectHeapPtr); } lastTest = 3; if (bDeep) { CHECK_AND_TEAR_DOWN(GetHeader()->Validate(bVerifySyncBlock)); } lastTest = 4; if (bDeep && (g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_GC)) { GCHeapUtilities::GetGCHeap()->ValidateObjectMember(this); } lastTest = 5; // since bSmallObjectHeapPtr is initialized to FALSE // we skip checking noRangeChecks since if skipping // is enabled bSmallObjectHeapPtr will always be false. if (bSmallObjectHeapPtr) { CHECK_AND_TEAR_DOWN(!GCHeapUtilities::GetGCHeap()->IsLargeObject(this)); } lastTest = 6; lastTest = 7; _ASSERTE(GCHeapUtilities::IsGCHeapInitialized()); // try to validate next object's header if (bDeep && bVerifyNextHeader && GCHeapUtilities::GetGCHeap()->RuntimeStructuresValid() //NextObj could be very slow if concurrent GC is going on && !GCHeapUtilities::GetGCHeap ()->IsConcurrentGCInProgress ()) { Object * nextObj = GCHeapUtilities::GetGCHeap ()->NextObj (this); if ((nextObj != NULL) && (nextObj->GetGCSafeMethodTable() != nullptr) && (nextObj->GetGCSafeMethodTable() != g_pFreeObjectMethodTable)) { // we need a read barrier here - to make sure we read the object header _after_ // reading data that tells us that the object is eligible for verification // (also see: gc.cpp/a_fit_segment_end_p) VOLATILE_MEMORY_BARRIER(); CHECK_AND_TEAR_DOWN(nextObj->GetHeader()->Validate(FALSE)); } } lastTest = 8; #ifdef FEATURE_64BIT_ALIGNMENT if (pMT->RequiresAlign8()) { CHECK_AND_TEAR_DOWN((((size_t)this) & 0x7) == (size_t)(pMT->IsValueType()?4:0)); } lastTest = 9; #endif // FEATURE_64BIT_ALIGNMENT } EX_CATCH { STRESS_LOG3(LF_ASSERT, LL_ALWAYS, "Detected use of corrupted OBJECTREF: %p [MT=%p] (lastTest=%d)", this, lastTest > 0 ? (*(size_t*)this) : 0, lastTest); CHECK_AND_TEAR_DOWN(!"Detected use of a corrupted OBJECTREF. Possible GC hole."); } EX_END_CATCH } #endif // VERIFY_HEAP /*==================================NewString=================================== **Action: Creates a System.String object. **Returns: **Arguments: **Exceptions: ==============================================================================*/ STRINGREF StringObject::NewString(INT32 length) { CONTRACTL { GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(length>=0); } CONTRACTL_END; STRINGREF pString; if (length<0) { return NULL; } else if (length == 0) { return GetEmptyString(); } else { pString = AllocateString(length); _ASSERTE(pString->GetBuffer()[length] == 0); return pString; } } /*==================================NewString=================================== **Action: Many years ago, VB didn't have the concept of a byte array, so enterprising ** users created one by allocating a BSTR with an odd length and using it to ** store bytes. A generation later, we're still stuck supporting this behavior. ** The way that we do this is to take advantage of the difference between the ** array length and the string length. The string length will always be the ** number of characters between the start of the string and the terminating 0. ** If we need an odd number of bytes, we'll take one wchar after the terminating 0. ** (e.g. at position StringLength+1). The high-order byte of this wchar is ** reserved for flags and the low-order byte is our odd byte. This function is ** used to allocate a string of that shape, but we don't actually mark the ** trailing byte as being in use yet. **Returns: A newly allocated string. Null if length is less than 0. **Arguments: length -- the length of the string to allocate ** bHasTrailByte -- whether the string also has a trailing byte. **Exceptions: OutOfMemoryException if AllocateString fails. ==============================================================================*/ STRINGREF StringObject::NewString(INT32 length, BOOL bHasTrailByte) { CONTRACTL { GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(length>=0 && length != INT32_MAX); } CONTRACTL_END; STRINGREF pString; if (length<0 || length == INT32_MAX) { return NULL; } else if (length == 0) { return GetEmptyString(); } else { pString = AllocateString(length); _ASSERTE(pString->GetBuffer()[length]==0); if (bHasTrailByte) { _ASSERTE(pString->GetBuffer()[length+1]==0); } } return pString; } //======================================================================== // Creates a System.String object and initializes from // the supplied null-terminated C string. // // Maps NULL to null. This function does *not* return null to indicate // error situations: it throws an exception instead. //======================================================================== STRINGREF StringObject::NewString(const WCHAR *pwsz) { CONTRACTL { GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (!pwsz) { return NULL; } else { DWORD nch = (DWORD)u16_strlen(pwsz); if (nch==0) { return GetEmptyString(); } #if 0 // // This assert is disabled because it is valid for us to get a // pointer from the gc heap here as long as it is pinned. This // can happen when a string is marshalled to unmanaged by // pinning and then later put into a struct and that struct is // then marshalled to managed. // _ASSERTE(!GCHeapUtilities::GetGCHeap()->IsHeapPointer((BYTE *) pwsz) || !"pwsz can not point to GC Heap"); #endif // 0 STRINGREF pString = AllocateString( nch ); memcpyNoGCRefs(pString->GetBuffer(), pwsz, nch*sizeof(WCHAR)); _ASSERTE(pString->GetBuffer()[nch] == 0); return pString; } } #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize("y", on) // Small critical routines, don't put in EBP frame #endif STRINGREF StringObject::NewString(const WCHAR *pwsz, int length) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(length>=0); } CONTRACTL_END; if (!pwsz) { return NULL; } else if (length <= 0) { return GetEmptyString(); } else { #if 0 // // This assert is disabled because it is valid for us to get a // pointer from the gc heap here as long as it is pinned. This // can happen when a string is marshalled to unmanaged by // pinning and then later put into a struct and that struct is // then marshalled to managed. // _ASSERTE(!GCHeapUtilities::GetGCHeap()->IsHeapPointer((BYTE *) pwsz) || !"pwsz can not point to GC Heap"); #endif // 0 STRINGREF pString = AllocateString(length); memcpyNoGCRefs(pString->GetBuffer(), pwsz, length*sizeof(WCHAR)); _ASSERTE(pString->GetBuffer()[length] == 0); return pString; } } #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize("", on) // Go back to command line default optimizations #endif STRINGREF StringObject::NewString(LPCUTF8 psz) { CONTRACTL { GC_TRIGGERS; MODE_COOPERATIVE; THROWS; PRECONDITION(CheckPointer(psz)); } CONTRACTL_END; int length = (int)strlen(psz); if (length == 0) { return GetEmptyString(); } CQuickBytes qb; WCHAR* pwsz = (WCHAR*) qb.AllocThrows((length) * sizeof(WCHAR)); length = MultiByteToWideChar(CP_UTF8, 0, psz, length, pwsz, length); if (length == 0) { COMPlusThrow(kArgumentException, W("Arg_InvalidUTF8String")); } return NewString(pwsz, length); } STRINGREF StringObject::NewString(LPCUTF8 psz, int cBytes) { CONTRACTL { GC_TRIGGERS; MODE_COOPERATIVE; THROWS; PRECONDITION(CheckPointer(psz, NULL_OK)); } CONTRACTL_END; if (!psz) return NULL; _ASSERTE(psz); _ASSERTE(cBytes >= 0); if (cBytes == 0) { return GetEmptyString(); } int cWszBytes = 0; if (!ClrSafeInt<int>::multiply(cBytes, sizeof(WCHAR), cWszBytes)) COMPlusThrowOM(); CQuickBytes qb; WCHAR* pwsz = (WCHAR*) qb.AllocThrows(cWszBytes); int length = MultiByteToWideChar(CP_UTF8, 0, psz, cBytes, pwsz, cBytes); if (length == 0) { COMPlusThrow(kArgumentException, W("Arg_InvalidUTF8String")); } return NewString(pwsz, length); } // // // STATIC MEMBER VARIABLES // // STRINGREF* StringObject::EmptyStringRefPtr = NULL; bool StringObject::EmptyStringIsFrozen = false; //The special string helpers are used as flag bits for weird strings that have bytes //after the terminating 0. The only case where we use this right now is the VB BSTR as //byte array which is described in MakeStringAsByteArrayFromBytes. #define SPECIAL_STRING_VB_BYTE_ARRAY 0x100 FORCEINLINE BOOL MARKS_VB_BYTE_ARRAY(WCHAR x) { return static_cast<BOOL>(x & SPECIAL_STRING_VB_BYTE_ARRAY); } FORCEINLINE WCHAR MAKE_VB_TRAIL_BYTE(BYTE x) { return static_cast<WCHAR>(x) | SPECIAL_STRING_VB_BYTE_ARRAY; } FORCEINLINE BYTE GET_VB_TRAIL_BYTE(WCHAR x) { return static_cast<BYTE>(x & 0xFF); } /*==============================InitEmptyStringRefPtr============================ **Action: Gets an empty string refptr, cache the result. **Returns: The retrieved STRINGREF. ==============================================================================*/ STRINGREF* StringObject::InitEmptyStringRefPtr() { CONTRACTL { THROWS; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; GCX_COOP(); EEStringData data(0, W(""), TRUE); void* pinnedStr = nullptr; EmptyStringRefPtr = SystemDomain::System()->DefaultDomain()->GetLoaderAllocator()->GetStringObjRefPtrFromUnicodeString(&data, &pinnedStr); EmptyStringIsFrozen = pinnedStr != nullptr; return EmptyStringRefPtr; } /*============================InternalTrailByteCheck============================ **Action: Many years ago, VB didn't have the concept of a byte array, so enterprising ** users created one by allocating a BSTR with an odd length and using it to ** store bytes. A generation later, we're still stuck supporting this behavior. ** The way that we do this is stick the trail byte in the sync block ** whenever we encounter such a situation. Since we expect this to be a very corner case ** accessing the sync block seems like a good enough solution ** **Returns: True if <CODE>str</CODE> contains a VB trail byte, false otherwise. **Arguments: str -- The string to be examined. **Exceptions: None ==============================================================================*/ BOOL StringObject::HasTrailByte() { WRAPPER_NO_CONTRACT; SyncBlock * pSyncBlock = PassiveGetSyncBlock(); if(pSyncBlock != NULL) { return pSyncBlock->HasCOMBstrTrailByte(); } return FALSE; } /*=================================GetTrailByte================================= **Action: If <CODE>str</CODE> contains a vb trail byte, returns a copy of it. **Returns: True if <CODE>str</CODE> contains a trail byte. *bTrailByte is set to ** the byte in question if <CODE>str</CODE> does have a trail byte, otherwise ** it's set to 0. **Arguments: str -- The string being examined. ** bTrailByte -- An out param to hold the value of the trail byte. **Exceptions: None. ==============================================================================*/ BOOL StringObject::GetTrailByte(BYTE *bTrailByte) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(bTrailByte); *bTrailByte=0; BOOL retValue = HasTrailByte(); if(retValue) { *bTrailByte = GET_VB_TRAIL_BYTE(GetHeader()->PassiveGetSyncBlock()->GetCOMBstrTrailByte()); } return retValue; } /*=================================SetTrailByte================================= **Action: Sets the trail byte in the sync block **Returns: True. **Arguments: str -- The string into which to set the trail byte. ** bTrailByte -- The trail byte to be added to the string. **Exceptions: None. ==============================================================================*/ BOOL StringObject::SetTrailByte(BYTE bTrailByte) { WRAPPER_NO_CONTRACT; GetHeader()->GetSyncBlock()->SetCOMBstrTrailByte(MAKE_VB_TRAIL_BYTE(bTrailByte)); return TRUE; } #ifdef USE_CHECKED_OBJECTREFS //------------------------------------------------------------- // Default constructor, for non-initializing declarations: // // OBJECTREF or; //------------------------------------------------------------- OBJECTREF::OBJECTREF() { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; m_asObj = (Object*)POISONC; Thread::ObjectRefNew(this); } //------------------------------------------------------------- // Copy constructor, for passing OBJECTREF's as function arguments. //------------------------------------------------------------- OBJECTREF::OBJECTREF(const OBJECTREF & objref) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_FORBID_FAULT; VALIDATEOBJECT(objref.m_asObj); // !!! If this assert is fired, there are two possibilities: // !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj // !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj), // !!! or ObjectToSTRINGREF(*(StringObject**)pObj) // !!! 2. There is a real GC hole here. // !!! Either way you need to fix the code. _ASSERTE(Thread::IsObjRefValid(&objref)); if ((objref.m_asObj != 0) && ((IGCHeap*)GCHeapUtilities::GetGCHeap())->IsHeapPointer( (BYTE*)this )) { _ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!"); } m_asObj = objref.m_asObj; if (m_asObj != 0) { ENABLESTRESSHEAP(); } Thread::ObjectRefNew(this); } //------------------------------------------------------------- // VolatileLoadWithoutBarrier constructor //------------------------------------------------------------- OBJECTREF::OBJECTREF(const OBJECTREF *pObjref, tagVolatileLoadWithoutBarrier tag) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_FORBID_FAULT; Object* objrefAsObj = VolatileLoadWithoutBarrier(&pObjref->m_asObj); VALIDATEOBJECT(objrefAsObj); // !!! If this assert is fired, there are two possibilities: // !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj // !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj), // !!! or ObjectToSTRINGREF(*(StringObject**)pObj) // !!! 2. There is a real GC hole here. // !!! Either way you need to fix the code. _ASSERTE(Thread::IsObjRefValid(pObjref)); if ((objrefAsObj != 0) && ((IGCHeap*)GCHeapUtilities::GetGCHeap())->IsHeapPointer( (BYTE*)this )) { _ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!"); } m_asObj = objrefAsObj; if (m_asObj != 0) { ENABLESTRESSHEAP(); } Thread::ObjectRefNew(this); } //------------------------------------------------------------- // To allow NULL to be used as an OBJECTREF. //------------------------------------------------------------- OBJECTREF::OBJECTREF(TADDR nul) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; //_ASSERTE(nul == 0); m_asObj = (Object*)nul; if( m_asObj != NULL) { // REVISIT_TODO: fix this, why is this constructor being used for non-null object refs? STATIC_CONTRACT_VIOLATION(ModeViolation); VALIDATEOBJECT(m_asObj); ENABLESTRESSHEAP(); } Thread::ObjectRefNew(this); } //------------------------------------------------------------- // This is for the GC's use only. Non-GC code should never // use the "Object" class directly. The unused "int" argument // prevents C++ from using this to implicitly convert Object*'s // to OBJECTREF. //------------------------------------------------------------- OBJECTREF::OBJECTREF(Object *pObject) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_FORBID_FAULT; DEBUG_ONLY_FUNCTION; if ((pObject != 0) && ((IGCHeap*)GCHeapUtilities::GetGCHeap())->IsHeapPointer( (BYTE*)this )) { _ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!"); } m_asObj = pObject; VALIDATEOBJECT(m_asObj); if (m_asObj != 0) { ENABLESTRESSHEAP(); } Thread::ObjectRefNew(this); } void OBJECTREF::Validate(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock) { LIMITED_METHOD_CONTRACT; if (m_asObj) { m_asObj->Validate(bDeep, bVerifyNextHeader, bVerifySyncBlock); } } //------------------------------------------------------------- // Test against NULL. //------------------------------------------------------------- int OBJECTREF::operator!() const { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; // We don't do any validation here, as we want to allow zero comparison in preemptive mode return !m_asObj; } //------------------------------------------------------------- // Compare two OBJECTREF's. //------------------------------------------------------------- int OBJECTREF::operator==(const OBJECTREF &objref) const { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; if (objref.m_asObj != NULL) // Allow comparison to zero in preemptive mode { // REVISIT_TODO: Weakening the contract system a little bit here. We should really // add a special NULLOBJECTREF which can be used for these situations and have // a separate code path for that with the correct contract protections. STATIC_CONTRACT_VIOLATION(ModeViolation); VALIDATEOBJECT(objref.m_asObj); // !!! If this assert is fired, there are two possibilities: // !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj // !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj), // !!! or ObjectToSTRINGREF(*(StringObject**)pObj) // !!! 2. There is a real GC hole here. // !!! Either way you need to fix the code. _ASSERTE(Thread::IsObjRefValid(&objref)); VALIDATEOBJECT(m_asObj); // If this assert fires, you probably did not protect // your OBJECTREF and a GC might have occurred. To // where the possible GC was, set a breakpoint in Thread::TriggersGC _ASSERTE(Thread::IsObjRefValid(this)); if (m_asObj != 0 || objref.m_asObj != 0) { ENABLESTRESSHEAP(); } } return m_asObj == objref.m_asObj; } //------------------------------------------------------------- // Compare two OBJECTREF's. //------------------------------------------------------------- int OBJECTREF::operator!=(const OBJECTREF &objref) const { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; if (objref.m_asObj != NULL) // Allow comparison to zero in preemptive mode { // REVISIT_TODO: Weakening the contract system a little bit here. We should really // add a special NULLOBJECTREF which can be used for these situations and have // a separate code path for that with the correct contract protections. STATIC_CONTRACT_VIOLATION(ModeViolation); VALIDATEOBJECT(objref.m_asObj); // !!! If this assert is fired, there are two possibilities: // !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj // !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj), // !!! or ObjectToSTRINGREF(*(StringObject**)pObj) // !!! 2. There is a real GC hole here. // !!! Either way you need to fix the code. _ASSERTE(Thread::IsObjRefValid(&objref)); VALIDATEOBJECT(m_asObj); // If this assert fires, you probably did not protect // your OBJECTREF and a GC might have occurred. To // where the possible GC was, set a breakpoint in Thread::TriggersGC _ASSERTE(Thread::IsObjRefValid(this)); if (m_asObj != 0 || objref.m_asObj != 0) { ENABLESTRESSHEAP(); } } return m_asObj != objref.m_asObj; } //------------------------------------------------------------- // Forward method calls. //------------------------------------------------------------- Object* OBJECTREF::operator->() { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; VALIDATEOBJECT(m_asObj); // If this assert fires, you probably did not protect // your OBJECTREF and a GC might have occurred. To // where the possible GC was, set a breakpoint in Thread::TriggersGC _ASSERTE(Thread::IsObjRefValid(this)); if (m_asObj != 0) { ENABLESTRESSHEAP(); } // if you are using OBJECTREF directly, // you probably want an Object * return (Object *)m_asObj; } //------------------------------------------------------------- // Forward method calls. //------------------------------------------------------------- const Object* OBJECTREF::operator->() const { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; VALIDATEOBJECT(m_asObj); // If this assert fires, you probably did not protect // your OBJECTREF and a GC might have occurred. To // where the possible GC was, set a breakpoint in Thread::TriggersGC _ASSERTE(Thread::IsObjRefValid(this)); if (m_asObj != 0) { ENABLESTRESSHEAP(); } // if you are using OBJECTREF directly, // you probably want an Object * return (Object *)m_asObj; } //------------------------------------------------------------- // Assignment. We don't validate the destination so as not // to break the sequence: // // OBJECTREF or; // or = ...; //------------------------------------------------------------- OBJECTREF& OBJECTREF::operator=(const OBJECTREF &objref) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; VALIDATEOBJECT(objref.m_asObj); // !!! If this assert is fired, there are two possibilities: // !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj // !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj), // !!! or ObjectToSTRINGREF(*(StringObject**)pObj) // !!! 2. There is a real GC hole here. // !!! Either way you need to fix the code. _ASSERTE(Thread::IsObjRefValid(&objref)); if ((objref.m_asObj != 0) && ((IGCHeap*)GCHeapUtilities::GetGCHeap())->IsHeapPointer( (BYTE*)this )) { _ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!"); } Thread::ObjectRefAssign(this); m_asObj = objref.m_asObj; if (m_asObj != 0) { ENABLESTRESSHEAP(); } return *this; } //------------------------------------------------------------- // Allows for the assignment of NULL to a OBJECTREF //------------------------------------------------------------- OBJECTREF& OBJECTREF::operator=(TADDR nul) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; _ASSERTE(nul == 0); Thread::ObjectRefAssign(this); m_asObj = (Object*)nul; if (m_asObj != 0) { ENABLESTRESSHEAP(); } return *this; } #endif // DEBUG #ifdef _DEBUG void* __cdecl GCSafeMemCpy(void * dest, const void * src, size_t len) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; if (!(((*(BYTE**)&dest) < g_lowest_address ) || ((*(BYTE**)&dest) >= g_highest_address))) { Thread* pThread = GetThreadNULLOk(); // GCHeapUtilities::IsHeapPointer has race when called in preemptive mode. It walks the list of segments // that can be modified by GC. Do the check below only if it is safe to do so. if (pThread != NULL && pThread->PreemptiveGCDisabled()) { // Note there is memcpyNoGCRefs which will allow you to do a memcpy into the GC // heap if you really know you don't need to call the write barrier _ASSERTE(!GCHeapUtilities::GetGCHeap()->IsHeapPointer((BYTE *) dest) || !"using memcpy to copy into the GC heap, use CopyValueClass"); } } return memcpyNoGCRefs(dest, src, len); } #endif // _DEBUG // This function clears a piece of memory in a GC safe way. It makes the guarantee // that it will clear memory in at least pointer sized chunks whenever possible. // Unaligned memory at the beginning and remaining bytes at the end are written bytewise. // We must make this guarantee whenever we clear memory in the GC heap that could contain // object references. The GC or other user threads can read object references at any time, // clearing them bytewise can result in a read on another thread getting incorrect data. void __fastcall ZeroMemoryInGCHeap(void* mem, size_t size) { WRAPPER_NO_CONTRACT; BYTE* memBytes = (BYTE*) mem; BYTE* endBytes = &memBytes[size]; // handle unaligned bytes at the beginning while (!IS_ALIGNED(memBytes, sizeof(PTR_PTR_VOID)) && memBytes < endBytes) *memBytes++ = 0; // now write pointer sized pieces // volatile ensures that this doesn't get optimized back into a memset call size_t nPtrs = (endBytes - memBytes) / sizeof(PTR_PTR_VOID); PTR_VOID volatile * memPtr = (PTR_PTR_VOID) memBytes; for (size_t i = 0; i < nPtrs; i++) *memPtr++ = 0; // handle remaining bytes at the end memBytes = (BYTE*) memPtr; while (memBytes < endBytes) *memBytes++ = 0; } void StackTraceArray::Append(StackTraceElement const * elem) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)this)); } CONTRACTL_END; // Only the thread that has created the array can append to it assert(GetObjectThread() == GetThreadNULLOk()); uint32_t newsize = Size() + 1; _ASSERTE(newsize <= Capacity()); memcpyNoGCRefs(GetData() + Size(), elem, sizeof(StackTraceElement)); SetSize(newsize); #if defined(_DEBUG) CheckState(); #endif } void StackTraceArray::CheckState() const { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; if (!m_array) return; _ASSERTE(GetObjectThread() == GetThreadNULLOk()); uint32_t size = Size(); StackTraceElement const * p; p = GetData(); for (uint32_t i = 0; i < size; ++i) _ASSERTE(p[i].pFunc != NULL); } void StackTraceArray::Allocate(size_t size) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)this)); } CONTRACTL_END; S_SIZE_T raw_size = S_SIZE_T(size) * S_SIZE_T(sizeof(StackTraceElement)) + S_SIZE_T(sizeof(ArrayHeader)); if (raw_size.IsOverflow() || !FitsIn<DWORD>(raw_size.Value())) { EX_THROW(EEMessageException, (kOverflowException, IDS_EE_ARRAY_DIMENSIONS_EXCEEDED)); } SetArray(I1ARRAYREF(AllocatePrimitiveArray(ELEMENT_TYPE_I1, static_cast<DWORD>(raw_size.Value())))); SetSize(0); SetKeepAliveItemsCount(0); SetObjectThread(); } size_t StackTraceArray::Capacity() const { WRAPPER_NO_CONTRACT; if (!m_array) { return 0; } return (m_array->GetNumComponents() - sizeof(ArrayHeader)) / sizeof(StackTraceElement); } // Compute the number of methods in the stack trace that can be collected. We need to store keepAlive // objects (Resolver / LoaderAllocator) for these methods. uint32_t StackTraceArray::ComputeKeepAliveItemsCount() { LIMITED_METHOD_CONTRACT; uint32_t count = 0; for (uint32_t i = 0; i < Size(); i++) { if ((*this)[i].flags & STEF_KEEPALIVE) { count++; } } return count; } uint32_t StackTraceArray::CopyDataFrom(StackTraceArray const & src) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)this)); PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)&src)); } CONTRACTL_END; uint32_t size = src.Size(); memcpyNoGCRefs(GetRaw(), src.GetRaw(), size * sizeof(StackTraceElement) + sizeof(ArrayHeader)); // Affinitize the copy with the current thread SetObjectThread(); return size; } #ifdef _DEBUG //=============================================================================== // Code that ensures that our unmanaged version of Nullable is consistant with // the managed version Nullable<T> for all T. void Nullable::CheckFieldOffsets(TypeHandle nullableType) { LIMITED_METHOD_CONTRACT; /*** // The non-instantiated method tables like List<T> that are used // by reflection and verification do not have correct field offsets // but we never make instances of these anyway. if (nullableMT->ContainsGenericVariables()) return; ***/ MethodTable* nullableMT = nullableType.GetMethodTable(); // ensure that the managed version of the table is the same as the // unmanaged. Note that we can't do this in corelib.h because this // class is generic and field layout depends on the instantiation. _ASSERTE(nullableMT->GetNumInstanceFields() == 2); FieldDesc* field = nullableMT->GetApproxFieldDescListRaw(); _ASSERTE(strcmp(field->GetDebugName(), "hasValue") == 0); // _ASSERTE(field->GetOffset() == offsetof(Nullable, hasValue)); field++; _ASSERTE(strcmp(field->GetDebugName(), "value") == 0); // _ASSERTE(field->GetOffset() == offsetof(Nullable, value)); } #endif //=============================================================================== // Returns true if nullableMT is Nullable<T> for T is equivalent to paramMT BOOL Nullable::IsNullableForTypeHelper(MethodTable* nullableMT, MethodTable* paramMT) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (!nullableMT->IsNullable()) return FALSE; // we require the parameter types to be equivalent return TypeHandle(paramMT).IsEquivalentTo(nullableMT->GetInstantiation()[0]); } //=============================================================================== int32_t Nullable::GetValueAddrOffset(MethodTable* nullableMT) { LIMITED_METHOD_CONTRACT; _ASSERTE(IsNullableType(nullableMT)); _ASSERTE(strcmp(nullableMT->GetApproxFieldDescListRaw()[1].GetDebugName(), "value") == 0); _ASSERTE(nullableMT->GetApproxFieldDescListRaw()[1].GetOffset() == nullableMT->GetNullableValueAddrOffset()); return nullableMT->GetNullableValueAddrOffset(); } CLR_BOOL* Nullable::HasValueAddr(MethodTable* nullableMT) { LIMITED_METHOD_CONTRACT; _ASSERTE(strcmp(nullableMT->GetApproxFieldDescListRaw()[0].GetDebugName(), "hasValue") == 0); _ASSERTE(nullableMT->GetApproxFieldDescListRaw()[0].GetOffset() == 0); return (CLR_BOOL*) this; } //=============================================================================== void* Nullable::ValueAddr(MethodTable* nullableMT) { LIMITED_METHOD_CONTRACT; _ASSERTE(strcmp(nullableMT->GetApproxFieldDescListRaw()[1].GetDebugName(), "value") == 0); _ASSERTE(nullableMT->GetApproxFieldDescListRaw()[1].GetOffset() == nullableMT->GetNullableValueAddrOffset()); return (((BYTE*) this) + nullableMT->GetNullableValueAddrOffset()); } //=============================================================================== // Special logic to box a nullable<T> as a boxed<T> OBJECTREF Nullable::Box(void* srcPtr, MethodTable* nullableMT) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; FAULT_NOT_FATAL(); // FIX_NOW: why do we need this? Nullable* src = (Nullable*) srcPtr; _ASSERTE(IsNullableType(nullableMT)); // We better have a concrete instantiation, or our field offset asserts are not useful _ASSERTE(!nullableMT->ContainsGenericVariables()); if (!*src->HasValueAddr(nullableMT)) return NULL; OBJECTREF obj = 0; GCPROTECT_BEGININTERIOR (src); MethodTable* argMT = nullableMT->GetInstantiation()[0].AsMethodTable(); // MethodTable::Allocate() triggers cctors, so to avoid that we // allocate directly without triggering cctors - boxing should not trigger cctors. argMT->EnsureInstanceActive(); obj = AllocateObject(argMT); CopyValueClass(obj->UnBox(), src->ValueAddr(nullableMT), argMT); GCPROTECT_END (); return obj; } //=============================================================================== // Special Logic to unbox a boxed T as a nullable<T> BOOL Nullable::UnBox(void* destPtr, OBJECTREF boxedVal, MethodTable* destMT) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; Nullable* dest = (Nullable*) destPtr; BOOL fRet = TRUE; // We should only get here if we are unboxing a T as a Nullable<T> _ASSERTE(IsNullableType(destMT)); // We better have a concrete instantiation, or our field offset asserts are not useful _ASSERTE(!destMT->ContainsGenericVariables()); if (boxedVal == NULL) { // Logically we are doing *dest->HasValueAddr(destMT) = false; // We zero out the whole structure because it may contain GC references // and these need to be initialized to zero. (could optimize in the non-GC case) InitValueClass(destPtr, destMT); fRet = TRUE; } else { GCPROTECT_BEGIN(boxedVal); if (!IsNullableForType(destMT, boxedVal->GetMethodTable())) { // For safety's sake, also allow true nullables to be unboxed normally. // This should not happen normally, but we want to be robust if (destMT->IsEquivalentTo(boxedVal->GetMethodTable())) { CopyValueClass(dest, boxedVal->GetData(), destMT); fRet = TRUE; } else { fRet = FALSE; } } else { *dest->HasValueAddr(destMT) = true; CopyValueClass(dest->ValueAddr(destMT), boxedVal->UnBox(), boxedVal->GetMethodTable()); fRet = TRUE; } GCPROTECT_END(); } return fRet; } //=============================================================================== // Special Logic to unbox a boxed T as a nullable<T> // Does not do any type checks. void Nullable::UnBoxNoCheck(void* destPtr, OBJECTREF boxedVal, MethodTable* destMT) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; Nullable* dest = (Nullable*) destPtr; // We should only get here if we are unboxing a T as a Nullable<T> _ASSERTE(IsNullableType(destMT)); // We better have a concrete instantiation, or our field offset asserts are not useful _ASSERTE(!destMT->ContainsGenericVariables()); if (boxedVal == NULL) { // Logically we are doing *dest->HasValueAddr(destMT) = false; // We zero out the whole structure because it may contain GC references // and these need to be initialized to zero. (could optimize in the non-GC case) InitValueClass(destPtr, destMT); } else { if (IsNullableType(boxedVal->GetMethodTable())) { // For safety's sake, also allow true nullables to be unboxed normally. // This should not happen normally, but we want to be robust CopyValueClass(dest, boxedVal->GetData(), destMT); return; } *dest->HasValueAddr(destMT) = true; CopyValueClass(dest->ValueAddr(destMT), boxedVal->UnBox(), boxedVal->GetMethodTable()); } } //=============================================================================== // a boxed Nullable<T> should either be null or a boxed T, but sometimes it is // useful to have a 'true' boxed Nullable<T> (that is it has two fields). This // function returns a 'normalized' version of this pointer. OBJECTREF Nullable::NormalizeBox(OBJECTREF obj) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (obj != NULL) { MethodTable* retMT = obj->GetMethodTable(); if (Nullable::IsNullableType(retMT)) obj = Nullable::Box(obj->GetData(), retMT); } return obj; } void ThreadBaseObject::SetInternal(Thread *it) { WRAPPER_NO_CONTRACT; // only allow a transition from NULL to non-NULL _ASSERTE((m_InternalThread == NULL) && (it != NULL)); m_InternalThread = it; // Now the native Thread will only be destroyed after the managed Thread is collected. // Tell the GC that the managed Thread actually represents much more memory. GCInterface::AddMemoryPressure(sizeof(Thread)); } void ThreadBaseObject::ClearInternal() { WRAPPER_NO_CONTRACT; _ASSERTE(m_InternalThread != NULL); m_InternalThread = NULL; GCInterface::RemoveMemoryPressure(sizeof(Thread)); } #endif // #ifndef DACCESS_COMPILE StackTraceElement const & StackTraceArray::operator[](size_t index) const { WRAPPER_NO_CONTRACT; return GetData()[index]; } StackTraceElement & StackTraceArray::operator[](size_t index) { WRAPPER_NO_CONTRACT; return GetData()[index]; } #if !defined(DACCESS_COMPILE) // If there are any dynamic methods, the stack trace object is the dynamic methods array with its first // slot set to the stack trace I1Array. // Otherwise the stack trace object is directly the stacktrace I1Array void ExceptionObject::SetStackTrace(OBJECTREF stackTrace) { CONTRACTL { GC_NOTRIGGER; NOTHROW; MODE_COOPERATIVE; } CONTRACTL_END; #ifdef STRESS_LOG if (StressLog::StressLogOn(~0u, 0)) { StressLog::CreateThreadStressLog(); } #endif SetObjectReference((OBJECTREF*)&_stackTrace, (OBJECTREF)stackTrace); } #endif // !defined(DACCESS_COMPILE) // Get the stack trace and keep alive array for the exception. // Both arrays returned by the method are safe to work with without other threads modifying them. // - if the stack trace was created by the current thread, the arrays are returned as is. // - if it was created by another thread, deep copies of the arrays are returned. It is ensured // that both of these arrays are consistent. That means that the stack trace doesn't contain // frames that need keep alive objects and that are not protected by entries in the keep alive // array. void ExceptionObject::GetStackTrace(StackTraceArray & stackTrace, PTRARRAYREF * outKeepAliveArray, Thread *pCurrentThread) const { CONTRACTL { GC_TRIGGERS; THROWS; MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)&stackTrace)); PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)outKeepAliveArray)); } CONTRACTL_END; ExceptionObject::GetStackTraceParts(_stackTrace, stackTrace, outKeepAliveArray); #ifndef DACCESS_COMPILE if ((stackTrace.Get() != NULL) && (stackTrace.GetObjectThread() != pCurrentThread)) { GetStackTraceClone(stackTrace, outKeepAliveArray); } #endif // DACCESS_COMPILE } #ifndef DACCESS_COMPILE void ExceptionObject::GetStackTraceClone(StackTraceArray & stackTrace, PTRARRAYREF * outKeepAliveArray) { { struct { StackTraceArray newStackTrace; PTRARRAYREF newKeepAliveArray = NULL; } gc; GCPROTECT_BEGIN(gc); // When the stack trace was created by other thread than the current one, we create a copy of both the stack trace and the keepAlive arrays to make sure // they are not changing while the caller is accessing them. gc.newStackTrace.Allocate(stackTrace.Capacity()); uint32_t numCopiedFrames = gc.newStackTrace.CopyDataFrom(stackTrace); // Set size to the exact value which was used when we copied the data, // another thread might have changed it at the time of copying gc.newStackTrace.SetSize(numCopiedFrames); stackTrace.Set(gc.newStackTrace.Get()); uint32_t keepAliveArrayCapacity = ((*outKeepAliveArray) == NULL) ? 0 : (*outKeepAliveArray)->GetNumComponents(); // It is possible that another thread was modifying the stack trace array and keep alive array while we were making the copies. // The following sequence of events could have happened: // Case 1: // * The current thread gets the stack trace array and the keep alive array references using the ExceptionObject::GetStackTraceParts above // * The current thread reads the size of the stack trace array // * Another thread adds a new stack frame to the stack trace array and a corresponding keep alive object to the keep alive array // * The current thread creates a copy of the stack trace using the size it read before // * The keep alive count stored in the stack trace array doesn't match the elements in the copy of the stack trace array // In this case, we need to recompute the keep alive count based on the copied stack trace array. // // Case 2: // * The current thread gets the stack trace array and the keep alive array references using the ExceptionObject::GetStackTraceParts above // * Another thread adds a stack frame with a keep alive item and that exceeds the keep alive array capacity. So it allocates a new keep alive array // and adds the new keep alive item to it. // * Thus the keep alive array this thread has read doesn't have the keep alive item, but the stack trace array contains the element the other thread has added. // In this case, we need to trim the stack trace array at the first element that doesn't have a corresponding keep alive object in the keep alive array. // We cannot fetch the keep alive object for that stack trace entry, because in the meanwhile, the keep alive array that the other thread created // may have been collected and the method related to the stack trace entry may have been collected as well. // uint32_t keepAliveItemsCount = 0; for (uint32_t i = 0; i < numCopiedFrames; i++) { if (stackTrace[i].flags & STEF_KEEPALIVE) { if ((keepAliveItemsCount + 1) >= keepAliveArrayCapacity) { // Trim the stack trace at a point where a dynamic or collectible method is found without a corresponding keepAlive object. stackTrace.SetSize(i); break; } else { _ASSERTE((*outKeepAliveArray)->GetAt(keepAliveItemsCount + 1) != NULL); } keepAliveItemsCount++; } } stackTrace.SetKeepAliveItemsCount(keepAliveItemsCount); _ASSERTE(stackTrace.ComputeKeepAliveItemsCount() == keepAliveItemsCount); if (keepAliveArrayCapacity != 0) { gc.newKeepAliveArray = (PTRARRAYREF)AllocateObjectArray(keepAliveArrayCapacity, g_pObjectClass); _ASSERTE((*outKeepAliveArray) != NULL); memmoveGCRefs(gc.newKeepAliveArray->GetDataPtr() + 1, (*outKeepAliveArray)->GetDataPtr() + 1, (keepAliveItemsCount) * sizeof(Object *)); gc.newKeepAliveArray->SetAt(0, stackTrace.Get()); *outKeepAliveArray = gc.newKeepAliveArray; } else { *outKeepAliveArray = NULL; } GCPROTECT_END(); } } #endif // DACCESS_COMPILE // Get the stack trace and the dynamic method array from the stack trace object. // If the stack trace was created by another thread, it returns clones of both arrays. /* static */ void ExceptionObject::GetStackTraceParts(OBJECTREF stackTraceObj, StackTraceArray & stackTrace, PTRARRAYREF * outKeepAliveArray /*= NULL*/) { CONTRACTL { GC_TRIGGERS; THROWS; MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)&stackTrace)); PRECONDITION(IsProtectedByGCFrame((OBJECTREF*)outKeepAliveArray)); } CONTRACTL_END; PTRARRAYREF keepAliveArray = NULL; // Extract the stack trace and keepAlive arrays from the stack trace object. if ((stackTraceObj != NULL) && ((dac_cast<PTR_ArrayBase>(OBJECTREFToObject(stackTraceObj)))->GetMethodTable()->ContainsGCPointers())) { // The stack trace object is the dynamic methods array with its first slot set to the stack trace I1Array. PTR_PTRArray combinedArray = dac_cast<PTR_PTRArray>(OBJECTREFToObject(stackTraceObj)); stackTrace.Set(dac_cast<I1ARRAYREF>(combinedArray->GetAt(0))); keepAliveArray = dac_cast<PTRARRAYREF>(ObjectToOBJECTREF(combinedArray)); } else { stackTrace.Set(dac_cast<I1ARRAYREF>(stackTraceObj)); } if (outKeepAliveArray != NULL) { *outKeepAliveArray = keepAliveArray; } } #ifndef DACCESS_COMPILE void LoaderAllocatorObject::SetSlotsUsed(INT32 newSlotsUsed) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(m_pLoaderAllocatorScout->m_nativeLoaderAllocator->HasHandleTableLock()); } CONTRACTL_END; m_slotsUsed = newSlotsUsed; } PTRARRAYREF LoaderAllocatorObject::GetHandleTable() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(m_pLoaderAllocatorScout->m_nativeLoaderAllocator->HasHandleTableLock()); } CONTRACTL_END; return (PTRARRAYREF)m_pSlots; } void LoaderAllocatorObject::SetHandleTable(PTRARRAYREF handleTable) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(m_pLoaderAllocatorScout->m_nativeLoaderAllocator->HasHandleTableLock()); } CONTRACTL_END; SetObjectReference(&m_pSlots, (OBJECTREF)handleTable); } INT32 LoaderAllocatorObject::GetSlotsUsed() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(m_pLoaderAllocatorScout->m_nativeLoaderAllocator->HasHandleTableLock()); } CONTRACTL_END; return m_slotsUsed; } #ifdef DEBUG static void CheckOffsetOfFieldInInstantiation(MethodTable *pMTOfInstantiation, FieldDesc* pField, size_t offset) { STANDARD_VM_CONTRACT; MethodTable* pGenericFieldMT = pField->GetApproxEnclosingMethodTable(); DWORD index = pGenericFieldMT->GetIndexForFieldDesc(pField); FieldDesc *pFieldOnInstantiation = pMTOfInstantiation->GetFieldDescByIndex(index); if (pFieldOnInstantiation->GetOffset() != offset) { _ASSERTE(!"Field offset mismatch"); } } /*static*/ void GenericCacheStruct::ValidateLayout(MethodTable* pMTOfInstantiation) { STANDARD_VM_CONTRACT; CheckOffsetOfFieldInInstantiation(pMTOfInstantiation, CoreLibBinder::GetField(FIELD__GENERICCACHE__TABLE), offsetof(GenericCacheStruct, _table)); CheckOffsetOfFieldInInstantiation(pMTOfInstantiation, CoreLibBinder::GetField(FIELD__GENERICCACHE__SENTINEL_TABLE), offsetof(GenericCacheStruct, _sentinelTable)); CheckOffsetOfFieldInInstantiation(pMTOfInstantiation, CoreLibBinder::GetField(FIELD__GENERICCACHE__LAST_FLUSH_SIZE), offsetof(GenericCacheStruct, _lastFlushSize)); CheckOffsetOfFieldInInstantiation(pMTOfInstantiation, CoreLibBinder::GetField(FIELD__GENERICCACHE__INITIAL_CACHE_SIZE), offsetof(GenericCacheStruct, _initialCacheSize)); CheckOffsetOfFieldInInstantiation(pMTOfInstantiation, CoreLibBinder::GetField(FIELD__GENERICCACHE__MAX_CACHE_SIZE), offsetof(GenericCacheStruct, _maxCacheSize)); // Validate the layout of the Generic } #endif #endif // DACCESS_COMPILE
1
0.971908
1
0.971908
game-dev
MEDIA
0.581942
game-dev
0.976036
1
0.976036
Pursue525/Nattalie-1.12.2
1,859
src/net/minecraft/client/renderer/entity/RenderOcelot.java
package net.minecraft.client.renderer.entity; import net.minecraft.client.model.ModelOcelot; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.util.ResourceLocation; public class RenderOcelot extends RenderLiving<EntityOcelot> { private static final ResourceLocation BLACK_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/black.png"); private static final ResourceLocation OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/ocelot.png"); private static final ResourceLocation RED_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/red.png"); private static final ResourceLocation SIAMESE_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/siamese.png"); public RenderOcelot(RenderManager p_i47199_1_) { super(p_i47199_1_, new ModelOcelot(), 0.4F); } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityOcelot entity) { switch (entity.getTameSkin()) { case 0: default: return OCELOT_TEXTURES; case 1: return BLACK_OCELOT_TEXTURES; case 2: return RED_OCELOT_TEXTURES; case 3: return SIAMESE_OCELOT_TEXTURES; } } /** * Allows the render to do state modifications necessary before the model is rendered. */ protected void preRenderCallback(EntityOcelot entitylivingbaseIn, float partialTickTime) { super.preRenderCallback(entitylivingbaseIn, partialTickTime); if (entitylivingbaseIn.isTamed()) { GlStateManager.scale(0.8F, 0.8F, 0.8F); } } }
1
0.573644
1
0.573644
game-dev
MEDIA
0.853654
game-dev,graphics-rendering
0.87619
1
0.87619
LordOfDragons/dragengine
2,418
src/dragengine/src/resources/component/deComponentTexture.cpp
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "deComponentTexture.h" #include "../skin/deSkin.h" #include "../skin/dynamic/deDynamicSkin.h" #include "../image/deImage.h" #include "../../common/exceptions.h" // Class deComponentTexture ///////////////////////////// // Constructor, destructor //////////////////////////// deComponentTexture::deComponentTexture(){ pSkin = NULL; pTexture = 0; pDynamicSkin = NULL; } deComponentTexture::~deComponentTexture(){ if( pDynamicSkin ){ pDynamicSkin->FreeReference(); } if( pSkin ){ pSkin->FreeReference(); } } // Management /////////////// void deComponentTexture::SetSkin( deSkin *skin ){ if( skin != pSkin ){ if( pSkin ){ pSkin->FreeReference(); } pSkin = skin; if( skin ){ skin->AddReference(); } } } void deComponentTexture::SetTexture( int texture ){ pTexture = texture; } void deComponentTexture::SetTransform( const decTexMatrix2 &matrix ){ pTransform = matrix; } void deComponentTexture::SetDynamicSkin( deDynamicSkin *dynamicSkin ){ if( dynamicSkin == pDynamicSkin ){ return; } if( pDynamicSkin ){ pDynamicSkin->FreeReference(); } pDynamicSkin = dynamicSkin; if( dynamicSkin ){ dynamicSkin->AddReference(); } }
1
0.928632
1
0.928632
game-dev
MEDIA
0.527825
game-dev
0.550661
1
0.550661
DAQEM/GriefLogger
2,686
common/src/main/java/com/daqem/grieflogger/model/SimpleItemStack.java
package com.daqem.grieflogger.model; import io.netty.buffer.Unpooled; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import java.util.Objects; public class SimpleItemStack { private final Item item; private int count; private final DataComponentPatch tag; public SimpleItemStack(ItemStack itemStack) { this(itemStack.getItem(), itemStack.getCount(), itemStack.getComponentsPatch()); } public SimpleItemStack(ResourceLocation itemLocation, int count, DataComponentPatch tag) { this.item = BuiltInRegistries.ITEM.getValue(itemLocation); this.count = count; this.tag = tag; } public SimpleItemStack(Item item, int count, DataComponentPatch tag) { this.item = item; this.count = count; this.tag = tag; } @Override public boolean equals(Object o) { //DOES NOT CHECK COUNT if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleItemStack that = (SimpleItemStack) o; return Objects.equals(item, that.item) && Objects.equals(tag, that.tag); } @Override public int hashCode() { return Objects.hash(item, count, tag); } public Item getItem() { return item; } public int getCount() { return count; } public DataComponentPatch getTag() { return tag; } public boolean hasTag() { return tag != null; } public boolean hasNoTag() { return tag == null; } public void setCount(int count) { this.count = count; } public void addCount(int count) { this.count += count; } public byte @Nullable [] getTagBytes(Level level) { if (tag == null) { return null; } RegistryFriendlyByteBuf buf = new RegistryFriendlyByteBuf(Unpooled.buffer(), level.registryAccess()); DataComponentPatch.STREAM_CODEC.encode(buf, tag); byte[] temp = new byte[buf.readableBytes()]; buf.readBytes(temp); return temp; } public ItemStack toItemStack() { ItemStack itemStack = new ItemStack(item, count); itemStack.applyComponents(tag); return itemStack; } public boolean isEmpty() { return item.equals(ItemStack.EMPTY.getItem()) || count == 0; } }
1
0.720536
1
0.720536
game-dev
MEDIA
0.998685
game-dev
0.858438
1
0.858438
Unity-Technologies/UnityCsReference
1,308
Modules/Properties/Runtime/Reflection/Internal/ReflectedPropertyBag.cs
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace Unity.Properties.Internal { class ReflectedPropertyBagAttribute : Attribute{} [ReflectedPropertyBag] class ReflectedPropertyBag<TContainer> : ContainerPropertyBag<TContainer> { internal new void AddProperty<TValue>(Property<TContainer, TValue> property) { var container = default(TContainer); if (TryGetProperty(ref container, property.Name, out var existing)) { if (existing.DeclaredValueType() == typeof(TValue)) { // Property with the same name and value type, it's safe to ignore. return; } Debug.LogWarning($"Detected multiple return types for PropertyBag=[{TypeUtility.GetTypeDisplayName(typeof(TContainer))}] Property=[{property.Name}]. The property will use the most derived Type=[{TypeUtility.GetTypeDisplayName(existing.DeclaredValueType())}] and IgnoreType=[{TypeUtility.GetTypeDisplayName(property.DeclaredValueType())}]."); return; } base.AddProperty(property); } } }
1
0.584301
1
0.584301
game-dev
MEDIA
0.639725
game-dev
0.594759
1
0.594759
PinkaLulan/ShinColle
3,864
src/main/java/com/lulan/shincolle/block/BlockCrane.java
package com.lulan.shincolle.block; import com.lulan.shincolle.capability.CapaTeitoku; import com.lulan.shincolle.entity.IShipOwner; import com.lulan.shincolle.tileentity.TileEntityCrane; import com.lulan.shincolle.utility.BlockHelper; import com.lulan.shincolle.utility.EntityHelper; import com.lulan.shincolle.utility.PacketHelper; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockCrane extends BasicBlockContainer { public static final String NAME = "BlockCrane"; public static final String TILENAME = "TileEntityCrane"; public BlockCrane() { super(Material.IRON); this.setUnlocalizedName(NAME); this.setRegistryName(NAME); this.setHardness(1F); this.setResistance(10F); this.setHarvestLevel("pickaxe", 0); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityCrane(); } //can drop items in inventory @Override public boolean canDropInventory(IBlockState state) { return false; } //can send block change when on block break @Override public boolean canAlertBlockChange() { return true; } //false = 紅石類方塊 @Override public boolean isNormalCube(IBlockState state) { return false; } //true = 可跟紅石線連接 @Override public boolean canProvidePower(IBlockState state) { return true; } //get redstone power value for active @Override public int getStrongPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { return this.getWeakPower(state, world, pos, side); } //get redstone power value for inactive @Override public int getWeakPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEntityCrane) { TileEntityCrane crane = (TileEntityCrane) tile; if (crane.getRedMode() > 0 && crane.getRedTick() > 0) return 15; } return 0; } //set owner on placed @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { super.onBlockPlacedBy(world, pos, state, placer, stack); TileEntity tile = world.getTileEntity(pos); if (!world.isRemote && tile instanceof IShipOwner) { //set tile ownership if (placer instanceof EntityPlayer) { CapaTeitoku capa = CapaTeitoku.getTeitokuCapability((EntityPlayer) placer); if (capa != null) ((IShipOwner) tile).setPlayerUID(capa.getPlayerUID()); } } } @Override public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { //check owner if (EntityHelper.checkOP(player) || BlockHelper.checkTileOwner(player, world.getTileEntity(pos))) { return super.removedByPlayer(state, world, pos, player, willHarvest); } return false; } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { //sync player UID while right click if (!world.isRemote) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof IShipOwner) { PacketHelper.sendS2CEntitySync(0, tile, tile.getWorld(), tile.getPos(), null); } } return super.onBlockActivated(world, pos, state, player, hand, facing, hitX, hitY, hitZ); } }
1
0.900808
1
0.900808
game-dev
MEDIA
0.999067
game-dev
0.978646
1
0.978646
MapleStoryUnity/MapleStoryUnity
1,819
Assets/JCSUnity/Scripts/Effects/Particle/Type/JCS_Bubble.cs
/** * $File: JCS_Bubble.cs $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ using UnityEngine; using MyBox; namespace JCSUnity { /// <summary> /// The component make the bubble movement. /// </summary> [RequireComponent(typeof(JCS_3DGoStraightAction))] public class JCS_Bubble : JCS_WeatherParticle { /* Variables */ [Separator("Runtime Variables (JCS_Bubble)")] [Tooltip("Do the effect?")] [SerializeField] private bool mDoAction = true; [Tooltip("How intense it shakes?")] [SerializeField] [Range(0.0f, 10.0f)] private float mShakeMargin = 2.0f; [Tooltip("How fast it moves?")] [SerializeField] [Range(0.1f, 1000.0f)] private float mShakeSpeed = 1.0f; [Tooltip("Type of the delta time.")] [SerializeField] private JCS_TimeType mTimeType = JCS_TimeType.DELTA_TIME; /* Setter & Getter */ public bool doAction { get { return mDoAction; } set { mDoAction = value; } } public float shakeSpeed { get { return mShakeSpeed; } set { mShakeSpeed = value; } } public float shakeMargin { get { return mShakeMargin; } set { mShakeMargin = value; } } public JCS_TimeType timeType { get { return mTimeType; } set { mTimeType = value; } } /* Functions */ private void Update() { if (!mDoAction) return; Vector3 newPos = transform.position; newPos.x += JCS_Random.Range(-mShakeMargin, mShakeMargin) * mShakeSpeed * JCS_Time.ItTime(mTimeType); transform.position = newPos; } } }
1
0.745463
1
0.745463
game-dev
MEDIA
0.851048
game-dev
0.936001
1
0.936001
AionGermany/aion-germany
3,274
AL-Game/data/scripts/system/handlers/quest/haramel/_71100InstancePreventionOfAethertapping.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 quest.haramel; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author QuestGenerator by Mariella */ public class _71100InstancePreventionOfAethertapping extends QuestHandler { private final static int questId = 71100; private final static int[] mobs = { 700950 }; public _71100InstancePreventionOfAethertapping() { super(questId); } @Override public void register() { qe.registerQuestNpc(700950).addOnTalkEvent(questId); // Aether Cart qe.registerQuestNpc(700953).addOnTalkEvent(questId); // Reprocessed Odella for (int mob : mobs) { qe.registerQuestNpc(mob).addOnKillEvent(questId); } } @Override public boolean onLvlUpEvent(QuestEnv env) { return defaultOnLvlUpEvent(env, 1000, true); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs == null) { return false; } if (qs.getStatus() == QuestStatus.START) { switch (targetId) { case 700950: { switch (dialog) { // ToDo: check correct action for this npc case USE_OBJECT: { qs.setQuestVar(1); updateQuestStatus(env); return false; } default: break; } break; } case 700953: { switch (dialog) { // ToDo: check correct action for this npc case USE_OBJECT: { qs.setQuestVar(2); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return false; } default: break; } break; } default: break; } } return false; } /* @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); int var1 = qs.getQuestVarById(1); // (0) Step: 0, Count: 3, Mobs : 700950 if (var == 0 && var1 < 2) { return defaultOnKillEvent(env, mobs, var1, var1 + 1, 1); } else { qs.setQuestVar(1); updateQuestStatus(env); } } return false; } */ }
1
0.943438
1
0.943438
game-dev
MEDIA
0.97386
game-dev
0.972363
1
0.972363
MartinTheDragon/Nuclear-Tech-Mod-Remake
3,074
src/main/kotlin/at/martinthedragon/nucleartech/block/SteelScaffoldBlock.kt
package at.martinthedragon.nucleartech.block import net.minecraft.core.BlockPos import net.minecraft.core.Direction import net.minecraft.world.item.context.BlockPlaceContext import net.minecraft.world.level.BlockGetter import net.minecraft.world.level.LevelAccessor import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.level.block.state.StateDefinition import net.minecraft.world.level.block.state.properties.BlockStateProperties import net.minecraft.world.level.material.FluidState import net.minecraft.world.level.material.Fluids import net.minecraft.world.level.pathfinder.PathComputationType import net.minecraft.world.phys.shapes.BooleanOp import net.minecraft.world.phys.shapes.CollisionContext import net.minecraft.world.phys.shapes.Shapes import net.minecraft.world.phys.shapes.VoxelShape class SteelScaffoldBlock(properties: Properties) : Block(properties) { init { registerDefaultState(stateDefinition.any().setValue(BlockStateProperties.HORIZONTAL_AXIS, Direction.Axis.X).setValue(BlockStateProperties.WATERLOGGED, false)) } override fun getFluidState(blockState: BlockState): FluidState = if (blockState.getValue(BlockStateProperties.WATERLOGGED)) Fluids.WATER.getSource(false) else Fluids.EMPTY.defaultFluidState() private val xShell = box(2.0, 0.0, 0.0, 14.0, 16.0, 16.0) private val xHollow = box(4.0, 0.0, 2.0, 12.0, 16.0, 14.0) private val zShell = box(0.0, 0.0, 2.0, 16.0, 16.0, 14.0) private val zHollow = box(2.0, 0.0, 4.0, 14.0, 16.0, 12.0) private val xShape = Shapes.join(xShell, xHollow, BooleanOp.ONLY_FIRST) private val zShape = Shapes.join(zShell, zHollow, BooleanOp.ONLY_FIRST) override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) { super.createBlockStateDefinition(builder) builder.add(BlockStateProperties.HORIZONTAL_AXIS, BlockStateProperties.WATERLOGGED) } override fun getStateForPlacement(context: BlockPlaceContext): BlockState? { val fluidState = context.level.getFluidState(context.clickedPos) return defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_AXIS, context.horizontalDirection.axis).setValue(BlockStateProperties.WATERLOGGED, fluidState.type == Fluids.WATER) } override fun getShape(state: BlockState, level: BlockGetter, pos: BlockPos, context: CollisionContext): VoxelShape = when (state.getValue(BlockStateProperties.HORIZONTAL_AXIS)) { Direction.Axis.X -> xShape Direction.Axis.Z -> zShape else -> xShell } override fun updateShape(state: BlockState, sourceDirection: Direction, otherState: BlockState, level: LevelAccessor, pos: BlockPos, otherPos: BlockPos): BlockState { if (state.getValue(BlockStateProperties.WATERLOGGED)) level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)) return state } override fun isPathfindable(state: BlockState, level: BlockGetter, pos: BlockPos, pathType: PathComputationType) = false }
1
0.844227
1
0.844227
game-dev
MEDIA
0.994518
game-dev
0.87355
1
0.87355
Mimi8298/Supercell.Magic
1,368
Supercell.Magic.Servers.Chat/Session/ChatSessionManager.cs
namespace Supercell.Magic.Servers.Chat.Session { using System; using System.Collections.Generic; using Supercell.Magic.Servers.Core.Network.Message.Session; public static class ChatSessionManager { private static Dictionary<long, ChatSession> m_sessions; public static int Count { get { return ChatSessionManager.m_sessions.Count; } } public static void Init() { ChatSessionManager.m_sessions = new Dictionary<long, ChatSession>(); } public static void OnStartServerSessionMessageReceived(StartServerSessionMessage message) { if (ChatSessionManager.m_sessions.ContainsKey(message.SessionId)) throw new Exception("ChatSessionManager.onStartSessionMessageReceived: session already started!"); ChatSessionManager.m_sessions.Add(message.SessionId, new ChatSession(message)); } public static void OnStopServerSessionMessageReceived(StopServerSessionMessage message) { if (ChatSessionManager.m_sessions.Remove(message.SessionId, out ChatSession session)) session.Destruct(); } public static bool TryGet(long id, out ChatSession session) { return ChatSessionManager.m_sessions.TryGetValue(id, out session); } } }
1
0.760102
1
0.760102
game-dev
MEDIA
0.649545
game-dev,networking
0.880012
1
0.880012
lua9520/source-engine-2018-cstrike15_src
2,884
hammer/mapsweptplayerhull.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef MAPSWEPTPLAYERHULL_H #define MAPSWEPTPLAYERHULL_H #ifdef _WIN32 #pragma once #endif #include "MapClass.h" #include "MapPointHandle.h" #include "ToolInterface.h" #include "MapEntity.h" class CHelperInfo; class CRender2D; class CRender3D; class CToolSweptPlayerHull; class CMapPlayerHullHandle; class CMapSweptPlayerHull : public CMapHelper { friend CToolSweptPlayerHull; public: DECLARE_MAPCLASS(CMapSweptPlayerHull, CMapHelper) // // Factory for building from a list of string parameters. // static CMapClass *Create(CHelperInfo *pInfo, CMapEntity *pParent); // // Construction/destruction: // CMapSweptPlayerHull(); ~CMapSweptPlayerHull(); void GetEndPoint(Vector &vecPos, int nPointIndex); void UpdateEndPoint(Vector &vecPos, int nPointIndex); // // CMapClass implementation. // void CalcBounds(BOOL bFullUpdate = FALSE); virtual CMapClass *Copy(bool bUpdateDependencies); virtual CMapClass *CopyFrom(CMapClass *pFrom, bool bUpdateDependencies); virtual void Render2D(CRender2D *pRender); virtual int SerializeRMF(std::fstream &File, BOOL bRMF); virtual int SerializeMAP(std::fstream &File, BOOL bRMF); // Overridden to chain down to our endpoints, which are not children. void SetOrigin(Vector &vecOrigin); // Overridden to chain down to our endpoints, which are not children. virtual SelectionState_t SetSelectionState(SelectionState_t eSelectionState); // Overridden because axis helpers don't take the color of their parent entity. virtual void SetRenderColor(unsigned char red, unsigned char green, unsigned char blue); virtual void SetRenderColor(color32 rgbColor); virtual bool HitTest2D(CMapView2D *pView, const Vector2D &point, HitInfo_t &HitData); virtual CBaseTool *GetToolObject(int nHitData, bool bAttachObject ); virtual bool IsVisualElement(void) { return true; } virtual bool IsClutter(void) const { return false; } virtual const char* GetDescription() { return("Swept player hull helper"); } virtual void OnAddToWorld(CMapWorld *pWorld); virtual void OnParentKeyChanged(const char *key, const char *value); virtual void PostloadWorld(CMapWorld *pWorld); virtual void Render3D(CRender3D *pRender); protected: SelectionState_t SetSelectionState(SelectionState_t eSelectionState, int nHandle); void UpdateParentKey(void); // Overriden to transform our endpoints, which are not children. virtual void DoTransform(const VMatrix &matrix); void Initialize(void); CMapPlayerHullHandle *m_Point[2]; // The two endpoints of the axis. }; inline bool IsSweptHullClass(CMapEntity *pEntity) { return (pEntity->GetChildOfType((CMapSweptPlayerHull *)NULL) != NULL); } #endif // MAPSWEPTPLAYERHULL_H
1
0.971984
1
0.971984
game-dev
MEDIA
0.622661
game-dev
0.55312
1
0.55312
ProjectIgnis/CardScripts
3,516
official/c15665977.lua
--キラーチューン・レッドシール --Killer Tune Red Seal --scripted by Naim local s,id=GetID() function s.initial_effect(c) c:EnableReviveLimit() --Synchro Summon procedure: "Killer Tune Reco" + 1+ Tuners Synchro.AddProcedure(c,aux.FALSE,1,1,s.tunerfilter,1,99,aux.FilterSummonCode(89392810)) --Gains 300 ATK for each Tuner in the GYs local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_MZONE) e1:SetValue(function(e,c) return 300*Duel.GetMatchingGroupCount(Card.IsType,0,LOCATION_GRAVE,LOCATION_GRAVE,nil,TYPE_TUNER) end) c:RegisterEffect(e1) --The Levels of monsters your opponent controls with 1700 or less original ATK are increased by 1 local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_UPDATE_LEVEL) e2:SetRange(LOCATION_MZONE) e2:SetTargetRange(0,LOCATION_MZONE) e2:SetTarget(function(e,c) return c:GetBaseAttack()<=1700 end) e2:SetValue(1) c:RegisterEffect(e2) --Negate the effects of 1 face-up card your opponent controls until the end of this turn local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,0)) e3:SetCategory(CATEGORY_DISABLE) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetCode(EVENT_FREE_CHAIN) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1,id) e3:SetCondition(function() return Duel.IsMainPhase() end) e3:SetCost(s.discost) e3:SetTarget(s.distg) e3:SetOperation(s.disop) e3:SetHintTiming(0,TIMING_STANDBY_PHASE|TIMING_MAIN_END|TIMINGS_CHECK_MONSTER) c:RegisterEffect(e3) --Multiple tuners local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_MATERIAL_CHECK) e4:SetValue(s.valcheck) c:RegisterEffect(e4) end s.listed_names={89392810} --"Killer Tune Reco" s.material={89392810} function s.tunerfilter(c,scard,sumtype,tp) return c:IsType(TYPE_TUNER,scard,sumtype,tp) or c:IsHasEffect(EFFECT_CAN_BE_TUNER) end function s.costfilter(c) return c:IsType(TYPE_TUNER) and c:IsAbleToRemoveAsCost() and aux.SpElimFilter(c,true) end function s.discost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function s.distg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and c:IsControler(1-tp) and chkc:IsNegatable() end if chk==0 then return Duel.IsExistingTarget(Card.IsNegatable,tp,0,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_NEGATE) local g=Duel.SelectTarget(tp,Card.IsNegatable,tp,0,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,1,tp,0) end function s.disop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then --Negate its effects until the end of this turn tc:NegateEffects(e:GetHandler(),RESET_PHASE|PHASE_END,true) end end function s.valcheck(e,c) local g=c:GetMaterial() if g:IsExists(function(c) return c:IsType(TYPE_TUNER) or c:IsHasEffect(EFFECT_CAN_BE_TUNER) end,2,nil) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_MULTIPLE_TUNERS) e1:SetReset(RESET_EVENT|(RESETS_STANDARD&~RESET_TOFIELD)|RESET_PHASE|PHASE_END) c:RegisterEffect(e1) end end
1
0.918655
1
0.918655
game-dev
MEDIA
0.987554
game-dev
0.945926
1
0.945926
Cannoneers-of-Create/CreateBigCannons
5,844
src/main/java/rbasamoyai/createbigcannons/effects/particles/explosions/FlakCloudParticle.java
package rbasamoyai.createbigcannons.effects.particles.explosions; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.minecraft.client.ParticleStatus; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.NoRenderParticle; import net.minecraft.client.particle.Particle; import net.minecraft.client.particle.ParticleProvider; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.phys.Vec3; import rbasamoyai.createbigcannons.CBCClientCommon; import rbasamoyai.createbigcannons.config.CBCConfigs; import rbasamoyai.createbigcannons.effects.particles.smoke.FlakSmokeParticleData; public class FlakCloudParticle extends NoRenderParticle { private final List<TrailSubparticle> trails = new LinkedList<>(); FlakCloudParticle(ClientLevel level, double x, double y, double z, double dx, double dy, double dz) { super(level, x, y, z, dx, dy, dz); if (CBCConfigs.client().showExtraFlakTrails.get()) { int count = switch (CBCClientCommon.getParticleStatus()) { case ALL -> 12 + level.random.nextInt(5); case DECREASED -> 4 + level.random.nextInt(3); case MINIMAL -> 0; }; for (int i = 0; i < count; ++i) { double dx1 = this.random.nextDouble() - this.random.nextDouble(); double dy1 = this.random.nextDouble() - this.random.nextDouble(); double dz1 = this.random.nextDouble() - this.random.nextDouble(); double rx = this.random.nextDouble() - this.random.nextDouble(); double ry = this.random.nextDouble() - this.random.nextDouble(); double rz = this.random.nextDouble() - this.random.nextDouble(); int lifetime = 5; this.trails.add(new TrailSubparticle(new Vec3(rx, ry, rz).scale(0.25), new Vec3(dx1, dy1, dz1).scale(2), 0.5, lifetime)); } } this.xd = dx; this.yd = dy; this.zd = dz; } @Override public void tick() { if (!CBCConfigs.client().showFlakClouds.get()) { this.remove(); return; } ParticleStatus status = CBCClientCommon.getParticleStatus(); int count = switch (status) { case ALL -> 30; case DECREASED -> 20; case MINIMAL -> 10; }; if (this.age == 0) { for (int i = 0; i < count; ++i) { double dx = this.random.nextDouble() - this.random.nextDouble(); double dy = this.random.nextDouble() - this.random.nextDouble(); double dz = this.random.nextDouble() - this.random.nextDouble(); double rx = this.random.nextDouble() - this.random.nextDouble(); double ry = this.random.nextDouble() - this.random.nextDouble(); double rz = this.random.nextDouble() - this.random.nextDouble(); int lifetime = 45 + this.random.nextInt(80); this.level.addParticle(new FlakSmokeParticleData(lifetime, 3), true, this.x + rx * 0.25, this.y + ry * 0.25, this.z + rz * 0.25, dx * 0.5, dy * 0.5, dz * 0.5); } if (status == ParticleStatus.ALL && CBCConfigs.client().showExtraFlakCloudFlames.get()) { for (int i = 0; i < 20; ++i) { double dx = this.random.nextDouble() - this.random.nextDouble(); double dy = this.random.nextDouble() - this.random.nextDouble(); double dz = this.random.nextDouble() - this.random.nextDouble(); double rx = this.random.nextDouble() - this.random.nextDouble(); double ry = this.random.nextDouble() - this.random.nextDouble(); double rz = this.random.nextDouble() - this.random.nextDouble(); this.level.addParticle(ParticleTypes.FLAME, true, this.x + rx * 0.25, this.y + ry * 0.25, this.z + rz * 0.25, dx * 0.3, dy * 0.3, dz * 0.3); } } if (status == ParticleStatus.ALL && CBCConfigs.client().showExtraFlakCloudShockwave.get()) { this.level.addParticle(ParticleTypes.EXPLOSION, this.x, this.y, this.z, 0, 0, 0); } } if (status != ParticleStatus.MINIMAL) { int trailSteps = status == ParticleStatus.ALL ? 5 : 2; for (Iterator<TrailSubparticle> iter = this.trails.iterator(); iter.hasNext(); ) { TrailSubparticle trail = iter.next(); if (this.age > trail.lifetime) { iter.remove(); continue; } Vec3 origin = trail.calculateDisplacement(this.age); Vec3 next = trail.calculateDisplacement(this.age + 1); for (int i = 0; i <= trailSteps; ++i) { Vec3 pos = origin.lerp(next, (double) i / (double) trailSteps).add(this.x, this.y, this.z); double dx = this.random.nextDouble() - this.random.nextDouble(); double dy = this.random.nextDouble() - this.random.nextDouble(); double dz = this.random.nextDouble() - this.random.nextDouble(); double rx = this.random.nextDouble() - this.random.nextDouble(); double ry = this.random.nextDouble() - this.random.nextDouble(); double rz = this.random.nextDouble() - this.random.nextDouble(); int lifetime = 20 + this.random.nextInt(5); this.level.addParticle(new FlakSmokeParticleData(lifetime, 1), true, pos.x + rx * 0.25, pos.y + ry * 0.25, pos.z + rz * 0.25, dx * 0.01, dy * 0.01, dz * 0.01); } } } super.tick(); } public static class Provider implements ParticleProvider<FlakCloudParticleData> { @Override public Particle createParticle(FlakCloudParticleData data, ClientLevel level, double x, double y, double z, double dx, double dy, double dz) { FlakCloudParticle particle = new FlakCloudParticle(level, x, y, z, dx, dy, dz); particle.setSize(0.25f, 0.25f); particle.setLifetime(30); return particle; } } private record TrailSubparticle(Vec3 displacement, Vec3 vel, double drag, int lifetime) { public Vec3 calculateDisplacement(int ticks) { if (ticks <= 0 || this.drag <= 1e-2d) return this.displacement; if (this.drag == 1) return this.displacement.add(this.vel.scale(ticks)); double geo = (1 - Math.pow(this.drag, ticks)) / (1 - this.drag); return this.displacement.add(this.vel.scale(geo)); } } }
1
0.769266
1
0.769266
game-dev
MEDIA
0.721403
game-dev
0.876701
1
0.876701
MrcSnm/HipremeEngine
6,372
modules/game2d/source/hip/gui/widget.d
module hip.gui.widget; /** * Whenever implementing layouts, only modify worldTransform. * Never modify local transform from other places. Only world transform is valid. */ class Widget { struct Bounds { int x, y, width, height; } struct Transform { int x, y; float rotation = 0, scaleX = 1, scaleY = 1; } int width, height; protected Widget parent; protected Widget[] children; protected Transform worldTransform; protected Transform localTransform; protected bool visible = true; protected bool propagates = true; protected bool isDirty = true; Bounds getWorldBounds() { Bounds b = Bounds(worldTransform.x, worldTransform.y, width, height); Bounds unmod = b; import hip.api; foreach(ch; children) { import hip.math.utils:min, max; Bounds chBounds = ch.getWorldBounds; b.x = min(b.x, chBounds.x); b.y = min(b.y, chBounds.y); b.width = max(b.width, chBounds.width+chBounds.x - unmod.x); b.height = max(b.height, chBounds.height+chBounds.y - unmod.y); } return b; } Widget findWidgetAt(float[2] pos){return findWidgetAt(cast(int)pos[0], cast(int)pos[1]);} Widget findWidgetAt(int x, int y) { import hip.math.collision; foreach_reverse(w; children) { Bounds wb = w.getWorldBounds(); if(w.visible && isPointInRect(x, y, wb.x, wb.y, wb.width, wb.height)) { if(w.propagates) return w.findWidgetAt(x, y); return w; } } Bounds wb = getWorldBounds(); return isPointInRect(x, y, wb.x, wb.y, wb.width, wb.height) ? this : null; } Bounds getLocalBounds(){return Bounds(localTransform.x,localTransform.y,width,height);} void setPosition(int x, int y) { isDirty = true; localTransform.x = x; localTransform.y = y; setChildrenDirty(); } protected void setChildrenDirty() { foreach(ch; children) { ch.isDirty = true; ch.setChildrenDirty(); } } private Widget getDirtyRoot() { Widget curr = parent; Widget last = curr; while(curr && curr.isDirty) { last = curr; curr = curr.parent; } return curr is null ? last : curr; } private void updateWorldTransform(in Transform* parentTransform) { if(parentTransform is null) worldTransform = localTransform; else { alias p = parentTransform; worldTransform.x = p.x+localTransform.x; worldTransform.y = p.y+localTransform.y; worldTransform.rotation = p.rotation+localTransform.rotation; worldTransform.scaleX = p.scaleX*localTransform.scaleX; worldTransform.scaleY = p.scaleY*localTransform.scaleY; } isDirty = false; foreach(ch; children) ch.updateWorldTransform(&worldTransform); } private void recalculateWorld() { if(isDirty) { Widget root = getDirtyRoot(); if(root) root.updateWorldTransform(root.parent ? &root.parent.worldTransform : null); else updateWorldTransform(parent ? &parent.worldTransform : null); } } void addChild(scope Widget[] widgets...) { foreach(w; widgets) addChild(w); } void addChild(Widget w) { children~= w; w.isDirty = true; w.parent = this; w.setChildrenDirty(); } void removeChild(Widget child) { import hip.util.array; if(!remove(children, child)) throw new Exception("Doesn't contain child."); child.parent = null; setChildrenDirty(); } void setParent(Widget w) { w.addChild(this); } //Event Methods void onFocusEnter() { isFocused = true; } void onFocusExit() { isFocused = false; } void onScroll(float[3] currentScroll, float[3] lastScroll) { setPosition( cast(int)(localTransform.x + currentScroll[0] - lastScroll[0]), cast(int)(localTransform.y + currentScroll[1] - lastScroll[1]) ); } ///Executed the first time the mouse enters in the widget's boundaries void onMouseEnter(){} ///Executed when the mouse goes down inside the widget void onMouseDown(){} ///Executed when both a mousedown and mouseup is executed when mouse is over this widget void onMouseClick(){} ///If onMouseDown was executed, onMouseUp will be called even if the mouse is not inside the widget void onMouseUp(){} void onMouseMove(){} private int dragOffsetX, dragOffsetY; void onDragStart(int x, int y) { dragOffsetX = worldTransform.x - x; dragOffsetY = worldTransform.y - y; } void onDragged(int x, int y) { import hip.api; setPosition(x + dragOffsetX, y + dragOffsetY); } void onDragEnd(){} ///Returns whether it accepted the receive bool onDropReceived(Widget w){return false;} void onMouseExit(){} bool isDraggable; bool isFocused; //End Event Methods void update() { foreach(ch; children) ch.update(); } protected void preRender(){recalculateWorld();} protected void render() { preRender(); onRender(); foreach(ch; children) if(ch.visible) ch.render(); } abstract void onRender(); } interface IWidgetRenderer { void render(int x, int y, int width, int height); } class DebugWidgetRenderer : IWidgetRenderer { import hip.api.graphics.color; import hip.math.random; HipColor color; this() { color[] = Random.rangeub(0, 255); } this(HipColor color){this.color = color;} void render(int x, int y, int width, int height) { import hip.api.graphics.g2d.renderer2d; fillRoundRect(x,y,width,height, 4, color); } }
1
0.920955
1
0.920955
game-dev
MEDIA
0.286396
game-dev
0.981735
1
0.981735
NeotokyoRebuild/neo
8,136
src/game/shared/neo/neo_ghost_cap_point.cpp
#include "cbase.h" #include "neo_ghost_cap_point.h" #include "neo_player_shared.h" #ifdef GAME_DLL #include "weapon_neobasecombatweapon.h" #if(0) // wide name localize helpers #include "tier3/tier3.h" #include "vgui/ILocalize.h" #endif #endif #ifdef CLIENT_DLL #include "ui/neo_hud_ghost_cap_point.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // In seconds, how often should the client think to update capzone graphics info. // This is *not* the framerate, only info like which team it belongs to, etc. // Actual rendering happens in the element's Paint() loop. static constexpr int NEO_GHOSTCAP_GRAPHICS_THINK_INTERVAL = 1; // NEO NOTE (Rain). These limits defined in original NT FGD as (48 - 256), // but it seems not even offical maps follow it. I haven't actually checked // if there's clamping in the original, but setting some sane limits here // anyways. These are in Hammer units. static constexpr float NEO_CAP_MIN_RADIUS = 8.0f; static constexpr float NEO_CAP_MAX_RADIUS = 10240.0f; static constexpr int NEO_FGD_TEAMNUM_ATTACKER = 0; static constexpr int NEO_FGD_TEAMNUM_DEFENDER = 1; LINK_ENTITY_TO_CLASS(neo_ghost_retrieval_point, CNEOGhostCapturePoint); #ifdef GAME_DLL IMPLEMENT_SERVERCLASS_ST(CNEOGhostCapturePoint, DT_NEOGhostCapturePoint) SendPropFloat(SENDINFO(m_flCapzoneRadius)), SendPropInt(SENDINFO(m_iOwningTeam)), SendPropInt(SENDINFO(m_iSuccessfulCaptorClientIndex)), SendPropBool(SENDINFO(m_bGhostHasBeenCaptured)), SendPropBool(SENDINFO(m_bIsActive)), END_SEND_TABLE() #else #ifdef CNEOGhostCapturePoint #undef CNEOGhostCapturePoint #endif IMPLEMENT_CLIENTCLASS_DT(C_NEOGhostCapturePoint, DT_NEOGhostCapturePoint, CNEOGhostCapturePoint) RecvPropFloat(RECVINFO(m_flCapzoneRadius)), RecvPropInt(RECVINFO(m_iOwningTeam)), RecvPropInt(RECVINFO(m_iSuccessfulCaptorClientIndex)), RecvPropBool(RECVINFO(m_bGhostHasBeenCaptured)), RecvPropBool(RECVINFO(m_bIsActive)), END_RECV_TABLE() #define CNEOGhostCapturePoint C_NEOGhostCapturePoint #endif BEGIN_DATADESC(CNEOGhostCapturePoint) #ifdef GAME_DLL DEFINE_THINKFUNC(Think_CheckMyRadius), #endif // These keyfields come from NT's FGD definition DEFINE_KEYFIELD(m_flCapzoneRadius, FIELD_FLOAT, "Radius"), DEFINE_KEYFIELD(m_iOwningTeam, FIELD_INTEGER, "team"), #ifdef GAME_DLL // Outputs DEFINE_OUTPUT(m_OnCap, "OnCap"), #endif END_DATADESC() CNEOGhostCapturePoint::CNEOGhostCapturePoint() { m_iSuccessfulCaptorClientIndex = 0; m_bIsActive = true; m_bGhostHasBeenCaptured = false; #ifdef CLIENT_DLL m_pHUDCapPoint = NULL; #endif } CNEOGhostCapturePoint::~CNEOGhostCapturePoint() { #ifdef CLIENT_DLL if (m_pHUDCapPoint) { m_pHUDCapPoint->DeletePanel(); m_pHUDCapPoint = NULL; } #endif } #ifdef GAME_DLL int CNEOGhostCapturePoint::UpdateTransmitState() { return FL_EDICT_ALWAYS; } bool CNEOGhostCapturePoint::IsGhostCaptured(int& outTeamNumber, int& outCaptorClientIndex) { if (m_bIsActive && m_bGhostHasBeenCaptured) { outTeamNumber = owningTeamAlternate(); outCaptorClientIndex = m_iSuccessfulCaptorClientIndex; CBaseEntity* pCaptor = UTIL_PlayerByIndex(m_iSuccessfulCaptorClientIndex); if (!pCaptor) // The capzone will be the activator if we can't find the guy who capped it { pCaptor = this; } m_OnCap.FireOutput(pCaptor, this); return true; } return false; } #endif int CNEOGhostCapturePoint::owningTeamAlternate() const { const bool alternate = NEORules()->roundAlternate(); int owningTeam = m_iOwningTeam; if (!alternate) owningTeam = (owningTeam == TEAM_JINRAI) ? TEAM_NSF : (owningTeam == TEAM_NSF) ? TEAM_JINRAI : owningTeam; return owningTeam; } void CNEOGhostCapturePoint::Spawn(void) { BaseClass::Spawn(); AddEFlags(EFL_FORCE_CHECK_TRANSMIT); #ifdef GAME_DLL // This is a Jinrai capzone if (m_iOwningTeam == NEO_FGD_TEAMNUM_ATTACKER) { m_iOwningTeam = TEAM_JINRAI; } // This is an NSF capzone else if (m_iOwningTeam == NEO_FGD_TEAMNUM_DEFENDER) { m_iOwningTeam = TEAM_NSF; } else { // We could recover, but it's probably better to break the capzone // and throw a nag message in console so the mapper can fix their error. Warning("Capzone had an invalid owning team: %i. Expected %i (Jinrai), or %i (NSF).\n", m_iOwningTeam.Get(), NEO_FGD_TEAMNUM_ATTACKER, NEO_FGD_TEAMNUM_DEFENDER); // Nobody will be able to cap here. m_iOwningTeam = TEAM_INVALID; } // Warning messages for the about-to-occur clamping, if we've hit limits. if (m_flCapzoneRadius < NEO_CAP_MIN_RADIUS) { Warning("Capzone had too small radius: %f, clamping! (Expected a minimum of %f)\n", m_flCapzoneRadius.Get(), NEO_CAP_MIN_RADIUS); } else if (m_flCapzoneRadius > NEO_CAP_MAX_RADIUS) { Warning("Capzone had too large radius: %f, clamping! (Expected a minimum of %f)\n", m_flCapzoneRadius.Get(), NEO_CAP_MAX_RADIUS); } // Actually clamp. m_flCapzoneRadius = clamp(m_flCapzoneRadius, NEO_CAP_MIN_RADIUS, NEO_CAP_MAX_RADIUS); // Set cap zone active if we've got a valid owner. SetActive(m_iOwningTeam == TEAM_JINRAI || m_iOwningTeam == TEAM_NSF); RegisterThinkContext("CheckMyRadius"); SetContextThink(&CNEOGhostCapturePoint::Think_CheckMyRadius, gpGlobals->curtime, "CheckMyRadius"); #else SetNextClientThink(gpGlobals->curtime + NEO_GHOSTCAP_GRAPHICS_THINK_INTERVAL); #endif } #ifdef GAME_DLL // Purpose: Checks if we have a valid ghoster inside our radius. void CNEOGhostCapturePoint::Think_CheckMyRadius(void) { if (m_bGhostHasBeenCaptured) { // We should have been reset after a cap before thinking! Assert(false); return; } // This round has already ended, we can't be capped into if (NEORules()->IsRoundOver()) { return; } const int checksPerSecond = 10; //DevMsg("CNEOGhostCapturePoint::Think_CheckMyRadius\n"); if (NEORules()->IsRoundLive()) { // VIP can escort themselves if sitting in their extract as the round restarts for (int i = 1; i <= gpGlobals->maxClients; i++) { CNEO_Player *player = static_cast<CNEO_Player*>(UTIL_EntityByIndex(i)); if (!player) { continue; } if (player->IsCarryingGhost() || player->GetClass() == NEO_CLASS_VIP) { const int team = player->GetTeamNumber(); Assert(team == TEAM_JINRAI || team == TEAM_NSF); bool isNotTeamCap = team != owningTeamAlternate(); // Is this our team's capzone? // NEO TODO (Rain): newbie UI helpers for attempting wrong team cap if (isNotTeamCap) { continue; } const Vector dir = player->GetAbsOrigin() - GetAbsOrigin(); const int distance = static_cast<int>(dir.Length()); Assert(distance >= 0); // Has the ghost carrier reached inside our radius? // NEO TODO (Rain): newbie UI helpers for approaching wrong team cap if (distance > m_flCapzoneRadius) { continue; } // We did it! m_bGhostHasBeenCaptured = true; m_iSuccessfulCaptorClientIndex = i; DevMsg("Player got ghost inside my radius\n"); // Return early; we pass next think responsibility to gamerules, // whenever it sees fit to start capzone thinking again. return; } } } SetContextThink(&CNEOGhostCapturePoint::Think_CheckMyRadius, gpGlobals->curtime + (1.0f / checksPerSecond), "CheckMyRadius"); } #else // Purpose: Set up clientside HUD graphics for capzone. void CNEOGhostCapturePoint::ClientThink(void) { BaseClass::ClientThink(); // If we haven't set up capzone HUD graphics yet if (!m_pHUDCapPoint) { m_pHUDCapPoint = new CNEOHud_GhostCapPoint("hudCapZone"); } m_pHUDCapPoint->SetPos(GetAbsOrigin()); m_pHUDCapPoint->SetRadius(m_flCapzoneRadius); m_pHUDCapPoint->SetTeam(owningTeamAlternate()); m_pHUDCapPoint->SetVisible(true); SetNextClientThink(gpGlobals->curtime + NEO_GHOSTCAP_GRAPHICS_THINK_INTERVAL); } #endif void CNEOGhostCapturePoint::Precache(void) { BaseClass::Precache(); AddEFlags(EFL_FORCE_CHECK_TRANSMIT); } void CNEOGhostCapturePoint::SetActive(bool isActive) { m_bIsActive = isActive; UpdateVisibility(); } inline void CNEOGhostCapturePoint::UpdateVisibility(void) { if (m_bIsActive) { RemoveEFlags(EF_NODRAW); } else { AddEFlags(EF_NODRAW); } }
1
0.944149
1
0.944149
game-dev
MEDIA
0.756575
game-dev,networking
0.988187
1
0.988187
Grimrukh/soulstruct
12,151
src/soulstruct/base/maps/enum_module_generator.py
"""Generates Python enum files for MSB entities for use as EMEVD arguments.""" from __future__ import annotations __all__ = [ "EnumModuleGenerator", ] import logging import re import typing as tp from pathlib import Path from soulstruct.base.game_types.map_types import MapEntity from soulstruct.games import Game from soulstruct.utilities.text import PY_NAME_RE from soulstruct.utilities.misc import IDList from .msb import MSB, MSBEntry, MSBEntryList from .msb.region_shapes import RegionShapeType _LOGGER = logging.getLogger(__name__) MAP_NAME_RE = re.compile(r"m(\d{2})_(\d{2})_(\d{2})_(\d{2})") TRAILING_DIGIT_RE = re.compile(r"(.*?)(\d+)") class EnumModuleGenerator: msb: MSB path: Path map_stem: str game: Game def __init__(self, msb: MSB, map_stem: str = None): self.msb = msb self.path = msb.path self.map_stem = map_stem or self.path.name.split(".")[0] self.game = self.msb.get_game() def write_enums_module( self, output_module_path: str | Path = None, append_to_module: str = "", separate_region_points_volumes: bool = False, sort_by_id=False, use_entity_id_ranges=True, comment_func: tp.Callable[[str, str], str] | None = None ): """Generates a '{mXX_YY}_enums.py' file with entity IDs for import into EVS scripts. If `append_to_module` text is given, all map enums will be appended to it. If `separate_region_points_volumes` is True, separate enums called `RegionPoints` and `RegionVolumes` (both inheriting from `Region`) will be created for `Region` entities based on their shape. This is useful for clearer arguments for EMEVD instructions like `IsInsideRegion`, so you're less likely to use shapeless Points. If `comment_func` is given, it should be a function that takes the enum class name (e.g. `Character`) and the MSB entity name (e.g. `c0000_0001`) and return an optional string to be appended to the enum line as a comment. """ if use_entity_id_ranges: if not (match := MAP_NAME_RE.match(self.map_stem)): _LOGGER.warning( f"Unusual map stem detected in `EnumModuleGenerator`: {self.map_stem}. Enum ID ranges will not be " f"applied to enum classes." ) auto_map_base_id = None else: aa_id, bb_id, cc_id, dd_id = map(int, match.group(1, 2, 3, 4)) if aa_id in {60, 61}: if dd_id not in {0, 1, 2}: _LOGGER.warning( f"Elden Ring overworld map tile size is invalid: {self.map_stem}. " f"Enum ID ranges will not be applied to enum classes." ) auto_map_base_id = None elif dd_id != 0: # Silently disable map ID ranges, since the true base entity ID for this map depends on the # small tile that each entity is actually in. auto_map_base_id = None else: # Elden Ring ten-digit overworld map format (small tiles). # Note that these match flags in Elden Ring. auto_map_base_id = int(f"10{bb_id:02d}{cc_id:02d}0000") elif self.game.variable_name == "ELDEN_RING": # Standard eight-digit format. auto_map_base_id = int(f"{aa_id:02d}{bb_id:02d}0000") else: # Older seven-digit format (single block digit). auto_map_base_id = int(f"{aa_id:02d}{bb_id:01d}{cc_id:02d}00") else: auto_map_base_id = None if output_module_path is None: if self.path is None: raise ValueError("Cannot auto-detect MSB entities `module_path` (MSB path not known).") output_module_path = self.path.parent / f"{self.path.name.split('.')[0]}_enums.py" else: output_module_path = Path(output_module_path) output_module_path.parent.mkdir(parents=True, exist_ok=True) game_types_import = f"from soulstruct.{self.game.submodule_name}.game_types import *" if append_to_module: if game_types_import not in append_to_module: # Add game type start import to module. (Very rare that it wouldn't already be there.) first_class_def_index = append_to_module.find("\nclass") if first_class_def_index != -1: append_to_module = append_to_module.replace("\nclass", game_types_import + "\n\nclass", 1) else: append_to_module += game_types_import module_text = append_to_module.rstrip("\n") + "\n" else: module_text = game_types_import for subtype_name, subtype_game_type in self.msb.ENTITY_GAME_TYPES.items(): if comment_func: def subtype_comment_func(name: str) -> str: return comment_func(subtype_game_type.__name__, name) else: subtype_comment_func = None if separate_region_points_volumes and subtype_name == "regions": # Two subtypes: `RegionPoints` and `RegionVolumes`. volume_shape_types = RegionShapeType.get_volume_types() other_shape_types = RegionShapeType.get_2d_types() for class_name, region_predicate in ( ("RegionPoints", lambda r: r.shape.SHAPE_TYPE == RegionShapeType.Point), ("RegionVolumes", lambda r: r.shape.SHAPE_TYPE in volume_shape_types), ("Region2D", lambda r: r.shape.SHAPE_TYPE in other_shape_types), # shouldn't exist but won't ignore ): filtered_regions = IDList([region for region in self.msb.get_regions() if region_predicate(region)]) if filtered_regions: class_contents = self._get_enum_class_contents( filtered_regions, sort_by_id, subtype_comment_func ) if class_contents: class_def = self._get_enum_class_def(class_name, subtype_game_type, auto_map_base_id) module_text += "\n" + class_def + class_contents else: # Standard: just one enum per subtype. class_name = subtype_game_type.get_msb_entry_supertype_subtype(pluralized_subtype=True)[1] subtype_list = getattr(self.msb, subtype_name) # type: MSBEntryList if subtype_list: class_contents = self._get_enum_class_contents(subtype_list, sort_by_id, subtype_comment_func) # If no entries in the list have entity IDs, `class_contents` will be empty. if class_contents: class_def = self._get_enum_class_def(class_name, subtype_game_type, auto_map_base_id) module_text += "\n" + class_def + class_contents module_text += "\n" # trailing newline with output_module_path.open("w", encoding="utf-8") as f: f.write(module_text) def _get_enum_class_contents( self, entry_list: IDList[MSBEntry], sort_by_id: bool, comment_func: tp.Callable[[str], str] | None = None, ) -> str: """Iterate over all MSB entries in the given list and return a string of definitions for an enum class. `entry_list` does not have to be a real `MSBEntryList`; just an `IDList[MSBEntry]`. """ entity_id_dict = self._get_entity_id_dict(entry_list, sort_by_entity_id=sort_by_id) # entity_id_dict = { # k: v for k, v in sorted(entity_id_dict.items(), key=self._sort_key) # } if not entity_id_dict: return "" class_lines = [] last_is_non_ascii = False for entity_id, entry in entity_id_dict.items(): # name = entry.name.replace(" ", "_") try: name = entry.name.encode("utf-8").decode("ascii") except UnicodeDecodeError: if not last_is_non_ascii: class_lines.append("# TODO: Non-ASCII name characters.") last_is_non_ascii = True class_lines.append(f"# {entry.name} = {entity_id}") # invalid name commented out name = entry.name else: last_is_non_ascii = False if not PY_NAME_RE.match(name): class_lines.append(f"# TODO: Invalid Python variable name.") class_lines.append(f"# {entry.name} = {entity_id}") # invalid name commented out else: # Best outcome: an MSB entry name that can be used as a Python variable name. class_lines.append(f"{name} = {entity_id}") if entry.description: class_lines[-1] += f" # {entry.description}" if comment_func: comment = comment_func(name) if comment: class_lines[-1] += f" # {comment}" return " " + "\n ".join(class_lines) def _get_enum_class_def( self, class_name: str, subtype_game_type: type[MapEntity], auto_map_base_id: int | None ) -> str: """Create class definition and docstring string.""" game_type_name = subtype_game_type.__name__ if auto_map_base_id is not None and subtype_game_type in self.msb.ID_RANGES: range_kwargs = self.msb.ID_RANGES[subtype_game_type](auto_map_base_id) try: first_value = range_kwargs["first_value"] last_value = range_kwargs["last_value"] except KeyError: _LOGGER.warning( f"`ID_RANGES` callback for {game_type_name} did not return `first_value` and `last_value`." ) class_def = f"\n\nclass {class_name}({game_type_name}):\n" else: class_def = f"\n\nclass {class_name}({game_type_name}, {first_value=}, {last_value=}):\n" else: class_def = f"\n\nclass {class_name}({game_type_name}):\n" class_def += f" \"\"\"`{game_type_name}` entity IDs for MSB and EVS use.\"\"\"\n\n" return class_def def _get_entity_id_dict(self, entries: IDList[MSBEntry], sort_by_entity_id=False) -> dict[int, MSBEntry]: """Get a dictionary mapping entity IDs to `MSBEntry` instances for this subtype list. If multiple `MSBEntry` instances are found for a given ID, a warning is logged, and only the *first* one found is used (which matches game engine behavior). Raises a `TypeError` if `entity_id` is not defined on this subtype. """ entries_by_id = {} for entry in entries: entity_id = entry.get_entity_id() if entity_id is None: raise TypeError(f"`entity_id` is not a valid field for MSB entry `{entry.name}`.") if entity_id <= 0: continue # ignore null ID if entity_id in entries_by_id: _LOGGER.warning( f"{self.map_stem}: Found multiple entries for entity ID {entity_id}. Using first only (in MSB " f"entry order), which is what the game engine will do with this ID." ) else: entries_by_id[entity_id] = entry if sort_by_entity_id: entries_by_id = {k: entries_by_id[k] for k in sorted(entries_by_id.keys())} return entries_by_id @staticmethod def _sort_key(key_value) -> tuple[str, int]: """Sort trailing digits properly.""" _, value_ = key_value if match := TRAILING_DIGIT_RE.match(value_.name): return match.group(1), int(match.group(2)) return value_.name, 0
1
0.895807
1
0.895807
game-dev
MEDIA
0.589944
game-dev
0.961283
1
0.961283
ForNeVeR/Cesium
1,050
Cesium.Runtime/FuncPtr.cs
// SPDX-FileCopyrightText: 2025 Cesium contributors <https://github.com/ForNeVeR/Cesium> // // SPDX-License-Identifier: MIT namespace Cesium.Runtime; /// <summary>A class encapsulating a C function pointer.</summary> public readonly unsafe struct FuncPtr<TDelegate> where TDelegate : MulticastDelegate // TODO[#487]: Think about vararg and empty parameter list encoding. { private readonly long _value; public FuncPtr(void* ptr) { _value = (long)ptr; } public static implicit operator TDelegate(FuncPtr<TDelegate> funcPtr) => (TDelegate)Activator.CreateInstance(typeof(TDelegate), [null, (IntPtr)funcPtr._value])!; public static implicit operator FuncPtr<TDelegate>(TDelegate @delegate) => @delegate.Method.MethodHandle.GetFunctionPointer(); public static implicit operator FuncPtr<TDelegate>(IntPtr funcPtr) => new((void*)funcPtr); public static implicit operator FuncPtr<TDelegate>(void* funcPtr) => new(funcPtr); public TDelegate AsDelegate() => this; public void* AsPtr() => (void*)_value; }
1
0.615144
1
0.615144
game-dev
MEDIA
0.516485
game-dev
0.567403
1
0.567403
ldmud/ldmud
2,984
mud/lp-245/room/bank.c
#include "std.h" int door_is_open, door_is_locked; object guard; #undef EXTRA_RESET #define EXTRA_RESET extra_reset(); void extra_reset() { if (!guard || !living(guard)) { object key, weapon; guard = clone_object("obj/monster"); guard->set_name("guard"); guard->set_level(11); guard->set_hp(200); guard->set_al(100); guard->set_short("A guard"); guard->set_long("A big and sturdy guard."); move_object(guard, this_object()); weapon = clone_object("obj/weapon"); weapon->set_name("shortsword"); weapon->set_short("A shortsword"); weapon->set_alias("sword"); weapon->set_long( "It is a professional looking short sword, used by warriors and guards"); weapon->set_class(15); weapon->set_value(700); weapon->set_weight(3); transfer(weapon, guard); guard->init_command("wield shortsword"); key = clone_object("obj/treasure"); key->set_id("key"); key->set_alias("bank key"); key->set_short("A bronze key"); key->set_value(10); key->set_weight(1); transfer(key, guard); } door_is_open = 0; door_is_locked = 1; } #undef EXTRA_LONG #define EXTRA_LONG\ if (str == "counter") {\ write("There is a sign in the counter that says\n" +\ "CLOSED FOR RECONSTRUCTION\n");\ return;\ }\ if (str == "door") {\ if (door_is_open) {\ write("The door is open.\n");\ return;\ }\ write("The door is closed.\n");\ return;\ } #undef EXTRA_INIT #define EXTRA_INIT\ add_action("open", "open");\ add_action("unlock", "unlock");\ add_action("east", "east"); ONE_EXIT("room/narr_alley","west", "The bank", "You are in the bank.\n" + "To the east is a low counter. The counter is covered\n" + "with heavy iron bars. On the wall beside the counter, a door\n" + "leads further east\n", 1) int id(string str) { return str == "door" || str == "counter"; } int open(string str) { if (str && str != "door") return 0; if (door_is_open) return 0; if (door_is_locked) { write("The door is locked.\n"); return 1; } door_is_open = 1; write("Ok.\n"); say(this_player()->query_name() + " opened the door.\n"); return 1; } int unlock(string str) { if (str && str != "door") return 0; if (door_is_open || !door_is_locked) return 0; if (!present("bank key", this_player())) { if (present("key", this_player())) write("You don't have the right key.\n"); else write("You need a key.\n"); return 1; } door_is_locked = 0; write("ok.\n"); say(this_player()->query_name() + " unlocked the door.\n"); return 1; } int east() { if (!door_is_open) { write("The door is closed.\n"); return 1; } if (guard && present(guard, this_object())) { write("The guard bars the way.\n"); return 1; } this_player()->move_player("east#room/bankroom"); return 1; } int query_door() { return !door_is_open; } void open_door_inside() { door_is_locked = 0; door_is_open = 1; } int query_drop_castle() { return 1; }
1
0.860697
1
0.860697
game-dev
MEDIA
0.49932
game-dev
0.795544
1
0.795544
dotnet/docs
5,367
docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex2.cs
// <Snippet4> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class Example15 { static Object randLock, numericLock; static Random rand; static CancellationTokenSource source; double totalValue = 0.0; int totalCount = 0; public Example15() { rand = new Random(); randLock = new Object(); numericLock = new Object(); source = new CancellationTokenSource(); } public static async Task Main() { Example15 ex = new Example15(); Thread.CurrentThread.Name = "Main"; await ex.Execute(); } private async Task Execute() { List<Task> tasks = new List<Task>(); for (int ctr = 0; ctr <= 10; ctr++) { CancellationToken token = source.Token; int taskNo = ctr; tasks.Add(Task.Run(() => { double previous = 0.0; int taskCtr = 0; double taskTotal = 0.0; double result = 0.0; for (int n = 0; n < 2000000; n++) { // Make sure there's no corruption of Random. token.ThrowIfCancellationRequested(); lock (randLock) { result = rand.NextDouble(); } // Check for corruption of Random instance. if ((result == previous) && result == 0) { source.Cancel(); } else { previous = result; } taskCtr++; taskTotal += result; } // Show result. Console.WriteLine($"Task {taskNo} finished execution."); Console.WriteLine($"Random numbers generated: {taskCtr:N0}"); Console.WriteLine($"Sum of random numbers: {taskTotal:N2}"); Console.WriteLine($"Random number mean: {taskTotal / taskCtr:N4}\n"); // Update overall totals. lock (numericLock) { totalCount += taskCtr; totalValue += taskTotal; } }, token)); } try { await Task.WhenAll(tasks.ToArray()); Console.WriteLine($"\nTotal random numbers generated: {totalCount:N0}"); Console.WriteLine($"Total sum of all random numbers: {totalValue:N2}"); Console.WriteLine($"Random number mean: {totalValue / totalCount:N4}"); } catch (AggregateException e) { foreach (Exception inner in e.InnerExceptions) { TaskCanceledException canc = inner as TaskCanceledException; if (canc != null) Console.WriteLine($"Task #{canc.Task.Id} cancelled."); else Console.WriteLine($"Exception: {inner.GetType().Name}"); } } finally { source.Dispose(); } } } // The example displays output like the following: // Task 1 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,502.47 // Random number mean: 0.5003 // // Task 0 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,445.63 // Random number mean: 0.5002 // // Task 2 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,556.04 // Random number mean: 0.5003 // // Task 3 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,178.87 // Random number mean: 0.5001 // // Task 4 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,819.17 // Random number mean: 0.4999 // // Task 5 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,190.58 // Random number mean: 0.5001 // // Task 6 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,720.21 // Random number mean: 0.4999 // // Task 7 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,000.96 // Random number mean: 0.4995 // // Task 8 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,499.33 // Random number mean: 0.4997 // // Task 9 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,193.25 // Random number mean: 0.5001 // // Task 10 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,960.82 // Random number mean: 0.5000 // // // Total random numbers generated: 22,000,000 // Total sum of all random numbers: 11,000,067.33 // Random number mean: 0.5000 // </Snippet4>
1
0.543695
1
0.543695
game-dev
MEDIA
0.28585
game-dev
0.649442
1
0.649442
mcneel/rhino3dm
3,534
src/librhino3dm_native/on_ground_plane.cpp
#include "stdafx.h" enum class GroundPlaneSetting : int { Enabled, ShowUnderside, AutoAltitude, Altitude, ShadowOnly, TextureOffsetLocked, TextureOffset, TextureSizeLocked, TextureSize, TextureRotation, MaterialInstanceId, }; RH_C_FUNCTION void ON_GroundPlane_GetValue(const ON_GroundPlane* gp, GroundPlaneSetting which, ON_XMLVariant* v) { if (gp && v) { switch (which) { case GroundPlaneSetting::Enabled: *v = gp->Enabled(); break; case GroundPlaneSetting::ShowUnderside: *v = gp->ShowUnderside(); break; case GroundPlaneSetting::AutoAltitude: *v = gp->AutoAltitude(); break; case GroundPlaneSetting::Altitude: *v = gp->Altitude(); break; case GroundPlaneSetting::ShadowOnly: *v = gp->ShadowOnly(); break; case GroundPlaneSetting::TextureOffsetLocked: *v = gp->TextureOffsetLocked(); break; case GroundPlaneSetting::TextureSizeLocked: *v = gp->TextureSizeLocked(); break; case GroundPlaneSetting::TextureRotation: *v = gp->TextureRotation(); break; case GroundPlaneSetting::MaterialInstanceId: *v = gp->MaterialInstanceId(); break; case GroundPlaneSetting::TextureOffset: *v = ON_2dPoint(gp->TextureOffset()); break; case GroundPlaneSetting::TextureSize: *v = ON_2dPoint(gp->TextureSize()); break; default: break; } } } RH_C_FUNCTION void ON_GroundPlane_SetValue(ON_GroundPlane* gp, GroundPlaneSetting which, const ON_XMLVariant* v) { if (gp && v) { switch (which) { case GroundPlaneSetting::Enabled: gp->SetEnabled(v->AsBool()); break; case GroundPlaneSetting::ShowUnderside: gp->SetShowUnderside(v->AsBool()); break; case GroundPlaneSetting::AutoAltitude: gp->SetAutoAltitude(v->AsBool()); break; case GroundPlaneSetting::Altitude: gp->SetAltitude(v->AsDouble()); break; case GroundPlaneSetting::ShadowOnly: gp->SetShadowOnly(v->AsBool()); break; case GroundPlaneSetting::TextureOffsetLocked: gp->SetTextureOffsetLocked(v->AsBool()); break; case GroundPlaneSetting::TextureOffset: gp->SetTextureOffset(v->As2dPoint()); break; case GroundPlaneSetting::TextureSizeLocked: gp->SetTextureSizeLocked(v->AsBool()); break; case GroundPlaneSetting::TextureSize: gp->SetTextureSize(v->As2dPoint()); break; case GroundPlaneSetting::TextureRotation: gp->SetTextureRotation(v->AsDouble()); break; case GroundPlaneSetting::MaterialInstanceId: gp->SetMaterialInstanceId(v->AsUuid()); break; default: break; } } } RH_C_FUNCTION void ON_3dmRenderSettings_GroundPlane_SetValue(ON_3dmRenderSettings* rs, GroundPlaneSetting which, const ON_XMLVariant* v) { if (nullptr != rs) { ON_GroundPlane_SetValue(&rs->GroundPlane(), which, v); } } RH_C_FUNCTION const ON_GroundPlane* ON_GroundPlane_FromONX_Model(ONX_Model* ptrModel) { if (nullptr == ptrModel) return nullptr; return &ptrModel->m_settings.m_RenderSettings.GroundPlane(); } RH_C_FUNCTION ON_GroundPlane* ON_GroundPlane_New() { return new ON_GroundPlane; } RH_C_FUNCTION void ON_GroundPlane_Delete(ON_GroundPlane* p) { delete p; } RH_C_FUNCTION void ON_GroundPlane_CopyFrom(ON_GroundPlane* target, const ON_GroundPlane* source) { if ((nullptr != target) && (nullptr != source)) { *target = *source; } }
1
0.814985
1
0.814985
game-dev
MEDIA
0.831689
game-dev
0.894346
1
0.894346
disruptorbeam/trilleon
6,480
client/Library/PackageCache/com.unity.ide.visualstudio@2.0.5/Editor/ProjectGeneration/AssemblyNameProvider.cs
/*--------------------------------------------------------------------------------------------- * Copyright (c) Unity Technologies. * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.Compilation; using UnityEditor.PackageManager; namespace Microsoft.Unity.VisualStudio.Editor { public interface IAssemblyNameProvider { string[] ProjectSupportedExtensions { get; } string ProjectGenerationRootNamespace { get; } ProjectGenerationFlag ProjectGenerationFlag { get; } string GetAssemblyNameFromScriptPath(string path); string GetAssemblyName(string assemblyOutputPath, string assemblyName); bool IsInternalizedPackagePath(string path); IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution); IEnumerable<string> GetAllAssetPaths(); UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories); void ToggleProjectGeneration(ProjectGenerationFlag preference); } public class AssemblyNameProvider : IAssemblyNameProvider { ProjectGenerationFlag m_ProjectGenerationFlag = (ProjectGenerationFlag)EditorPrefs.GetInt( "unity_project_generation_flag", (int)(ProjectGenerationFlag.Local | ProjectGenerationFlag.Embedded)); public string[] ProjectSupportedExtensions => EditorSettings.projectGenerationUserExtensions; public string ProjectGenerationRootNamespace => EditorSettings.projectGenerationRootNamespace; public ProjectGenerationFlag ProjectGenerationFlag { get => m_ProjectGenerationFlag; private set { EditorPrefs.SetInt("unity_project_generation_flag", (int)value); m_ProjectGenerationFlag = value; } } public string GetAssemblyNameFromScriptPath(string path) { return CompilationPipeline.GetAssemblyNameFromScriptPath(path); } public IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution) { foreach (var assembly in CompilationPipeline.GetAssemblies()) { if (assembly.sourceFiles.Any(shouldFileBePartOfSolution)) { var options = new ScriptCompilerOptions { ResponseFiles = assembly.compilerOptions.ResponseFiles, AllowUnsafeCode = assembly.compilerOptions.AllowUnsafeCode, ApiCompatibilityLevel = assembly.compilerOptions.ApiCompatibilityLevel }; yield return new Assembly(assembly.name, @"Temp\Bin\Debug\", assembly.sourceFiles, new[] { "DEBUG", "TRACE" }.Concat(assembly.defines).Concat(EditorUserBuildSettings.activeScriptCompilationDefines).ToArray(), assembly.assemblyReferences, assembly.compiledAssemblyReferences, assembly.flags, #if UNITY_2020_2_OR_NEWER options, assembly.rootNamespace); #else options); #endif } } if (ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies)) { foreach (var assembly in CompilationPipeline.GetAssemblies(AssembliesType.Player).Where(assembly => assembly.sourceFiles.Any(shouldFileBePartOfSolution))) { var options = new ScriptCompilerOptions { ResponseFiles = assembly.compilerOptions.ResponseFiles, AllowUnsafeCode = assembly.compilerOptions.AllowUnsafeCode, ApiCompatibilityLevel = assembly.compilerOptions.ApiCompatibilityLevel }; yield return new Assembly(assembly.name, @"Temp\Bin\Debug\Player\", assembly.sourceFiles, new[] { "DEBUG", "TRACE" }.Concat(assembly.defines).ToArray(), assembly.assemblyReferences, assembly.compiledAssemblyReferences, assembly.flags, #if UNITY_2020_2_OR_NEWER options, assembly.rootNamespace); #else options); #endif } } } public string GetCompileOutputPath(string assemblyName) { return assemblyName.EndsWith(".Player", StringComparison.Ordinal) ? @"Temp\Bin\Debug\Player\" : @"Temp\Bin\Debug\"; } public IEnumerable<string> GetAllAssetPaths() { return AssetDatabase.GetAllAssetPaths(); } public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) { return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); } public bool IsInternalizedPackagePath(string path) { if (string.IsNullOrEmpty(path.Trim())) { return false; } var packageInfo = FindForAssetPath(path); if (packageInfo == null) { return false; } var packageSource = packageInfo.source; switch (packageSource) { case PackageSource.Embedded: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Embedded); case PackageSource.Registry: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Registry); case PackageSource.BuiltIn: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.BuiltIn); case PackageSource.Unknown: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Unknown); case PackageSource.Local: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Local); case PackageSource.Git: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Git); case PackageSource.LocalTarball: return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.LocalTarBall); } return false; } public ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories) { return CompilationPipeline.ParseResponseFile( responseFilePath, projectDirectory, systemReferenceDirectories ); } public void ToggleProjectGeneration(ProjectGenerationFlag preference) { if (ProjectGenerationFlag.HasFlag(preference)) { ProjectGenerationFlag ^= preference; } else { ProjectGenerationFlag |= preference; } } public void ResetProjectGenerationFlag() { ProjectGenerationFlag = ProjectGenerationFlag.None; } public string GetAssemblyName(string assemblyOutputPath, string assemblyName) { return assemblyOutputPath.EndsWith(@"\Player\", StringComparison.Ordinal) ? assemblyName + ".Player" : assemblyName; } } }
1
0.73605
1
0.73605
game-dev
MEDIA
0.346725
game-dev
0.721127
1
0.721127
chai3d/chai3d
60,342
modules/Bullet/externals/bullet/examples/SoftDemo/SoftDemo.cpp
/* 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. */ ///btSoftBody implementation by Nathanael Presson #include "btBulletDynamicsCommon.h" #include "BulletSoftBody/btSoftRigidDynamicsWorld.h" #include "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btIDebugDraw.h" #include "BunnyMesh.h" #include "TorusMesh.h" #include <stdio.h> //printf debugging #include "LinearMath/btConvexHull.h" #include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h" #include "BulletSoftBody/btSoftBodyHelpers.h" #include "SoftDemo.h" #include "GL_ShapeDrawer.h" #include "LinearMath/btAlignedObjectArray.h" #include "BulletSoftBody/btSoftBody.h" class btBroadphaseInterface; class btCollisionShape; class btOverlappingPairCache; class btCollisionDispatcher; class btConstraintSolver; struct btCollisionAlgorithmCreateFunc; class btDefaultCollisionConfiguration; ///collisions between two btSoftBody's class btSoftSoftCollisionAlgorithm; ///collisions between a btSoftBody and a btRigidBody class btSoftRididCollisionAlgorithm; class btSoftRigidDynamicsWorld; #include "../CommonInterfaces/CommonRigidBodyBase.h" class SoftDemo : public CommonRigidBodyBase { public: btAlignedObjectArray<btSoftSoftCollisionAlgorithm*> m_SoftSoftCollisionAlgorithms; btAlignedObjectArray<btSoftRididCollisionAlgorithm*> m_SoftRigidCollisionAlgorithms; btSoftBodyWorldInfo m_softBodyWorldInfo; bool m_autocam; bool m_cutting; bool m_raycast; btScalar m_animtime; btClock m_clock; int m_lastmousepos[2]; btVector3 m_impact; btSoftBody::sRayCast m_results; btSoftBody::Node* m_node; btVector3 m_goal; bool m_drag; //keep the collision shapes, for deletion/cleanup btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btBroadphaseInterface* m_broadphase; btCollisionDispatcher* m_dispatcher; btConstraintSolver* m_solver; btCollisionAlgorithmCreateFunc* m_boxBoxCF; btDefaultCollisionConfiguration* m_collisionConfiguration; public: void initPhysics(); void exitPhysics(); virtual void resetCamera() { //@todo depends on current_demo? float dist = 45; float pitch = 27; float yaw = 31; float targetPos[3]={10-1,0}; m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]); } SoftDemo(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper), m_drag(false) { } virtual ~SoftDemo() { btAssert(m_dynamicsWorld==0); } //virtual void clientMoveAndDisplay(); //virtual void displayCallback(); void createStack( btCollisionShape* boxShape, float halfCubeSize, int size, float zPos ); virtual void setDrawClusters(bool drawClusters); virtual const btSoftRigidDynamicsWorld* getSoftDynamicsWorld() const { ///just make it a btSoftRigidDynamicsWorld please ///or we will add type checking return (btSoftRigidDynamicsWorld*) m_dynamicsWorld; } virtual btSoftRigidDynamicsWorld* getSoftDynamicsWorld() { ///just make it a btSoftRigidDynamicsWorld please ///or we will add type checking return (btSoftRigidDynamicsWorld*) m_dynamicsWorld; } // //void clientResetScene(); void renderme(); void keyboardCallback(unsigned char key, int x, int y); void mouseFunc(int button, int state, int x, int y); void mouseMotionFunc(int x,int y); GUIHelperInterface* getGUIHelper() { return m_guiHelper; } virtual void renderScene() { CommonRigidBodyBase::renderScene(); btSoftRigidDynamicsWorld* softWorld = getSoftDynamicsWorld(); for ( int i=0;i<softWorld->getSoftBodyArray().size();i++) { btSoftBody* psb=(btSoftBody*)softWorld->getSoftBodyArray()[i]; if (softWorld->getDebugDrawer() && !(softWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe))) { btSoftBodyHelpers::DrawFrame(psb,softWorld->getDebugDrawer()); btSoftBodyHelpers::Draw(psb,softWorld->getDebugDrawer(),softWorld->getDrawFlags()); } } } }; #define MACRO_SOFT_DEMO(a) class SoftDemo##a : public SoftDemo\ {\ public:\ static DemoApplication* Create()\ {\ SoftDemo* demo = new SoftDemo##a;\ extern int current_demo;\ current_demo=a;\ demo->initPhysics();\ return demo;\ }\ }; //MACRO_SOFT_DEMO(0) //Init_Cloth #if 0 MACRO_SOFT_DEMO(1) //Init_Pressure MACRO_SOFT_DEMO(2)//Init_Volume MACRO_SOFT_DEMO(3)//Init_Ropes MACRO_SOFT_DEMO(4)//Init_Ropes_Attach MACRO_SOFT_DEMO(5)//Init_ClothAttach MACRO_SOFT_DEMO(6)//Init_Sticks MACRO_SOFT_DEMO(7)//Init_Collide MACRO_SOFT_DEMO(8)//Init_Collide2 MACRO_SOFT_DEMO(9)//Init_Collide3 MACRO_SOFT_DEMO(10)//Init_Impact MACRO_SOFT_DEMO(11)//Init_Aero MACRO_SOFT_DEMO(12)//Init_Friction MACRO_SOFT_DEMO(13)//Init_Torus MACRO_SOFT_DEMO(14)//Init_TorusMatch MACRO_SOFT_DEMO(15)//Init_Bunny MACRO_SOFT_DEMO(16)//Init_BunnyMatch MACRO_SOFT_DEMO(17)//Init_Cutting1 MACRO_SOFT_DEMO(18)//Init_ClusterDeform MACRO_SOFT_DEMO(19)//Init_ClusterCollide1 MACRO_SOFT_DEMO(20)//Init_ClusterCollide2 MACRO_SOFT_DEMO(21)//Init_ClusterSocket MACRO_SOFT_DEMO(22)//Init_ClusterHinge MACRO_SOFT_DEMO(23)//Init_ClusterCombine MACRO_SOFT_DEMO(24)//Init_ClusterCar MACRO_SOFT_DEMO(25)//Init_ClusterRobot MACRO_SOFT_DEMO(26)//Init_ClusterStackSoft MACRO_SOFT_DEMO(27)//Init_ClusterStackMixed MACRO_SOFT_DEMO(28)//Init_TetraCube MACRO_SOFT_DEMO(29)//Init_TetraBunny #endif extern float eye[3]; extern int glutScreenWidth; extern int glutScreenHeight; static bool sDemoMode = false; const int maxProxies = 32766; const int maxOverlap = 65535; static btVector3* gGroundVertices=0; static int* gGroundIndices=0; static btBvhTriangleMeshShape* trimeshShape =0; static btRigidBody* staticBody = 0; static float waveheight = 5.f; const float TRIANGLE_SIZE=8.f; int current_demo=20; #define DEMO_MODE_TIMEOUT 15.f //15 seconds for each demo #ifdef _DEBUG const int gNumObjects = 1; #else const int gNumObjects = 1;//try this in release mode: 3000. never go above 16384, unless you increate maxNumObjects value in DemoApplication.cp #endif const int maxNumObjects = 32760; #define CUBE_HALF_EXTENTS 1.5 #define EXTRA_HEIGHT -10.f // void SoftDemo::createStack( btCollisionShape* boxShape, float halfCubeSize, int size, float zPos ) { btTransform trans; trans.setIdentity(); for(int i=0; i<size; i++) { // This constructs a row, from left to right int rowSize = size - i; for(int j=0; j< rowSize; j++) { btVector3 pos; pos.setValue( -rowSize * halfCubeSize + halfCubeSize + j * 2.0f * halfCubeSize, halfCubeSize + i * halfCubeSize * 2.0f, zPos); trans.setOrigin(pos); btScalar mass = 1.f; btRigidBody* body = 0; body = createRigidBody(mass,trans,boxShape); } } } //////////////////////////////////// extern int gNumManifold; extern int gOverlappingPairs; ///for mouse picking void pickingPreTickCallback (btDynamicsWorld *world, btScalar timeStep) { SoftDemo* softDemo = (SoftDemo*)world->getWorldUserInfo(); if(softDemo->m_drag) { const int x=softDemo->m_lastmousepos[0]; const int y=softDemo->m_lastmousepos[1]; float rf[3]; softDemo->getGUIHelper()->getRenderInterface()->getActiveCamera()->getCameraPosition(rf); float target[3]; softDemo->getGUIHelper()->getRenderInterface()->getActiveCamera()->getCameraTargetPosition(target); btVector3 cameraTargetPosition(target[0],target[1],target[2]); const btVector3 cameraPosition(rf[0],rf[1],rf[2]); const btVector3 rayFrom=cameraPosition; const btVector3 rayTo=softDemo->getRayTo(x,y); const btVector3 rayDir=(rayTo-rayFrom).normalized(); const btVector3 N=(cameraTargetPosition-cameraPosition).normalized(); const btScalar O=btDot(softDemo->m_impact,N); const btScalar den=btDot(N,rayDir); if((den*den)>0) { const btScalar num=O-btDot(N,rayFrom); const btScalar hit=num/den; if((hit>0)&&(hit<1500)) { softDemo->m_goal=rayFrom+rayDir*hit; } } btVector3 delta=softDemo->m_goal-softDemo->m_node->m_x; static const btScalar maxdrag=10; if(delta.length2()>(maxdrag*maxdrag)) { delta=delta.normalized()*maxdrag; } softDemo->m_node->m_v+=delta/timeStep; } } // // ImplicitShape // // struct ImplicitSphere : btSoftBody::ImplicitFn { btVector3 center; btScalar sqradius; ImplicitSphere() {} ImplicitSphere(const btVector3& c,btScalar r) : center(c),sqradius(r*r) {} btScalar Eval(const btVector3& x) { return((x-center).length2()-sqradius); } }; // // Tetra meshes // struct TetraBunny { #include "bunny.inl" }; struct TetraCube { #include "cube.inl" }; // // Random // static inline btScalar UnitRand() { return(rand()/(btScalar)RAND_MAX); } static inline btScalar SignedUnitRand() { return(UnitRand()*2-1); } static inline btVector3 Vector3Rand() { const btVector3 p=btVector3(SignedUnitRand(),SignedUnitRand(),SignedUnitRand()); return(p.normalized()); } // // Rb rain // static void Ctor_RbUpStack(SoftDemo* pdemo,int count) { float mass=10; btCompoundShape* cylinderCompound = new btCompoundShape; btCollisionShape* cylinderShape = new btCylinderShapeX(btVector3(4,1,1)); btCollisionShape* boxShape = new btBoxShape(btVector3(4,1,1)); btTransform localTransform; localTransform.setIdentity(); cylinderCompound->addChildShape(localTransform,boxShape); btQuaternion orn(SIMD_HALF_PI,0,0); localTransform.setRotation(orn); // localTransform.setOrigin(btVector3(1,1,1)); cylinderCompound->addChildShape(localTransform,cylinderShape); btCollisionShape* shape[]={cylinderCompound, new btBoxShape(btVector3(1,1,1)), new btSphereShape(1.5) }; static const int nshapes=sizeof(shape)/sizeof(shape[0]); for(int i=0;i<count;++i) { btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,2+6*i,0)); pdemo->createRigidBody(mass,startTransform,shape[i%nshapes]); //pdemo->createRigidBody(mass,startTransform,shape[0]); } } // // Big ball // static void Ctor_BigBall(SoftDemo* pdemo,btScalar mass=10) { btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,13,0)); pdemo->createRigidBody(mass,startTransform,new btSphereShape(3)); } // // Big plate // static btRigidBody* Ctor_BigPlate(SoftDemo* pdemo,btScalar mass=15,btScalar height=4) { btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,height,0.5)); btRigidBody* body=pdemo->createRigidBody(mass,startTransform,new btBoxShape(btVector3(5,1,5))); body->setFriction(1); return(body); } // // Linear stair // static void Ctor_LinearStair(SoftDemo* pdemo,const btVector3& org,const btVector3& sizes,btScalar angle,int count) { btBoxShape* shape=new btBoxShape(sizes); for(int i=0;i<count;++i) { btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(org+btVector3(sizes.x()*i*2,sizes.y()*i*2,0)); btRigidBody* body=pdemo->createRigidBody(0,startTransform,shape); body->setFriction(1); } } // // Softbox // static btSoftBody* Ctor_SoftBox(SoftDemo* pdemo,const btVector3& p,const btVector3& s) { const btVector3 h=s*0.5; const btVector3 c[]={ p+h*btVector3(-1,-1,-1), p+h*btVector3(+1,-1,-1), p+h*btVector3(-1,+1,-1), p+h*btVector3(+1,+1,-1), p+h*btVector3(-1,-1,+1), p+h*btVector3(+1,-1,+1), p+h*btVector3(-1,+1,+1), p+h*btVector3(+1,+1,+1)}; btSoftBody* psb=btSoftBodyHelpers::CreateFromConvexHull(pdemo->m_softBodyWorldInfo,c,8); psb->generateBendingConstraints(2); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } // // SoftBoulder // static btSoftBody* Ctor_SoftBoulder(SoftDemo* pdemo,const btVector3& p,const btVector3& s,int np,int id) { btAlignedObjectArray<btVector3> pts; if(id) srand(id); for(int i=0;i<np;++i) { pts.push_back(Vector3Rand()*s+p); } btSoftBody* psb=btSoftBodyHelpers::CreateFromConvexHull(pdemo->m_softBodyWorldInfo,&pts[0],pts.size()); psb->generateBendingConstraints(2); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } //#define TRACEDEMO { pdemo->demoname=__FUNCTION__+5;printf("Launching demo: " __FUNCTION__ "\r\n"); } // // Basic ropes // static void Init_Ropes(SoftDemo* pdemo) { //TRACEDEMO const int n=15; for(int i=0;i<n;++i) { btSoftBody* psb=btSoftBodyHelpers::CreateRope(pdemo->m_softBodyWorldInfo, btVector3(-10,0,i*0.25), btVector3(10,0,i*0.25), 16, 1+2); psb->m_cfg.piterations = 4; psb->m_materials[0]->m_kLST = 0.1+(i/(btScalar)(n-1))*0.9; psb->setTotalMass(20); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } } // // Rope attach // static void Init_RopeAttach(SoftDemo* pdemo) { //TRACEDEMO pdemo->m_softBodyWorldInfo.m_sparsesdf.RemoveReferences(0); struct Functors { static btSoftBody* CtorRope(SoftDemo* pdemo,const btVector3& p) { btSoftBody* psb=btSoftBodyHelpers::CreateRope(pdemo->m_softBodyWorldInfo,p,p+btVector3(10,0,0),8,1); psb->setTotalMass(50); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } }; btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(12,8,0)); btRigidBody* body=pdemo->createRigidBody(50,startTransform,new btBoxShape(btVector3(2,6,2))); btSoftBody* psb0=Functors::CtorRope(pdemo,btVector3(0,8,-1)); btSoftBody* psb1=Functors::CtorRope(pdemo,btVector3(0,8,+1)); psb0->appendAnchor(psb0->m_nodes.size()-1,body); psb1->appendAnchor(psb1->m_nodes.size()-1,body); } // // Cloth attach // static void Init_ClothAttach(SoftDemo* pdemo) { //TRACEDEMO const btScalar s=4; const btScalar h=6; const int r=9; btSoftBody* psb=btSoftBodyHelpers::CreatePatch(pdemo->m_softBodyWorldInfo,btVector3(-s,h,-s), btVector3(+s,h,-s), btVector3(-s,h,+s), btVector3(+s,h,+s),r,r,4+8,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,h,-(s+3.5))); btRigidBody* body=pdemo->createRigidBody(20,startTransform,new btBoxShape(btVector3(s,1,3))); psb->appendAnchor(0,body); psb->appendAnchor(r-1,body); pdemo->m_cutting=true; } // // Impact // static void Init_Impact(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateRope(pdemo->m_softBodyWorldInfo, btVector3(0,0,0), btVector3(0,-1,0), 0, 1); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); psb->m_cfg.kCHR=0.5; btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,20,0)); pdemo->createRigidBody(10,startTransform,new btBoxShape(btVector3(2,2,2))); } static void Init_CapsuleCollision(SoftDemo* pdemo) { #ifdef USE_AMD_OPENCL btAlignedObjectArray<btSoftBody*> emptyArray; if (g_openCLSIMDSolver) g_openCLSIMDSolver->optimize(emptyArray); #endif //USE_AMD_OPENCL //TRACEDEMO const btScalar s=4; const btScalar h=6; const int r=20; btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,h-2,0)); btCollisionShape* capsuleShape= new btCapsuleShapeX(1,5); capsuleShape->setMargin( 0.5 ); // capsule->setLocalScaling(btVector3(5,1,1)); // btRigidBody* body=pdemo->createRigidBody(20,startTransform,capsuleShape); btRigidBody* body=pdemo->createRigidBody(0,startTransform,capsuleShape); body->setFriction( 0.8f ); int fixed=0;//4+8; btSoftBody* psb=btSoftBodyHelpers::CreatePatch(pdemo->m_softBodyWorldInfo,btVector3(-s,h,-s), btVector3(+s,h,-s), btVector3(-s,h,+s), btVector3(+s,h,+s),r,r,fixed,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); psb->setTotalMass(0.1); psb->m_cfg.piterations = 10; psb->m_cfg.citerations = 10; psb->m_cfg.diterations = 10; // psb->m_cfg.viterations = 10; // psb->appendAnchor(0,body); // psb->appendAnchor(r-1,body); // pdemo->m_cutting=true; } // // Collide // static void Init_Collide(SoftDemo* pdemo) { //TRACEDEMO struct Functor { static btSoftBody* Create(SoftDemo* pdemo,const btVector3& x,const btVector3& a) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVertices, &gIndices[0][0], NUM_TRIANGLES); psb->generateBendingConstraints(2); psb->m_cfg.piterations=2; psb->m_cfg.collisions|=btSoftBody::fCollision::VF_SS; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(a.x(),a.y(),a.z()); psb->transform(btTransform(m,x)); psb->scale(btVector3(2,2,2)); psb->setTotalMass(50,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } }; for(int i=0;i<3;++i) { Functor::Create(pdemo,btVector3(3*i,2,0),btVector3(SIMD_PI/2*(1-(i&1)),SIMD_PI/2*(i&1),0)); } pdemo->m_cutting=true; } // // Collide2 // static void Init_Collide2(SoftDemo* pdemo) { //TRACEDEMO struct Functor { static btSoftBody* Create(SoftDemo* pdemo,const btVector3& x,const btVector3& a) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVerticesBunny, &gIndicesBunny[0][0], BUNNY_NUM_TRIANGLES); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.5; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.piterations = 2; psb->m_cfg.kDF = 0.5; psb->m_cfg.collisions |= btSoftBody::fCollision::VF_SS; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(a.x(),a.y(),a.z()); psb->transform(btTransform(m,x)); psb->scale(btVector3(6,6,6)); psb->setTotalMass(100,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } }; for(int i=0;i<3;++i) { Functor::Create(pdemo,btVector3(0,-1+5*i,0),btVector3(0,SIMD_PI/2*(i&1),0)); } pdemo->m_cutting=true; } // // Collide3 // static void Init_Collide3(SoftDemo* pdemo) { //TRACEDEMO { const btScalar s=8; btSoftBody* psb=btSoftBodyHelpers::CreatePatch( pdemo->m_softBodyWorldInfo,btVector3(-s,0,-s), btVector3(+s,0,-s), btVector3(-s,0,+s), btVector3(+s,0,+s), 15,15,1+2+4+8,true); psb->m_materials[0]->m_kLST = 0.4; psb->m_cfg.collisions |= btSoftBody::fCollision::VF_SS; psb->setTotalMass(150); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } { const btScalar s=4; const btVector3 o=btVector3(5,10,0); btSoftBody* psb=btSoftBodyHelpers::CreatePatch( pdemo->m_softBodyWorldInfo, btVector3(-s,0,-s)+o, btVector3(+s,0,-s)+o, btVector3(-s,0,+s)+o, btVector3(+s,0,+s)+o, 7,7,0,true); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.1; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_materials[0]->m_kLST = 0.5; psb->m_cfg.collisions |= btSoftBody::fCollision::VF_SS; psb->setTotalMass(150); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); pdemo->m_cutting=true; } } // // Aerodynamic forces, 50x1g flyers // static void Init_Aero(SoftDemo* pdemo) { //TRACEDEMO const btScalar s=2; const btScalar h=10; const int segments=6; const int count=50; for(int i=0;i<count;++i) { btSoftBody* psb=btSoftBodyHelpers::CreatePatch(pdemo->m_softBodyWorldInfo,btVector3(-s,h,-s), btVector3(+s,h,-s), btVector3(-s,h,+s), btVector3(+s,h,+s), segments,segments, 0,true); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.kLF = 0.004; psb->m_cfg.kDG = 0.0003; psb->m_cfg.aeromodel = btSoftBody::eAeroModel::V_TwoSided; btTransform trs; btQuaternion rot; btVector3 ra=Vector3Rand()*0.1; btVector3 rp=Vector3Rand()*15+btVector3(0,20,80); rot.setEuler(SIMD_PI/8+ra.x(),-SIMD_PI/7+ra.y(),ra.z()); trs.setIdentity(); trs.setOrigin(rp); trs.setRotation(rot); psb->transform(trs); psb->setTotalMass(0.1); psb->addForce(btVector3(0,2,0),0); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } pdemo->m_autocam=true; } static void Init_Aero2(SoftDemo* pdemo) { //TRACEDEMO const btScalar s=5; //psb->getWorldInfo()->m_gravity.setValue(0,0,0); const int segments=10; const int count=5; btVector3 pos(-s*segments, 0, 0); btScalar gap = 0.5; for(int i=0;i<count;++i) { btSoftBody* psb=btSoftBodyHelpers::CreatePatch( pdemo->m_softBodyWorldInfo,btVector3(-s,0,-s*3), btVector3(+s,0,-s*3), btVector3(-s,0,+s), btVector3(+s,0,+s), segments,segments*3, 1+2,true); psb->getCollisionShape()->setMargin(0.5); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.0004; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.kLF = 0.05; psb->m_cfg.kDG = 0.01; //psb->m_cfg.kLF = 0.004; //psb->m_cfg.kDG = 0.0003; psb->m_cfg.piterations = 2; psb->m_cfg.aeromodel = btSoftBody::eAeroModel::V_TwoSidedLiftDrag; psb->setWindVelocity(btVector3(4, -12.0, -25.0)); btTransform trs; btQuaternion rot; pos += btVector3(s*2 + gap, 0, 0); rot.setRotation(btVector3(1, 0, 0), btScalar(SIMD_PI/2)); trs.setIdentity(); trs.setOrigin(pos); trs.setRotation(rot); psb->transform(trs); psb->setTotalMass(2.0); //this could help performance in some cases btSoftBodyHelpers::ReoptimizeLinkOrder(psb); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } pdemo->m_autocam=true; } // // Friction // static void Init_Friction(SoftDemo* pdemo) { //TRACEDEMO const btScalar bs=2; const btScalar ts=bs+bs/4; for(int i=0,ni=20;i<ni;++i) { const btVector3 p(-ni*ts/2+i*ts,-10+bs,40); btSoftBody* psb=Ctor_SoftBox(pdemo,p,btVector3(bs,bs,bs)); psb->m_cfg.kDF = 0.1 * ((i+1)/(btScalar)ni); psb->addVelocity(btVector3(0,0,-10)); } } // // Pressure // static void Init_Pressure(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateEllipsoid(pdemo->m_softBodyWorldInfo,btVector3(35,25,0), btVector3(1,1,1)*3, 512); psb->m_materials[0]->m_kLST = 0.1; psb->m_cfg.kDF = 1; psb->m_cfg.kDP = 0.001; // fun factor... psb->m_cfg.kPR = 2500; psb->setTotalMass(30,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); Ctor_BigPlate(pdemo); Ctor_LinearStair(pdemo,btVector3(0,0,0),btVector3(2,1,5),0,10); pdemo->m_autocam=true; } // // Volume conservation // static void Init_Volume(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateEllipsoid(pdemo->m_softBodyWorldInfo,btVector3(35,25,0), btVector3(1,1,1)*3, 512); psb->m_materials[0]->m_kLST = 0.45; psb->m_cfg.kVC = 20; psb->setTotalMass(50,true); psb->setPose(true,false); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); Ctor_BigPlate(pdemo); Ctor_LinearStair(pdemo,btVector3(0,0,0),btVector3(2,1,5),0,10); pdemo->m_autocam=true; } // // Stick+Bending+Rb's // static void Init_Sticks(SoftDemo* pdemo) { //TRACEDEMO const int n=16; const int sg=4; const btScalar sz=5; const btScalar hg=4; const btScalar in=1/(btScalar)(n-1); for(int y=0;y<n;++y) { for(int x=0;x<n;++x) { const btVector3 org(-sz+sz*2*x*in, -10, -sz+sz*2*y*in); btSoftBody* psb=btSoftBodyHelpers::CreateRope( pdemo->m_softBodyWorldInfo, org, org+btVector3(hg*0.001,hg,0), sg, 1); psb->m_cfg.kDP = 0.005; psb->m_cfg.kCHR = 0.1; for(int i=0;i<3;++i) { psb->generateBendingConstraints(2+i); } psb->setMass(1,0); psb->setTotalMass(0.01); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } } Ctor_BigBall(pdemo); } // // Bending // static void Init_Bending(SoftDemo* pdemo) { //TRACEDEMO const btScalar s=4; const btVector3 x[]={ btVector3(-s,0,-s), btVector3(+s,0,-s), btVector3(+s,0,+s), btVector3(-s,0,+s)}; const btScalar m[]={ 0,0,0,1}; btSoftBody* psb=new btSoftBody(&pdemo->m_softBodyWorldInfo,4,x,m); psb->appendLink(0,1); psb->appendLink(1,2); psb->appendLink(2,3); psb->appendLink(3,0); psb->appendLink(0,2); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } // // 100kg cloth locked at corners, 10 falling 10kg rb's. // static void Init_Cloth(SoftDemo* pdemo) { //TRACEDEMO const btScalar s=8; btSoftBody* psb=btSoftBodyHelpers::CreatePatch( pdemo->m_softBodyWorldInfo,btVector3(-s,0,-s), btVector3(+s,0,-s), btVector3(-s,0,+s), btVector3(+s,0,+s), 31,31, // 31,31, 1+2+4+8,true); psb->getCollisionShape()->setMargin(0.5); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.4; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->setTotalMass(150); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); Ctor_RbUpStack(pdemo,10); pdemo->m_cutting=true; } // // 100kg Stanford's bunny // static void Init_Bunny(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVerticesBunny, &gIndicesBunny[0][0], BUNNY_NUM_TRIANGLES); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.5; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.piterations = 2; psb->m_cfg.kDF = 0.5; psb->randomizeConstraints(); psb->scale(btVector3(6,6,6)); psb->setTotalMass(100,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); pdemo->m_cutting=true; } // // 100kg Stanford's bunny with pose matching // static void Init_BunnyMatch(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo, gVerticesBunny, &gIndicesBunny[0][0], BUNNY_NUM_TRIANGLES); psb->m_cfg.kDF = 0.5; psb->m_cfg.kMT = 0.05; psb->m_cfg.piterations = 5; psb->randomizeConstraints(); psb->scale(btVector3(6,6,6)); psb->setTotalMass(100,true); psb->setPose(false,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } // // 50Kg Torus // static void Init_Torus(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh( pdemo->m_softBodyWorldInfo, gVertices, &gIndices[0][0], NUM_TRIANGLES); psb->generateBendingConstraints(2); psb->m_cfg.piterations=2; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(SIMD_PI/2,0,0); psb->transform(btTransform(m,btVector3(0,4,0))); psb->scale(btVector3(2,2,2)); psb->setTotalMass(50,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); pdemo->m_cutting=true; } // // 50Kg Torus with pose matching // static void Init_TorusMatch(SoftDemo* pdemo) { //TRACEDEMO btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo, gVertices, &gIndices[0][0], NUM_TRIANGLES); psb->m_materials[0]->m_kLST = 0.1; psb->m_cfg.kMT = 0.05; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(SIMD_PI/2,0,0); psb->transform(btTransform(m,btVector3(0,4,0))); psb->scale(btVector3(2,2,2)); psb->setTotalMass(50,true); psb->setPose(false,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); } // // Cutting1 // static void Init_Cutting1(SoftDemo* pdemo) { const btScalar s=6; const btScalar h=2; const int r=16; const btVector3 p[]={ btVector3(+s,h,-s), btVector3(-s,h,-s), btVector3(+s,h,+s), btVector3(-s,h,+s)}; btSoftBody* psb=btSoftBodyHelpers::CreatePatch(pdemo->m_softBodyWorldInfo,p[0],p[1],p[2],p[3],r,r,1+2+4+8,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); psb->m_cfg.piterations=1; pdemo->m_cutting=true; } // // Clusters // // static void Ctor_Gear(SoftDemo* pdemo,const btVector3& pos,btScalar speed) { btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin(pos); btCompoundShape* shape=new btCompoundShape(); #if 1 shape->addChildShape(btTransform(btQuaternion(0,0,0)),new btBoxShape(btVector3(5,1,6))); shape->addChildShape(btTransform(btQuaternion(0,0,SIMD_HALF_PI)),new btBoxShape(btVector3(5,1,6))); #else shape->addChildShape(btTransform(btQuaternion(0,0,0)),new btCylinderShapeZ(btVector3(5,1,7))); shape->addChildShape(btTransform(btQuaternion(0,0,SIMD_HALF_PI)),new btBoxShape(btVector3(4,1,8))); #endif btRigidBody* body=pdemo->createRigidBody(10,startTransform,shape); body->setFriction(1); btDynamicsWorld* world=pdemo->getDynamicsWorld(); btHingeConstraint* hinge=new btHingeConstraint(*body,btTransform::getIdentity()); if(speed!=0) hinge->enableAngularMotor(true,speed,3); world->addConstraint(hinge); } // static btSoftBody* Ctor_ClusterBunny(SoftDemo* pdemo,const btVector3& x,const btVector3& a) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVerticesBunny,&gIndicesBunny[0][0],BUNNY_NUM_TRIANGLES); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 1; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.piterations = 2; psb->m_cfg.kDF = 1; psb->m_cfg.collisions = btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(a.x(),a.y(),a.z()); psb->transform(btTransform(m,x)); psb->scale(btVector3(8,8,8)); psb->setTotalMass(150,true); psb->generateClusters(1); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } // static btSoftBody* Ctor_ClusterTorus(SoftDemo* pdemo,const btVector3& x,const btVector3& a,const btVector3& s=btVector3(2,2,2)) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVertices,&gIndices[0][0],NUM_TRIANGLES); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 1; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.piterations = 2; psb->m_cfg.collisions = btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS; psb->randomizeConstraints(); psb->scale(s); psb->rotate(btQuaternion(a[0],a[1],a[2])); psb->translate(x); psb->setTotalMass(50,true); psb->generateClusters(64); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } // static struct MotorControl : btSoftBody::AJoint::IControl { MotorControl() { goal=0; maxtorque=0; } btScalar Speed(btSoftBody::AJoint*,btScalar current) { return(current+btMin(maxtorque,btMax(-maxtorque,goal-current))); } btScalar goal; btScalar maxtorque; } motorcontrol; // struct SteerControl : btSoftBody::AJoint::IControl { SteerControl(btScalar s) { angle=0; sign=s; } void Prepare(btSoftBody::AJoint* joint) { joint->m_refs[0][0]=btCos(angle*sign); joint->m_refs[0][2]=btSin(angle*sign); } btScalar Speed(btSoftBody::AJoint* joint,btScalar current) { return(motorcontrol.Speed(joint,current)); } btScalar angle; btScalar sign; }; static SteerControl steercontrol_f(+1); static SteerControl steercontrol_r(-1); // static void Init_ClusterDeform(SoftDemo* pdemo) { btSoftBody* psb=Ctor_ClusterTorus(pdemo,btVector3(0,0,0),btVector3(SIMD_PI/2,0,SIMD_HALF_PI)); psb->generateClusters(8); psb->m_cfg.kDF=1; } // static void Init_ClusterCollide1(SoftDemo* pdemo) { const btScalar s=8; btSoftBody* psb=btSoftBodyHelpers::CreatePatch( pdemo->m_softBodyWorldInfo,btVector3(-s,0,-s), btVector3(+s,0,-s), btVector3(-s,0,+s), btVector3(+s,0,+s), 17,17,//9,9,//31,31, 1+2+4+8, true); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_kLST = 0.4; pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->m_cfg.kDF = 1; psb->m_cfg.kSRHR_CL = 1; psb->m_cfg.kSR_SPLT_CL = 0; psb->m_cfg.collisions = btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS; psb->generateBendingConstraints(2,pm); psb->getCollisionShape()->setMargin(0.05); psb->setTotalMass(50); ///pass zero in generateClusters to create cluster for each tetrahedron or triangle psb->generateClusters(0); //psb->generateClusters(64); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); Ctor_RbUpStack(pdemo,10); } // static void Init_ClusterCollide2(SoftDemo* pdemo) { struct Functor { static btSoftBody* Create(SoftDemo* pdemo,const btVector3& x,const btVector3& a) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTriMesh(pdemo->m_softBodyWorldInfo,gVertices, &gIndices[0][0], NUM_TRIANGLES); btSoftBody::Material* pm=psb->appendMaterial(); pm->m_flags -= btSoftBody::fMaterial::DebugDraw; psb->generateBendingConstraints(2,pm); psb->m_cfg.piterations=2; psb->m_cfg.kDF =1; psb->m_cfg.kSSHR_CL =1; psb->m_cfg.kSS_SPLT_CL =0; psb->m_cfg.kSKHR_CL =0.1f; psb->m_cfg.kSK_SPLT_CL =1; psb->m_cfg.collisions= btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS; psb->randomizeConstraints(); btMatrix3x3 m; m.setEulerZYX(a.x(),a.y(),a.z()); psb->transform(btTransform(m,x)); psb->scale(btVector3(2,2,2)); psb->setTotalMass(50,true); psb->generateClusters(16); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } }; for(int i=0;i<3;++i) { Functor::Create(pdemo,btVector3(3*i,2,0),btVector3(SIMD_PI/2*(1-(i&1)),SIMD_PI/2*(i&1),0)); } } // static void Init_ClusterSocket(SoftDemo* pdemo) { btSoftBody* psb=Ctor_ClusterTorus(pdemo,btVector3(0,0,0),btVector3(SIMD_PI/2,0,SIMD_HALF_PI)); btRigidBody* prb=Ctor_BigPlate(pdemo,50,8); psb->m_cfg.kDF=1; btSoftBody::LJoint::Specs lj; lj.position = btVector3(0,5,0); psb->appendLinearJoint(lj,prb); } // static void Init_ClusterHinge(SoftDemo* pdemo) { btSoftBody* psb=Ctor_ClusterTorus(pdemo,btVector3(0,0,0),btVector3(SIMD_PI/2,0,SIMD_HALF_PI)); btRigidBody* prb=Ctor_BigPlate(pdemo,50,8); psb->m_cfg.kDF=1; btSoftBody::AJoint::Specs aj; aj.axis = btVector3(0,0,1); psb->appendAngularJoint(aj,prb); } // static void Init_ClusterCombine(SoftDemo* pdemo) { const btVector3 sz(2,4,2); btSoftBody* psb0=Ctor_ClusterTorus(pdemo,btVector3(0,8,0),btVector3(SIMD_PI/2,0,SIMD_HALF_PI),sz); btSoftBody* psb1=Ctor_ClusterTorus(pdemo,btVector3(0,8,10),btVector3(SIMD_PI/2,0,SIMD_HALF_PI),sz); btSoftBody* psbs[]={psb0,psb1}; for(int j=0;j<2;++j) { psbs[j]->m_cfg.kDF=1; psbs[j]->m_cfg.kDP=0; psbs[j]->m_cfg.piterations=1; psbs[j]->m_clusters[0]->m_matching = 0.05; psbs[j]->m_clusters[0]->m_ndamping = 0.05; } btSoftBody::AJoint::Specs aj; aj.axis = btVector3(0,0,1); aj.icontrol = &motorcontrol; psb0->appendAngularJoint(aj,psb1); btSoftBody::LJoint::Specs lj; lj.position = btVector3(0,8,5); psb0->appendLinearJoint(lj,psb1); } // static void Init_ClusterCar(SoftDemo* pdemo) { // pdemo->setAzi(180); const btVector3 origin(100,80,0); const btQuaternion orientation(-SIMD_PI/2,0,0); const btScalar widthf=8; const btScalar widthr=9; const btScalar length=8; const btScalar height=4; const btVector3 wheels[]= { btVector3(+widthf,-height,+length), // Front left btVector3(-widthf,-height,+length), // Front right btVector3(+widthr,-height,-length), // Rear left btVector3(-widthr,-height,-length), // Rear right }; btSoftBody* pa=Ctor_ClusterBunny(pdemo,btVector3(0,0,0),btVector3(0,0,0)); btSoftBody* pfl=Ctor_ClusterTorus(pdemo,wheels[0],btVector3(0,0,SIMD_HALF_PI),btVector3(2,4,2)); btSoftBody* pfr=Ctor_ClusterTorus(pdemo,wheels[1],btVector3(0,0,SIMD_HALF_PI),btVector3(2,4,2)); btSoftBody* prl=Ctor_ClusterTorus(pdemo,wheels[2],btVector3(0,0,SIMD_HALF_PI),btVector3(2,5,2)); btSoftBody* prr=Ctor_ClusterTorus(pdemo,wheels[3],btVector3(0,0,SIMD_HALF_PI),btVector3(2,5,2)); pfl->m_cfg.kDF = pfr->m_cfg.kDF = prl->m_cfg.kDF = prr->m_cfg.kDF = 1; btSoftBody::LJoint::Specs lspecs; lspecs.cfm = 1; lspecs.erp = 1; lspecs.position = btVector3(0,0,0); lspecs.position=wheels[0];pa->appendLinearJoint(lspecs,pfl); lspecs.position=wheels[1];pa->appendLinearJoint(lspecs,pfr); lspecs.position=wheels[2];pa->appendLinearJoint(lspecs,prl); lspecs.position=wheels[3];pa->appendLinearJoint(lspecs,prr); btSoftBody::AJoint::Specs aspecs; aspecs.cfm = 1; aspecs.erp = 1; aspecs.axis = btVector3(1,0,0); aspecs.icontrol = &steercontrol_f; pa->appendAngularJoint(aspecs,pfl); pa->appendAngularJoint(aspecs,pfr); aspecs.icontrol = &motorcontrol; pa->appendAngularJoint(aspecs,prl); pa->appendAngularJoint(aspecs,prr); pa->rotate(orientation); pfl->rotate(orientation); pfr->rotate(orientation); prl->rotate(orientation); prr->rotate(orientation); pa->translate(origin); pfl->translate(origin); pfr->translate(origin); prl->translate(origin); prr->translate(origin); pfl->m_cfg.piterations = pfr->m_cfg.piterations = prl->m_cfg.piterations = prr->m_cfg.piterations = 1; pfl->m_clusters[0]->m_matching = pfr->m_clusters[0]->m_matching = prl->m_clusters[0]->m_matching = prr->m_clusters[0]->m_matching = 0.05; pfl->m_clusters[0]->m_ndamping = pfr->m_clusters[0]->m_ndamping = prl->m_clusters[0]->m_ndamping = prr->m_clusters[0]->m_ndamping = 0.05; Ctor_LinearStair(pdemo,btVector3(0,-8,0),btVector3(3,2,40),0,20); Ctor_RbUpStack(pdemo,50); pdemo->m_autocam=true; } // static void Init_ClusterRobot(SoftDemo* pdemo) { struct Functor { static btSoftBody* CreateBall(SoftDemo* pdemo,const btVector3& pos) { btSoftBody* psb=btSoftBodyHelpers::CreateEllipsoid(pdemo->m_softBodyWorldInfo,pos,btVector3(1,1,1)*3,512); psb->m_materials[0]->m_kLST = 0.45; psb->m_cfg.kVC = 20; psb->setTotalMass(50,true); psb->setPose(true,false); psb->generateClusters(1); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); return(psb); } }; const btVector3 base=btVector3(0,25,8); btSoftBody* psb0=Functor::CreateBall(pdemo,base+btVector3(-8,0,0)); btSoftBody* psb1=Functor::CreateBall(pdemo,base+btVector3(+8,0,0)); btSoftBody* psb2=Functor::CreateBall(pdemo,base+btVector3(0,0,+8*btSqrt(2))); const btVector3 ctr=(psb0->clusterCom(0)+psb1->clusterCom(0)+psb2->clusterCom(0))/3; btCylinderShape* pshp=new btCylinderShape(btVector3(8,1,8)); btRigidBody* prb=pdemo->createRigidBody(50,btTransform(btQuaternion(0,0,0),ctr+btVector3(0,5,0)),pshp); btSoftBody::LJoint::Specs ls; ls.erp=0.5f; ls.position=psb0->clusterCom(0);psb0->appendLinearJoint(ls,prb); ls.position=psb1->clusterCom(0);psb1->appendLinearJoint(ls,prb); ls.position=psb2->clusterCom(0);psb2->appendLinearJoint(ls,prb); btBoxShape* pbox=new btBoxShape(btVector3(20,1,40)); btRigidBody* pgrn=pdemo->createRigidBody(0,btTransform(btQuaternion(0,-SIMD_HALF_PI/2,0),btVector3(0,0,0)),pbox); pdemo->m_autocam=true; } // static void Init_ClusterStackSoft(SoftDemo* pdemo) { for(int i=0;i<10;++i) { btSoftBody* psb=Ctor_ClusterTorus(pdemo,btVector3(0,-9+8.25*i,0),btVector3(0,0,0)); psb->m_cfg.kDF=1; } } // static void Init_ClusterStackMixed(SoftDemo* pdemo) { for(int i=0;i<10;++i) { if((i+1)&1) { Ctor_BigPlate(pdemo,50,-9+4.25*i); } else { btSoftBody* psb=Ctor_ClusterTorus(pdemo,btVector3(0,-9+4.25*i,0),btVector3(0,0,0)); psb->m_cfg.kDF=1; } } } // // TetraBunny // static void Init_TetraBunny(SoftDemo* pdemo) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTetGenData(pdemo->m_softBodyWorldInfo, TetraBunny::getElements(), 0, TetraBunny::getNodes(), false,true,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); psb->rotate(btQuaternion(SIMD_PI/2,0,0)); psb->setVolumeMass(150); psb->m_cfg.piterations=2; //psb->m_cfg.piterations=1; pdemo->m_cutting=false; //psb->getCollisionShape()->setMargin(0.01); psb->m_cfg.collisions = btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS //+ btSoftBody::fCollision::CL_SELF ; ///pass zero in generateClusters to create cluster for each tetrahedron or triangle psb->generateClusters(0); //psb->m_materials[0]->m_kLST=.2; psb->m_cfg.kDF = 10. ; } // // TetraCube // static void Init_TetraCube(SoftDemo* pdemo) { btSoftBody* psb=btSoftBodyHelpers::CreateFromTetGenData(pdemo->m_softBodyWorldInfo, TetraCube::getElements(), 0, TetraCube::getNodes(), false,true,true); pdemo->getSoftDynamicsWorld()->addSoftBody(psb); psb->scale(btVector3(4,4,4)); psb->translate(btVector3(0,5,0)); psb->setVolumeMass(300); ///fix one vertex //psb->setMass(0,0); //psb->setMass(10,0); //psb->setMass(20,0); psb->m_cfg.piterations=1; //psb->generateClusters(128); psb->generateClusters(16); //psb->getCollisionShape()->setMargin(0.5); psb->getCollisionShape()->setMargin(0.01); psb->m_cfg.collisions = btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS //+ btSoftBody::fCollision::CL_SELF ; psb->m_materials[0]->m_kLST=0.8; pdemo->m_cutting=false; } /* Init */ void (*demofncs[])(SoftDemo*)= { Init_Cloth, Init_Pressure, Init_Volume, Init_Ropes, Init_RopeAttach, Init_ClothAttach, Init_Sticks, Init_CapsuleCollision, Init_Collide, Init_Collide2, Init_Collide3, Init_Impact, Init_Aero, Init_Aero2, Init_Friction, Init_Torus, Init_TorusMatch, Init_Bunny, Init_BunnyMatch, Init_Cutting1, Init_ClusterDeform, Init_ClusterCollide1, Init_ClusterCollide2, Init_ClusterSocket, Init_ClusterHinge, Init_ClusterCombine, Init_ClusterCar, Init_ClusterRobot, Init_ClusterStackSoft, Init_ClusterStackMixed, Init_TetraCube, Init_TetraBunny, }; #if 0 void SoftDemo::clientResetScene() { m_azi = 0; m_cameraDistance = 30.f; m_cameraTargetPosition.setValue(0,0,0); /* Clean up */ for(int i=m_dynamicsWorld->getNumCollisionObjects()-1;i>=0;i--) { btCollisionObject* obj=m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body=btRigidBody::upcast(obj); if(body&&body->getMotionState()) { delete body->getMotionState(); } while(m_dynamicsWorld->getNumConstraints()) { btTypedConstraint* pc=m_dynamicsWorld->getConstraint(0); m_dynamicsWorld->removeConstraint(pc); delete pc; } btSoftBody* softBody = btSoftBody::upcast(obj); if (softBody) { getSoftDynamicsWorld()->removeSoftBody(softBody); } else { btRigidBody* body = btRigidBody::upcast(obj); if (body) m_dynamicsWorld->removeRigidBody(body); else m_dynamicsWorld->removeCollisionObject(obj); } delete obj; } } #if 0 void SoftDemo::clientMoveAndDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); float ms = getDeltaTimeMicroseconds(); float dt = ms / 1000000.f;//1.0/60.; if (m_dynamicsWorld) { if (sDemoMode) { static float demoCounter = DEMO_MODE_TIMEOUT; demoCounter-= dt; if (demoCounter<0) { demoCounter=DEMO_MODE_TIMEOUT; current_demo++; current_demo=current_demo%(sizeof(demofncs)/sizeof(demofncs[0])); clientResetScene(); } } //#define FIXED_STEP #ifdef FIXED_STEP m_dynamicsWorld->stepSimulation(dt=1.0f/60.f,0); #else //during idle mode, just run 1 simulation step maximum, otherwise 4 at max // int maxSimSubSteps = m_idle ? 1 : 4; //if (m_idle) // dt = 1.0/420.f; int numSimSteps; numSimSteps = m_dynamicsWorld->stepSimulation(dt); //numSimSteps = m_dynamicsWorld->stepSimulation(dt,10,1./240.f); #ifdef VERBOSE_TIMESTEPPING_CONSOLEOUTPUT if (!numSimSteps) printf("Interpolated transforms\n"); else { if (numSimSteps > maxSimSubSteps) { //detect dropping frames printf("Dropped (%i) simulation steps out of %i\n",numSimSteps - maxSimSubSteps,numSimSteps); } else { printf("Simulated (%i) steps\n",numSimSteps); } } #endif //VERBOSE_TIMESTEPPING_CONSOLEOUTPUT #endif #ifdef USE_AMD_OPENCL if (g_openCLSIMDSolver) g_openCLSIMDSolver->copyBackToSoftBodies(); #endif //USE_AMD_OPENCL if(m_drag) { m_node->m_v*=0; } m_softBodyWorldInfo.m_sparsesdf.GarbageCollect(); //optional but useful: debug drawing } #ifdef USE_QUICKPROF btProfiler::beginBlock("render"); #endif //USE_QUICKPROF renderme(); //render the graphics objects, with center of mass shift updateCamera(); #ifdef USE_QUICKPROF btProfiler::endBlock("render"); #endif glFlush(); //some additional debugging info #ifdef PRINT_CONTACT_STATISTICS printf("num manifolds: %i\n",gNumManifold); printf("num gOverlappingPairs: %i\n",gOverlappingPairs); #endif //PRINT_CONTACT_STATISTICS swapBuffers(); } #endif #if 0 void SoftDemo::renderme() { btIDebugDraw* idraw=m_dynamicsWorld->getDebugDrawer(); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); m_dynamicsWorld->debugDrawWorld(); //int debugMode = m_dynamicsWorld->getDebugDrawer()? m_dynamicsWorld->getDebugDrawer()->getDebugMode() : -1; btSoftRigidDynamicsWorld* softWorld = (btSoftRigidDynamicsWorld*)m_dynamicsWorld; //btIDebugDraw* sdraw = softWorld ->getDebugDrawer(); for ( int i=0;i<softWorld->getSoftBodyArray().size();i++) { btSoftBody* psb=(btSoftBody*)softWorld->getSoftBodyArray()[i]; if (softWorld->getDebugDrawer() && !(softWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe))) { btSoftBodyHelpers::DrawFrame(psb,softWorld->getDebugDrawer()); btSoftBodyHelpers::Draw(psb,softWorld->getDebugDrawer(),softWorld->getDrawFlags()); } } /* Bodies */ btVector3 ps(0,0,0); int nps=0; btSoftBodyArray& sbs=getSoftDynamicsWorld()->getSoftBodyArray(); for(int ib=0;ib<sbs.size();++ib) { btSoftBody* psb=sbs[ib]; nps+=psb->m_nodes.size(); for(int i=0;i<psb->m_nodes.size();++i) { ps+=psb->m_nodes[i].m_x; } } ps/=nps; if(m_autocam) m_cameraTargetPosition+=(ps-m_cameraTargetPosition)*0.05; /* Anm */ if(!isIdle()) m_animtime=m_clock.getTimeMilliseconds()/1000.f; /* Ray cast */ if(m_raycast) { /* Prepare rays */ const int res=64; const btScalar fres=res-1; const btScalar size=8; const btScalar dist=10; btTransform trs; trs.setOrigin(ps); btScalar rayLength = 1000.f; const btScalar angle=m_animtime*0.2; trs.setRotation(btQuaternion(angle,SIMD_PI/4,0)); btVector3 dir=trs.getBasis()*btVector3(0,-1,0); trs.setOrigin(ps-dir*dist); btAlignedObjectArray<btVector3> origins; btAlignedObjectArray<btScalar> fractions; origins.resize(res*res); fractions.resize(res*res,1.f); for(int y=0;y<res;++y) { for(int x=0;x<res;++x) { const int idx=y*res+x; origins[idx]=trs*btVector3(-size+size*2*x/fres,dist,-size+size*2*y/fres); } } /* Cast rays */ { m_clock.reset(); if (sbs.size()) { btVector3* org=&origins[0]; btScalar* fraction=&fractions[0]; btSoftBody** psbs=&sbs[0]; btSoftBody::sRayCast results; for(int i=0,ni=origins.size(),nb=sbs.size();i<ni;++i) { for(int ib=0;ib<nb;++ib) { btVector3 rayFrom = *org; btVector3 rayTo = rayFrom+dir*rayLength; if(psbs[ib]->rayTest(rayFrom,rayTo,results)) { *fraction=results.fraction; } } ++org;++fraction; } long ms=btMax<long>(m_clock.getTimeMilliseconds(),1); long rayperseconds=(1000*(origins.size()*sbs.size()))/ms; printf("%d ms (%d rays/s)\r\n",int(ms),int(rayperseconds)); } } /* Draw rays */ const btVector3 c[]={ origins[0], origins[res-1], origins[res*(res-1)], origins[res*(res-1)+res-1]}; idraw->drawLine(c[0],c[1],btVector3(0,0,0)); idraw->drawLine(c[1],c[3],btVector3(0,0,0)); idraw->drawLine(c[3],c[2],btVector3(0,0,0)); idraw->drawLine(c[2],c[0],btVector3(0,0,0)); for(int i=0,ni=origins.size();i<ni;++i) { const btScalar fraction=fractions[i]; const btVector3& org=origins[i]; if(fraction<1.f) { idraw->drawLine(org,org+dir*rayLength*fraction,btVector3(1,0,0)); } else { idraw->drawLine(org,org-dir*rayLength*0.1,btVector3(0,0,0)); } } #undef RES } /* Water level */ static const btVector3 axis[]={btVector3(1,0,0), btVector3(0,1,0), btVector3(0,0,1)}; if(m_softBodyWorldInfo.water_density>0) { const btVector3 c= btVector3((btScalar)0.25,(btScalar)0.25,1); const btScalar a= (btScalar)0.5; const btVector3 n= m_softBodyWorldInfo.water_normal; const btVector3 o= -n*m_softBodyWorldInfo.water_offset; const btVector3 x= btCross(n,axis[n.minAxis()]).normalized(); const btVector3 y= btCross(x,n).normalized(); const btScalar s= 25; idraw->drawTriangle(o-x*s-y*s,o+x*s-y*s,o+x*s+y*s,c,a); idraw->drawTriangle(o-x*s-y*s,o+x*s+y*s,o-x*s+y*s,c,a); } // int lineWidth=280; int xStart = m_glutScreenWidth - lineWidth; int yStart = 20; if((getDebugMode() & btIDebugDraw::DBG_NoHelpText)==0) { setOrthographicProjection(); glDisable(GL_LIGHTING); glColor3f(0, 0, 0); char buf[124]; glRasterPos3f(xStart, yStart, 0); if (sDemoMode) { sprintf(buf,"d to toggle demo mode (on)"); } else { sprintf(buf,"d to toggle demo mode (off)"); } GLDebugDrawString(xStart,20,buf); glRasterPos3f(xStart, yStart, 0); sprintf(buf,"] for next demo (%d)",current_demo); yStart+=20; GLDebugDrawString(xStart,yStart,buf); glRasterPos3f(xStart, yStart, 0); sprintf(buf,"c to visualize clusters"); yStart+=20; GLDebugDrawString(xStart,yStart,buf); glRasterPos3f(xStart, yStart, 0); sprintf(buf,"; to toggle camera mode"); yStart+=20; GLDebugDrawString(xStart,yStart,buf); glRasterPos3f(xStart, yStart, 0); sprintf(buf,"n,m,l,k for power and steering"); yStart+=20; GLDebugDrawString(xStart,yStart,buf); resetPerspectiveProjection(); glEnable(GL_LIGHTING); } DemoApplication::renderme(); } #endif #endif void SoftDemo::setDrawClusters(bool drawClusters) { if (drawClusters) { getSoftDynamicsWorld()->setDrawFlags(getSoftDynamicsWorld()->getDrawFlags()|fDrawFlags::Clusters); } else { getSoftDynamicsWorld()->setDrawFlags(getSoftDynamicsWorld()->getDrawFlags()& (~fDrawFlags::Clusters)); } } #if 0 void SoftDemo::keyboardCallback(unsigned char key, int x, int y) { switch(key) { case 'd': sDemoMode = !sDemoMode; break; case 'n': motorcontrol.maxtorque=10;motorcontrol.goal+=1;break; case 'm': motorcontrol.maxtorque=10;motorcontrol.goal-=1;break; case 'l': steercontrol_f.angle+=0.1;steercontrol_r.angle+=0.1;break; case 'k': steercontrol_f.angle-=0.1;steercontrol_r.angle-=0.1;break; case ']': ++current_demo;clientResetScene();break; case '[': --current_demo;clientResetScene();break; case ',': m_raycast=!m_raycast;break; case ';': m_autocam=!m_autocam;break; case 'c': getSoftDynamicsWorld()->setDrawFlags(getSoftDynamicsWorld()->getDrawFlags()^fDrawFlags::Clusters);break; case '`': { btSoftBodyArray& sbs=getSoftDynamicsWorld()->getSoftBodyArray(); for(int ib=0;ib<sbs.size();++ib) { btSoftBody* psb=sbs[ib]; psb->staticSolve(128); } } break; default: DemoApplication::keyboardCallback(key,x,y); } } #endif // void SoftDemo::mouseMotionFunc(int x,int y) { if(m_node&&(m_results.fraction<1.f)) { if(!m_drag) { #define SQ(_x_) (_x_)*(_x_) if((SQ(x-m_lastmousepos[0])+SQ(y-m_lastmousepos[1]))>6) { m_drag=true; } #undef SQ } if(m_drag) { m_lastmousepos[0] = x; m_lastmousepos[1] = y; } } } #if 0 // void SoftDemo::mouseFunc(int button, int state, int x, int y) { if(button==0) { switch(state) { case 0: { m_results.fraction=1.f; DemoApplication::mouseFunc(button,state,x,y); if(!m_pickConstraint) { const btVector3 rayFrom=m_cameraPosition; const btVector3 rayTo=getRayTo(x,y); const btVector3 rayDir=(rayTo-rayFrom).normalized(); btSoftBodyArray& sbs=getSoftDynamicsWorld()->getSoftBodyArray(); for(int ib=0;ib<sbs.size();++ib) { btSoftBody* psb=sbs[ib]; btSoftBody::sRayCast res; if(psb->rayTest(rayFrom,rayTo,res)) { m_results=res; } } if(m_results.fraction<1.f) { m_impact = rayFrom+(rayTo-rayFrom)*m_results.fraction; m_drag = m_cutting ? false : true; m_lastmousepos[0] = x; m_lastmousepos[1] = y; m_node = 0; switch(m_results.feature) { case btSoftBody::eFeature::Tetra: { btSoftBody::Tetra& tet=m_results.body->m_tetras[m_results.index]; m_node=tet.m_n[0]; for(int i=1;i<4;++i) { if( (m_node->m_x-m_impact).length2()> (tet.m_n[i]->m_x-m_impact).length2()) { m_node=tet.m_n[i]; } } break; } case btSoftBody::eFeature::Face: { btSoftBody::Face& f=m_results.body->m_faces[m_results.index]; m_node=f.m_n[0]; for(int i=1;i<3;++i) { if( (m_node->m_x-m_impact).length2()> (f.m_n[i]->m_x-m_impact).length2()) { m_node=f.m_n[i]; } } } break; } if(m_node) m_goal=m_node->m_x; return; } } } break; case 1: if((!m_drag)&&m_cutting&&(m_results.fraction<1.f)) { ImplicitSphere isphere(m_impact,1); printf("Mass before: %f\r\n",m_results.body->getTotalMass()); m_results.body->refine(&isphere,0.0001,true); printf("Mass after: %f\r\n",m_results.body->getTotalMass()); } m_results.fraction=1.f; m_drag=false; DemoApplication::mouseFunc(button,state,x,y); break; } } else { DemoApplication::mouseFunc(button,state,x,y); } } #endif void SoftDemo::initPhysics() { ///create concave ground mesh m_guiHelper->setUpAxis(1); // m_azi = 0; //reset and disable motorcontrol at the start motorcontrol.goal = 0; motorcontrol.maxtorque = 0; btCollisionShape* groundShape = 0; { int i; int j; const int NUM_VERTS_X = 30; const int NUM_VERTS_Y = 30; const int totalVerts = NUM_VERTS_X*NUM_VERTS_Y; const int totalTriangles = 2*(NUM_VERTS_X-1)*(NUM_VERTS_Y-1); gGroundVertices = new btVector3[totalVerts]; gGroundIndices = new int[totalTriangles*3]; btScalar offset(-50); for ( i=0;i<NUM_VERTS_X;i++) { for (j=0;j<NUM_VERTS_Y;j++) { gGroundVertices[i+j*NUM_VERTS_X].setValue((i-NUM_VERTS_X*0.5f)*TRIANGLE_SIZE, //0.f, waveheight*sinf((float)i)*cosf((float)j+offset), (j-NUM_VERTS_Y*0.5f)*TRIANGLE_SIZE); } } int vertStride = sizeof(btVector3); int indexStride = 3*sizeof(int); int index=0; for ( i=0;i<NUM_VERTS_X-1;i++) { for (int j=0;j<NUM_VERTS_Y-1;j++) { gGroundIndices[index++] = j*NUM_VERTS_X+i; gGroundIndices[index++] = j*NUM_VERTS_X+i+1; gGroundIndices[index++] = (j+1)*NUM_VERTS_X+i+1; gGroundIndices[index++] = j*NUM_VERTS_X+i; gGroundIndices[index++] = (j+1)*NUM_VERTS_X+i+1; gGroundIndices[index++] = (j+1)*NUM_VERTS_X+i; } } btTriangleIndexVertexArray* indexVertexArrays = new btTriangleIndexVertexArray(totalTriangles, gGroundIndices, indexStride, totalVerts,(btScalar*) &gGroundVertices[0].x(),vertStride); bool useQuantizedAabbCompression = true; groundShape = new btBvhTriangleMeshShape(indexVertexArrays,useQuantizedAabbCompression); groundShape->setMargin(0.5); } m_collisionShapes.push_back(groundShape); btCollisionShape* groundBox = new btBoxShape (btVector3(100,CUBE_HALF_EXTENTS,100)); m_collisionShapes.push_back(groundBox); btCompoundShape* cylinderCompound = new btCompoundShape; btCollisionShape* cylinderShape = new btCylinderShape (btVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS)); btTransform localTransform; localTransform.setIdentity(); cylinderCompound->addChildShape(localTransform,cylinderShape); btQuaternion orn(btVector3(0,1,0),SIMD_PI); localTransform.setRotation(orn); cylinderCompound->addChildShape(localTransform,cylinderShape); m_collisionShapes.push_back(cylinderCompound); m_dispatcher=0; ///register some softbody collision algorithms on top of the default btDefaultCollisionConfiguration m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_softBodyWorldInfo.m_dispatcher = m_dispatcher; //////////////////////////// ///Register softbody versus softbody collision algorithm ///Register softbody versus rigidbody collision algorithm //////////////////////////// btVector3 worldAabbMin(-1000,-1000,-1000); btVector3 worldAabbMax(1000,1000,1000); m_broadphase = new btAxisSweep3(worldAabbMin,worldAabbMax,maxProxies); m_softBodyWorldInfo.m_broadphase = m_broadphase; btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver(); m_solver = solver; btSoftBodySolver* softBodySolver = 0; #ifdef USE_AMD_OPENCL static bool once = true; if (once) { once=false; initCL(0,0); } if( g_openCLSIMDSolver ) delete g_openCLSIMDSolver; if( g_softBodyOutput ) delete g_softBodyOutput; if (1) { g_openCLSIMDSolver = new btOpenCLSoftBodySolverSIMDAware( g_cqCommandQue, g_cxMainContext); // g_openCLSIMDSolver = new btOpenCLSoftBodySolver( g_cqCommandQue, g_cxMainContext); g_openCLSIMDSolver->setCLFunctions(new CachingCLFunctions(g_cqCommandQue, g_cxMainContext)); } softBodySolver = g_openCLSIMDSolver; g_softBodyOutput = new btSoftBodySolverOutputCLtoCPU; #endif //USE_AMD_OPENCL btDiscreteDynamicsWorld* world = new btSoftRigidDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration,softBodySolver); m_dynamicsWorld = world; m_dynamicsWorld->setInternalTickCallback(pickingPreTickCallback,this,true); m_dynamicsWorld->getDispatchInfo().m_enableSPU = true; m_dynamicsWorld->setGravity(btVector3(0,-10,0)); m_softBodyWorldInfo.m_gravity.setValue(0,-10,0); m_guiHelper->createPhysicsDebugDrawer(world); // clientResetScene(); m_softBodyWorldInfo.m_sparsesdf.Initialize(); // clientResetScene(); //create ground object btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(0,-12,0)); btCollisionObject* newOb = new btCollisionObject(); newOb->setWorldTransform(tr); newOb->setInterpolationWorldTransform( tr); int lastDemo = (sizeof(demofncs)/sizeof(demofncs[0]))-1; if (current_demo<0) current_demo = lastDemo; if (current_demo > lastDemo) current_demo =0; if (current_demo>19) { newOb->setCollisionShape(m_collisionShapes[0]); } else { newOb->setCollisionShape(m_collisionShapes[1]); } m_dynamicsWorld->addCollisionObject(newOb); m_softBodyWorldInfo.m_sparsesdf.Reset(); motorcontrol.goal = 0; motorcontrol.maxtorque = 0; m_softBodyWorldInfo.air_density = (btScalar)1.2; m_softBodyWorldInfo.water_density = 0; m_softBodyWorldInfo.water_offset = 0; m_softBodyWorldInfo.water_normal = btVector3(0,0,0); m_softBodyWorldInfo.m_gravity.setValue(0,-10,0); m_autocam = false; m_raycast = false; m_cutting = false; m_results.fraction = 1.f; demofncs[current_demo](this); m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } void SoftDemo::exitPhysics() { //cleanup in the reverse order of creation/initialization //remove the rigidbodies from the dynamics world and delete them int i; for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) { btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } m_dynamicsWorld->removeCollisionObject( obj ); delete obj; } //delete collision shapes for (int j=0;j<m_collisionShapes.size();j++) { btCollisionShape* shape = m_collisionShapes[j]; m_collisionShapes[j] = 0; delete shape; } //delete dynamics world delete m_dynamicsWorld; m_dynamicsWorld = 0; //delete solver delete m_solver; //delete broadphase delete m_broadphase; //delete dispatcher delete m_dispatcher; delete m_collisionConfiguration; } class CommonExampleInterface* SoftDemoCreateFunc(struct CommonExampleOptions& options) { current_demo = options.m_option; return new SoftDemo(options.m_guiHelper); }
1
0.870672
1
0.870672
game-dev
MEDIA
0.810341
game-dev
0.833115
1
0.833115
fetus-hina/stat.ink
3,779
components/ability/effect/Base.php
<?php /** * @copyright Copyright (C) 2016-2025 AIZAWA Hina * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT * @author AIZAWA Hina <hina@fetus.jp> */ namespace app\components\ability\effect; use yii\base\Component; use function ceil; use function pow; abstract class Base extends Component { public const SPECIAL_DURATION_40PCT = 75; public const SPECIAL_DURATION_60PCT = 50; public $battle; public $version; private $countCache = []; abstract public function getCalculatorVersion(); abstract public function getAttackPct(); abstract public function getDefensePct(); abstract public function getInkUsePctMain(); abstract public function getInkUsePctSub(); abstract public function getInkRecoverySec(); abstract public function getRunSpeedPct(); abstract public function getSwimSpeedPct(); abstract public function getSpecialChargePoint(); abstract public function getSpecialDurationSec(); abstract public function getSpecialLossPct(); abstract public function getRespawnSec(); abstract public function getSuperJumpSecs(); abstract public function getBombThrowPct(); abstract public function getMarkingPct(); public function getSpecialDurationCount() { $interval = $this->getSpecialFrameInterval(); if ($interval === null || $interval < 1) { return null; } return (int)ceil($this->getSpecialDurationSec() * 60 / $interval); } protected function getSpecialFrameInterval() { switch ($this->battle->weapon->special->key ?? null) { case 'quickbomb': return 22; case 'splashbomb': return 33; case 'kyubanbomb': return 33; case 'chasebomb': return 38; case 'supershot': return 64; default: return null; } } public function calcDamage($baseDamage, $defMain, $defSub) { $def = $defMain * 10 + $defSub * 3; return $this->calcDamageImpl( $baseDamage, $this->calcX('damage_up', 100), ((0.99 * $def) - pow(0.09 * $def, 2)) / 100, ); } protected function calcDamageImpl($baseDamage, $a, $d) { $x = $a >= $d ? 1 + $a - $d : (1 + ($a - $d) / 1.8); return $baseDamage * $x; } protected function getEffectiveCount($key) { if (!isset($this->countCache[$key])) { $this->countCache[$key] = $this->getEffectiveCountImpl($key); } return $this->countCache[$key]; } protected function getEffectiveCountImpl($key) { $gears = [ $this->battle->headgear, $this->battle->clothing, $this->battle->shoes, ]; $main = 0; $sub = 0; foreach ($gears as $gear) { if (!$gear) { return null; } if ($gear->primaryAbility) { if ($gear->primaryAbility->key === $key) { ++$main; } } if ($gear->secondaries) { foreach ($gear->secondaries as $secondary) { if ($secondary->ability) { if ($secondary->ability->key === $key) { ++$sub; } } } } } return $main * 10 + $sub * 3; } protected function calcX($key, $divBy) { $a = $this->getEffectiveCount($key); if ($a === null) { return null; } return ((0.99 * $a) - pow(0.09 * $a, 2)) / $divBy; } }
1
0.887276
1
0.887276
game-dev
MEDIA
0.814472
game-dev
0.990105
1
0.990105
benfrankel/blobo_party
4,183
src/game/ground.rs
use bevy::prelude::*; use bevy::reflect::TypePath; use bevy::render::render_resource::AsBindGroup; use bevy::render::render_resource::ShaderRef; use bevy::render::render_resource::ShaderType; use bevy::sprite::AlphaMode2d; use bevy::sprite::Material2d; use bevy::sprite::Material2dPlugin; use bevy::time::Stopwatch; use pyri_state::prelude::*; use crate::core::UpdateSet; use crate::core::pause::Pause; use crate::game::audio::music::on_full_beat; use crate::screen::Screen; use crate::util::prelude::*; pub(super) fn plugin(app: &mut App) { app.configure::<(Ground, IsGround)>(); } const GROUND_Z_INDEX: f32 = -10.0; const GROUND_MESH_SIZE: f32 = 1024.0; const GROUND_SNAP_INTERVAL: f32 = GROUND_MESH_SIZE / 4.0; const GROUND_SNAP: Vec2 = Vec2::splat(GROUND_SNAP_INTERVAL); #[derive(Resource)] pub struct Ground { material: Handle<GroundMaterial>, mesh: Handle<Mesh>, animation_stopwatch: Stopwatch, } impl Configure for Ground { fn configure(app: &mut App) { app.add_plugins(Material2dPlugin::<GroundMaterial>::default()); app.init_resource::<Self>(); app.add_systems( Update, Screen::Playing.on_update(( update_background.run_if(Pause::is_disabled), update_background_beat .in_set(UpdateSet::Update) .run_if(on_full_beat(4)), )), ); } } impl FromWorld for Ground { fn from_world(world: &mut World) -> Self { let material = world .resource_mut::<Assets<GroundMaterial>>() .add(GroundMaterial::default()); let mesh = world .resource_mut::<Assets<Mesh>>() .add(Rectangle::default()); let animation_stopwatch = Stopwatch::new(); Self { material, mesh, animation_stopwatch, } } } #[derive(Default, AsBindGroup, Asset, TypePath, Debug, Clone)] pub struct GroundMaterial { #[uniform(100)] uniforms: Uniforms, } #[derive(ShaderType, Default, Clone, Debug)] struct Uniforms { pub camera_x: f32, pub camera_y: f32, pub random: f32, pub time: f32, } impl Material2d for GroundMaterial { fn fragment_shader() -> ShaderRef { "shaders/ground.wgsl".into() } fn alpha_mode(&self) -> AlphaMode2d { AlphaMode2d::Blend } } #[derive(Component, Reflect)] #[reflect(Component)] pub struct IsGround; impl Configure for IsGround { fn configure(app: &mut App) { app.register_type::<Self>(); } } pub fn ground(mut entity: EntityWorldMut) { let ground = r!(entity.world().get_resource::<Ground>()); let mesh = ground.mesh.clone(); let material = ground.material.clone(); entity.insert(( Name::new("Background"), Transform::from_translation(Vec2::ZERO.extend(GROUND_Z_INDEX)) .with_scale(Vec3::splat(GROUND_MESH_SIZE)), Mesh2d(mesh), MeshMaterial2d(material), IsGround, )); } fn update_background( mut ground_material: ResMut<Assets<GroundMaterial>>, mut ground: ResMut<Ground>, camera_query: Query<&Transform, (With<IsDefaultUiCamera>, Without<IsGround>)>, mut ground_query: Query<&mut Transform, With<IsGround>>, time: Res<Time>, ) { for (_, material) in ground_material.iter_mut() { for mut ground_transform in &mut ground_query { for camera_transform in &camera_query { let translation = ((camera_transform.translation.truncate() / GROUND_SNAP).floor() * GROUND_SNAP) .extend(GROUND_Z_INDEX); ground.animation_stopwatch.tick(time.delta()); ground_transform.translation = translation; material.uniforms.camera_x = translation.x; material.uniforms.camera_y = translation.y; material.uniforms.time = ground.animation_stopwatch.elapsed_secs(); } } } } fn update_background_beat(mut ground_material: ResMut<Assets<GroundMaterial>>) { for (_, material) in ground_material.iter_mut() { material.uniforms.random = rand::random(); } }
1
0.752686
1
0.752686
game-dev
MEDIA
0.953185
game-dev
0.540698
1
0.540698
minecraft-ros2/minecraft_ros2
6,463
src/main/java/com/kazusa/minecraft_ros2/block/RedstonePubSubBlock.java
package com.kazusa.minecraft_ros2.block; import com.kazusa.minecraft_ros2.ros2.BlockIntPublisher; import com.kazusa.minecraft_ros2.ros2.BlockBoolSubscriber; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundSource; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MapColor; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.server.level.ServerPlayer; import net.minecraft.network.FriendlyByteBuf; import java.util.function.Consumer; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class RedstonePubSubBlock extends Block implements EntityBlock { public static final BooleanProperty POWERED = BlockStateProperties.POWERED; // ワールド中に現在存在する座標を保持 private static final Set<BlockPos> INSTANCES = ConcurrentHashMap.newKeySet(); private BlockIntPublisher publisher; private BlockBoolSubscriber subscriber; @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new RedStonePubSubBlockEntity(pos, state); } public RedstonePubSubBlock() { super(BlockBehaviour.Properties.of() .mapColor(MapColor.WOOD) .strength(2.0f, 6.0f) .sound(SoundType.WOOD) ); publisher = null; subscriber = null; // デフォルト状態を OFF に設定 this.registerDefaultState(this.stateDefinition.any().setValue(POWERED, false)); } public RedstonePubSubBlock(Properties props) { super(props); } @Override public void onPlace(BlockState state, Level world, BlockPos pos, BlockState oldState, boolean isMoving) { super.onPlace(state, world, pos, oldState, isMoving); if (!world.isClientSide()) { INSTANCES.add(pos.immutable()); } } @Override public void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean isMoving) { super.onRemove(state, world, pos, newState, isMoving); if (!world.isClientSide()) { INSTANCES.remove(pos); } } public void onLoad(BlockPos pos) { // ブロックがロードされたときに座標をセットに追加 INSTANCES.add(pos.immutable()); } /** 現在ワールド上にあるすべての座標を返す */ public static Set<BlockPos> getAllInstances() { return Collections.unmodifiableSet(INSTANCES); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(POWERED); } @Override public ItemInteractionResult useItemOn( ItemStack held, BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit ) { if (held.getItem() == Items.STICK) { // サーバー側だけ GUI を開く if (!world.isClientSide) { ServerPlayer serverPlayer = (ServerPlayer) player; BlockEntity be = world.getBlockEntity(pos); if (be instanceof RedStonePubSubBlockEntity named) { // MenuProvider(= NamedScreenHandlerFactory)として開く var consumer = (Consumer<FriendlyByteBuf>) buf -> { buf.writeBlockPos(pos); // ブロック位置を送信 buf.writeUtf("Redstone Pub Sub Block"); // 名前を指定して開く }; serverPlayer.openMenu( named, consumer ); } } // クライアント/サーバー両方で「成功扱い」を返す return ItemInteractionResult.sidedSuccess(world.isClientSide); } return super.useItemOn(held, state, world, pos, player, hand, hit); } @Override public InteractionResult useWithoutItem( BlockState state, Level world, BlockPos pos, Player player, BlockHitResult hit ) { if (world.isClientSide) { return InteractionResult.SUCCESS; } boolean powered = state.getValue(POWERED); world.setBlock(pos, state.setValue(POWERED, !powered), 3); world.playSound(null, pos, powered ? SoundEvents.STONE_BUTTON_CLICK_OFF : SoundEvents.STONE_BUTTON_CLICK_ON, SoundSource.BLOCKS, 0.3f, 1.0f ); world.updateNeighborsAt(pos, this); return InteractionResult.CONSUME; } @Override public boolean isSignalSource(BlockState state) { return true; } @Override public int getSignal(BlockState state, net.minecraft.world.level.BlockGetter world, BlockPos pos, Direction side) { return state.getValue(POWERED) ? 15 : 0; } @Override public int getDirectSignal(BlockState state, net.minecraft.world.level.BlockGetter world, BlockPos pos, Direction side) { return state.getValue(POWERED) ? 15 : 0; } public void initializeSubscriber(BlockPos pos, String namespace) { if (subscriber != null) { subscriber.shutdown(); subscriber = null; } subscriber = new BlockBoolSubscriber(pos, namespace); } public BlockBoolSubscriber getSubscriber() { return subscriber; } public void initializePublisher(BlockPos pos, String namespace) { if (publisher != null) { publisher.shutdown(); publisher = null; } publisher = new BlockIntPublisher(pos, namespace); } public BlockIntPublisher getPublisher() { return publisher; } }
1
0.820005
1
0.820005
game-dev
MEDIA
0.998415
game-dev
0.89118
1
0.89118
EphemeralSpace/ephemeral-space
3,151
Content.IntegrationTests/Tests/Actions/RetractableItemActionTest.cs
#nullable enable using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Actions; using Content.Shared.Hands.EntitySystems; using Content.Shared.RetractableItemAction; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests.Actions; public sealed class RetractableItemActionTest : InteractionTest { private static readonly EntProtoId ArmBladeActionProtoId = "ActionRetractableItemArmBlade"; /// <summary> /// Gives the player the arm blade action, then activates it and makes sure they are given the blade. /// Afterwards, uses the action again to retract the blade and makes sure their hand is empty. /// </summary> [Test] public async Task ArmBladeActivateDeactivateTest() { var actionsSystem = Server.System<SharedActionsSystem>(); var handsSystem = Server.System<SharedHandsSystem>(); var playerUid = SEntMan.GetEntity(Player); await Server.WaitAssertion(() => { // Make sure the player's hand starts empty var heldItem = handsSystem.GetActiveItem((playerUid, Hands)); Assert.That(heldItem, Is.Null, $"Player is holding an item ({SEntMan.ToPrettyString(heldItem)}) at start of test."); // Inspect the action prototype to find the item it spawns var armBladeActionProto = ProtoMan.Index(ArmBladeActionProtoId); // Find the component Assert.That(armBladeActionProto.TryGetComponent<RetractableItemActionComponent>(out var actionComp, SEntMan.ComponentFactory)); // Get the item protoId from the component var spawnedProtoId = actionComp!.SpawnedPrototype; // Add the action to the player var actionUid = actionsSystem.AddAction(playerUid, ArmBladeActionProtoId); // Make sure the player has the action now Assert.That(actionUid, Is.Not.Null, "Failed to add action to player."); var actionEnt = actionsSystem.GetAction(actionUid); // Make sure the player's hand is still empty heldItem = handsSystem.GetActiveItem((playerUid, Hands)); Assert.That(heldItem, Is.Null, $"Player is holding an item ({SEntMan.ToPrettyString(heldItem)}) after adding action."); // Activate the arm blade actionsSystem.PerformAction(ToServer(Player), actionEnt!.Value); // Make sure the player is now holding the expected item heldItem = handsSystem.GetActiveItem((playerUid, Hands)); Assert.That(heldItem, Is.Not.Null, $"Expected player to be holding {spawnedProtoId} but was holding nothing."); AssertPrototype(spawnedProtoId, SEntMan.GetNetEntity(heldItem)); // Use the action again to retract the arm blade actionsSystem.PerformAction(ToServer(Player), actionEnt.Value); // Make sure the player's hand is empty again heldItem = handsSystem.GetActiveItem((playerUid, Hands)); Assert.That(heldItem, Is.Null, $"Player is still holding an item ({SEntMan.ToPrettyString(heldItem)}) after second use."); }); } }
1
0.97022
1
0.97022
game-dev
MEDIA
0.923985
game-dev,testing-qa
0.845951
1
0.845951
revbayes/revbayes
1,590
src/revlanguage/functions/math/Func_normalize.h
#ifndef Func_normalize_H #define Func_normalize_H #include "RlTypedFunction.h" #include "ModelVector.h" #include "RealPos.h" #include <map> #include <string> namespace RevLanguage { class Func_normalize : public TypedFunction< ModelVector<RealPos> > { public: Func_normalize(); // Basic utility functions Func_normalize* clone(void) const; //!< Clone the object static const std::string& getClassType(void); //!< Get Rev type static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec std::string getFunctionName(void) const; //!< Get the primary name of the function in Rev const TypeSpec& getTypeSpec(void) const; //!< Get language type of the object // Regular functions const ArgumentRules& getArgumentRules(void) const; //!< Get argument rules RevBayesCore::TypedFunction< RevBayesCore::RbVector<double> >* createFunction(void) const; //!< Create internal function object }; } #endif
1
0.687564
1
0.687564
game-dev
MEDIA
0.38686
game-dev
0.560976
1
0.560976
Fate-Grand-Automata/FGA
1,791
scripts/src/main/java/io/github/fate_grand_automata/scripts/locations/MasterLocations.kt
package io.github.fate_grand_automata.scripts.locations import io.github.fate_grand_automata.scripts.IImageLoader import io.github.fate_grand_automata.scripts.IScriptMessages import io.github.fate_grand_automata.scripts.Images import io.github.fate_grand_automata.scripts.ScriptLog import io.github.fate_grand_automata.scripts.models.Skill import io.github.lib_automata.AutomataApi import io.github.lib_automata.Location import io.github.lib_automata.Region import io.github.lib_automata.dagger.ScriptScope import javax.inject.Inject @ScriptScope class MasterLocations @Inject constructor( scriptAreaTransforms: IScriptAreaTransforms, private val images: IImageLoader, private val automataApi: AutomataApi, private val messages: IScriptMessages, ) : IScriptAreaTransforms by scriptAreaTransforms { // Master Skills and Stage counter are right-aligned differently, // so we use locations relative to a matched location private val masterOffsetNewUI: Location by lazy { automataApi.run { Region(-400, 360, 400, 80) .xFromRight() .find(images[Images.BattleMenu]) ?.region ?.center ?.copy(y = 0) ?: Location(-298, 0).xFromRight().also { messages.log(ScriptLog.DefaultMasterOffset) } } } fun locate(skill: Skill.Master) = when (skill) { Skill.Master.A -> -740 Skill.Master.B -> -560 Skill.Master.C -> -400 }.let { x -> Location(x + 178, 620) + masterOffsetNewUI } val stageCountRegion get() = Region(if (isWide) -571 else -638, 23, 33, 53) + masterOffsetNewUI val masterSkillOpenClick get() = Location(0, 640) + masterOffsetNewUI }
1
0.638875
1
0.638875
game-dev
MEDIA
0.673611
game-dev
0.588389
1
0.588389