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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
panoanx/ms-mano-unity | 14,831 | Assets/RFUniverse/Scripts/Attributes/PointCloudAttr.cs | using UnityEngine;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System;
namespace RFUniverse.Attributes
{
public class PointCloudAttr : BaseAttr
{
MeshFilter filter = null;
MeshRenderer render = null;
List<Vector3> positions = new List<Vector3>();
List<Color> colors = new List<Color>();
public override void AnalysisData(string type, object[] data)
{
switch (type)
{
case "ShowPointCloud":
ShowPointCloud((string)data[0], (float[,])data[1], (float[,])data[2], (float)data[3]);
return;
case "SetRadius":
SetRadius((float)data[0]);
return;
}
base.AnalysisData(type, data);
}
private void ShowPointCloud(string path, float[,] positionArray, float[,] colorsArray, float radius)
{
PlayerMain.Instance.GroundActive = false;
if (!string.IsNullOrEmpty(path))
{
ImportPointCloud(path);
}
else
{
positions = RFUniverseUtility.FloatArrayToListVector3(positionArray);
colors = RFUniverseUtility.FloatArrayToListColor(colorsArray);
}
Mesh mesh = CreatePointCloudMesh(positions, colors);
if (render == null)
{
render = gameObject.AddComponent<MeshRenderer>();
render.material = new Material(Shader.Find("RFUniverse/PointCloud"));
}
if (filter == null)
{
filter = gameObject.AddComponent<MeshFilter>();
}
filter.mesh = mesh;
SetRadius(radius);
}
private void SetRadius(float radius)
{
render.material.SetFloat("_Radius", radius);
}
enum DataProperty
{
Invalid,
R8, G8, B8, A8,
R16, G16, B16, A16,
SingleX, SingleY, SingleZ,
DoubleX, DoubleY, DoubleZ,
Data8, Data16, Data32, Data64
}
static int GetPropertySize(DataProperty p)
{
switch (p)
{
case DataProperty.R8: return 1;
case DataProperty.G8: return 1;
case DataProperty.B8: return 1;
case DataProperty.A8: return 1;
case DataProperty.R16: return 2;
case DataProperty.G16: return 2;
case DataProperty.B16: return 2;
case DataProperty.A16: return 2;
case DataProperty.SingleX: return 4;
case DataProperty.SingleY: return 4;
case DataProperty.SingleZ: return 4;
case DataProperty.DoubleX: return 8;
case DataProperty.DoubleY: return 8;
case DataProperty.DoubleZ: return 8;
case DataProperty.Data8: return 1;
case DataProperty.Data16: return 2;
case DataProperty.Data32: return 4;
case DataProperty.Data64: return 8;
}
return 0;
}
class DataHeader
{
public List<DataProperty> properties = new List<DataProperty>();
public int vertexCount = -1;
}
class DataBody
{
public List<Vector3> vertices;
public List<Color> colors;
public DataBody(int vertexCount)
{
vertices = new List<Vector3>(vertexCount);
colors = new List<Color>(vertexCount);
}
public void AddPoint(
float x, float y, float z,
byte r, byte g, byte b, byte a
)
{
vertices.Add(new Vector3(x, y, z));
colors.Add(new Color32(r, g, b, a));
}
}
void ImportPointCloud(string path)
{
try
{
var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
var header = ReadDataHeader(new StreamReader(stream));
var body = ReadDataBody(header, new BinaryReader(stream));
positions = body.vertices;
colors = body.colors;
name = Path.GetFileNameWithoutExtension(path);
}
catch (Exception e)
{
Debug.LogError("Failed importing " + path + ". " + e.Message);
}
}
DataHeader ReadDataHeader(StreamReader reader)
{
var data = new DataHeader();
var readCount = 0;
// Magic number line ("ply")
var line = reader.ReadLine();
readCount += line.Length + 1;
if (line != "ply")
throw new ArgumentException("Magic number ('ply') mismatch.");
// Data format: check if it's binary/little endian.
line = reader.ReadLine();
readCount += line.Length + 1;
if (line != "format binary_little_endian 1.0")
throw new ArgumentException(
"Invalid data format ('" + line + "'). " +
"Should be binary/little endian.");
// Read header contents.
for (var skip = false; ;)
{
// Read a line and split it with white space.
line = reader.ReadLine();
readCount += line.Length + 1;
if (line == "end_header") break;
var col = line.Split();
// Element declaration (unskippable)
if (col[0] == "element")
{
if (col[1] == "vertex")
{
data.vertexCount = Convert.ToInt32(col[2]);
skip = false;
}
else
{
// Don't read elements other than vertices.
skip = true;
}
}
if (skip) continue;
// Property declaration line
if (col[0] == "property")
{
var prop = DataProperty.Invalid;
// Parse the property name entry.
switch (col[2])
{
case "red": prop = DataProperty.R8; break;
case "green": prop = DataProperty.G8; break;
case "blue": prop = DataProperty.B8; break;
case "alpha": prop = DataProperty.A8; break;
case "x": prop = DataProperty.SingleX; break;
case "y": prop = DataProperty.SingleY; break;
case "z": prop = DataProperty.SingleZ; break;
}
// Check the property type.
if (col[1] == "char" || col[1] == "uchar" ||
col[1] == "int8" || col[1] == "uint8")
{
if (prop == DataProperty.Invalid)
prop = DataProperty.Data8;
else if (GetPropertySize(prop) != 1)
throw new ArgumentException("Invalid property type ('" + line + "').");
}
else if (col[1] == "short" || col[1] == "ushort" ||
col[1] == "int16" || col[1] == "uint16")
{
switch (prop)
{
case DataProperty.Invalid: prop = DataProperty.Data16; break;
case DataProperty.R8: prop = DataProperty.R16; break;
case DataProperty.G8: prop = DataProperty.G16; break;
case DataProperty.B8: prop = DataProperty.B16; break;
case DataProperty.A8: prop = DataProperty.A16; break;
}
if (GetPropertySize(prop) != 2)
throw new ArgumentException("Invalid property type ('" + line + "').");
}
else if (col[1] == "int" || col[1] == "uint" || col[1] == "float" ||
col[1] == "int32" || col[1] == "uint32" || col[1] == "float32")
{
if (prop == DataProperty.Invalid)
prop = DataProperty.Data32;
else if (GetPropertySize(prop) != 4)
throw new ArgumentException("Invalid property type ('" + line + "').");
}
else if (col[1] == "int64" || col[1] == "uint64" ||
col[1] == "double" || col[1] == "float64")
{
switch (prop)
{
case DataProperty.Invalid: prop = DataProperty.Data64; break;
case DataProperty.SingleX: prop = DataProperty.DoubleX; break;
case DataProperty.SingleY: prop = DataProperty.DoubleY; break;
case DataProperty.SingleZ: prop = DataProperty.DoubleZ; break;
}
if (GetPropertySize(prop) != 8)
throw new ArgumentException("Invalid property type ('" + line + "').");
}
else
{
throw new ArgumentException("Unsupported property type ('" + line + "').");
}
data.properties.Add(prop);
}
}
// Rewind the stream back to the exact position of the reader.
reader.BaseStream.Position = readCount;
return data;
}
DataBody ReadDataBody(DataHeader header, BinaryReader reader)
{
var data = new DataBody(header.vertexCount);
float x = 0, y = 0, z = 0;
Byte r = 255, g = 255, b = 255, a = 255;
for (var i = 0; i < header.vertexCount; i++)
{
foreach (var prop in header.properties)
{
switch (prop)
{
case DataProperty.R8: r = reader.ReadByte(); break;
case DataProperty.G8: g = reader.ReadByte(); break;
case DataProperty.B8: b = reader.ReadByte(); break;
case DataProperty.A8: a = reader.ReadByte(); break;
case DataProperty.R16: r = (byte)(reader.ReadUInt16() >> 8); break;
case DataProperty.G16: g = (byte)(reader.ReadUInt16() >> 8); break;
case DataProperty.B16: b = (byte)(reader.ReadUInt16() >> 8); break;
case DataProperty.A16: a = (byte)(reader.ReadUInt16() >> 8); break;
case DataProperty.SingleX: x = reader.ReadSingle(); break;
case DataProperty.SingleY: y = reader.ReadSingle(); break;
case DataProperty.SingleZ: z = reader.ReadSingle(); break;
case DataProperty.DoubleX: x = (float)reader.ReadDouble(); break;
case DataProperty.DoubleY: y = (float)reader.ReadDouble(); break;
case DataProperty.DoubleZ: z = (float)reader.ReadDouble(); break;
case DataProperty.Data8: reader.ReadByte(); break;
case DataProperty.Data16: reader.BaseStream.Position += 2; break;
case DataProperty.Data32: reader.BaseStream.Position += 4; break;
case DataProperty.Data64: reader.BaseStream.Position += 8; break;
}
}
data.AddPoint(x, y, z, r, g, b, a);
}
return data;
}
Mesh CreatePointCloudMesh(List<Vector3> positions, List<Color> colors)
{
List<Vector3> meshVertices = new();
List<Vector3> meshNormals = new();
List<Color> meshColors = new();
List<int> meshTriangles = new();
for (int i = 0; i < positions.Count; i++)
{
Vector3 position = positions[i];
Color color = colors[i];
meshVertices.Add(position);
meshNormals.Add(Vector3.up);
meshColors.Add(color);
meshVertices.Add(position);
meshNormals.Add(Vector3.left);
meshColors.Add(color);
meshVertices.Add(position);
meshNormals.Add(Vector3.forward);
meshColors.Add(color);
meshVertices.Add(position);
meshNormals.Add(Vector3.right);
meshColors.Add(color);
meshVertices.Add(position);
meshNormals.Add(Vector3.back);
meshColors.Add(color);
meshVertices.Add(position);
meshNormals.Add(Vector3.down);
meshColors.Add(color);
meshTriangles.Add(i * 6 + 0);
meshTriangles.Add(i * 6 + 1);
meshTriangles.Add(i * 6 + 2);
meshTriangles.Add(i * 6 + 0);
meshTriangles.Add(i * 6 + 2);
meshTriangles.Add(i * 6 + 3);
meshTriangles.Add(i * 6 + 0);
meshTriangles.Add(i * 6 + 3);
meshTriangles.Add(i * 6 + 4);
meshTriangles.Add(i * 6 + 0);
meshTriangles.Add(i * 6 + 4);
meshTriangles.Add(i * 6 + 1);
meshTriangles.Add(i * 6 + 5);
meshTriangles.Add(i * 6 + 1);
meshTriangles.Add(i * 6 + 4);
meshTriangles.Add(i * 6 + 5);
meshTriangles.Add(i * 6 + 4);
meshTriangles.Add(i * 6 + 3);
meshTriangles.Add(i * 6 + 5);
meshTriangles.Add(i * 6 + 3);
meshTriangles.Add(i * 6 + 2);
meshTriangles.Add(i * 6 + 5);
meshTriangles.Add(i * 6 + 2);
meshTriangles.Add(i * 6 + 1);
}
Mesh mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.SetVertices(meshVertices);
mesh.SetNormals(meshNormals);
mesh.SetColors(meshColors);
mesh.SetTriangles(meshTriangles, 0);
return mesh;
}
}
}
| 0 | 0.876227 | 1 | 0.876227 | game-dev | MEDIA | 0.682896 | game-dev,graphics-rendering | 0.988105 | 1 | 0.988105 |
jacking75/NewbieGameServerProgrammerLearningMaterials | 10,105 | csharp_omok_client/CSharp_OmokClient_3/OmokBoard.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
namespace csharp_test_client
{
public partial class mainForm
{
CSCommon.OmokRule OmokLogic = new CSCommon.OmokRule();
enum 돌종류 { 없음, 흑돌, 백돌 };
private int 시작위치 = 30;
private int 눈금크기 = 30;
private int 돌크기 = 20;
private int 화점크기 = 10;
private int 바둑판크기 = 19;
private Stack<Point> st = new Stack<Point>();
private int 전x좌표 = -1, 전y좌표 = -1;
private int 전돌x좌표 = -1, 전돌y좌표 = -1;
private int 현재돌x좌표 = -1, 현재돌y좌표 = -1;
private Pen 검은펜 = new Pen(Color.Black);
private SolidBrush 빨간색 = new SolidBrush(Color.Red);
private SolidBrush 검은색 = new SolidBrush(Color.Black);
private SolidBrush 흰색 = new SolidBrush(Color.White);
private int[,] 바둑판 = new int[19, 19];
private bool 흑돌차례 = true;
private bool 게임종료 = false;
private bool 삼삼 = false;
private bool AI모드 = true;
//private 돌종류 컴퓨터돌;
private SoundPlayer 시작효과음 = new SoundPlayer("/sound/대국시작.wav");
private SoundPlayer 종료효과음 = new SoundPlayer("/sound/대국종료.wav");
private SoundPlayer 승리효과음 = new SoundPlayer("/sound/대국승리.wav");
private SoundPlayer 바둑돌소리 = new SoundPlayer("/sound/바둑돌소리.wav");
private SoundPlayer 무르기요청 = new SoundPlayer("/sound/무르기.wav");
private SoundPlayer 오류효과음 = new SoundPlayer("/sound/오류.wav");
private AI ai;
void Init()
{
DoubleBuffered = true;
시작효과음.Play();
ai = new AI(바둑판);
//컴퓨터돌 = 돌종류.백돌;
}
//오목 게임 시작
/*void StartGame()
{
Array.Clear(바둑판, 0, 바둑판크기 * 바둑판크기);
전x좌표 = 전y좌표 = -1;
전돌x좌표 = 전돌y좌표 = -1;
현재돌x좌표 = 현재돌y좌표 = -1;
흑돌차례 = true;
삼삼 = false;
게임종료 = false;
시작효과음.Play();
st.Clear();
if (AI모드 == true && 컴퓨터돌 == 돌종류.흑돌)
컴퓨터두기();
panel1.Invalidate();
}*/
/*void 한수무르기()
{
st.Pop();
바둑판[현재돌x좌표, 현재돌y좌표] = (int)돌종류.없음;
if (st.Count != 0)
{
현재돌x좌표 = st.Peek().X;
현재돌y좌표 = st.Peek().Y;
}
else
{
현재돌x좌표 = 현재돌y좌표 = -1;
}
}*/
/*void 무르기(object sender, EventArgs e)
{
if (!게임종료 && st.Count != 0)
{
무르기요청.Play();
if (MessageBox.Show("한 수 무르시겠습니까?", "무르기", MessageBoxButtons.YesNo) == DialogResult.Yes) // MessageBox 띄워서 무르기 여부 확인하고 예를 누르면
{
if (AI모드)
{
한수무르기();
한수무르기();
}
else
{
한수무르기();
흑돌차례 = !흑돌차례;
}
panel1.Invalidate();
}
}
}*/
/*void AI흑돌(object sender, EventArgs e)
{
if (AI모드 == false || 컴퓨터돌 == 돌종류.백돌)
{
컴퓨터돌 = 돌종류.흑돌;
AI모드 = true;
StartGame();
}
}*/
/*void AI백돌(object sender, EventArgs e)
{
if (AI모드 == false || 컴퓨터돌 == 돌종류.흑돌)
{
컴퓨터돌 = 돌종류.백돌;
AI모드 = true;
StartGame();
}
}*/
void DisableAIMode()
{
if (AI모드 == true)
{
AI모드 = false;
}
}
#region omok UI
void panel1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < 바둑판크기; i++) // 바둑판 선 그리기
{
e.Graphics.DrawLine(검은펜, 시작위치, 시작위치 + i * 눈금크기, 시작위치 + 18 * 눈금크기, 시작위치 + i * 눈금크기);
e.Graphics.DrawLine(검은펜, 시작위치 + i * 눈금크기, 시작위치, 시작위치 + i * 눈금크기, 시작위치 + 18 * 눈금크기);
}
for (int i = 0; i < 3; i++) // 화점 그리기
{
for (int j = 0; j < 3; j++)
{
Rectangle r = new Rectangle(시작위치 + 눈금크기 * 3 + 눈금크기 * i * 6 - 화점크기 / 2,
시작위치 + 눈금크기 * 3 + 눈금크기 * j * 6 - 화점크기 / 2, 화점크기, 화점크기);
e.Graphics.FillEllipse(검은색, r);
}
}
for (int i = 0; i < 바둑판크기; i++)
for (int j = 0; j < 바둑판크기; j++)
돌그리기(i, j);
if (현재돌x좌표 >= 0 && 현재돌y좌표 >= 0)
현재돌표시();
다음돌표시();
}
void 돌그리기(int x, int y)
{
Graphics g = panel1.CreateGraphics();
Rectangle r = new Rectangle(시작위치 + 눈금크기 * x - 돌크기 / 2,
시작위치 + 눈금크기 * y - 돌크기 / 2, 돌크기, 돌크기);
if (바둑판[x, y] == (int)돌종류.흑돌) // 검은 돌
g.FillEllipse(검은색, r);
else if (바둑판[x, y] == (int)돌종류.백돌) // 흰 돌
g.FillEllipse(흰색, r);
}
void 현재돌표시()
{
// 가장 최근에 놓은 돌에 화점 크기만한 빨간 점으로 표시하기
Graphics g = panel1.CreateGraphics();
Rectangle 앞에찍은돌을다시찍기위한구역 = new Rectangle(시작위치 + 눈금크기 * 전돌x좌표 - 돌크기 / 2,
시작위치 + 눈금크기 * 전돌y좌표 - 돌크기 / 2, 돌크기, 돌크기);
Rectangle r = new Rectangle(시작위치 + 눈금크기 * 현재돌x좌표 - 화점크기 / 2,
시작위치 + 눈금크기 * 현재돌y좌표 - 화점크기 / 2, 화점크기, 화점크기);
if (전돌x좌표 >= 0 && 전돌y좌표 >= 0) // 초기화값이 -1이므로 -1보다 큰 값이 존재하면 찍은 값이 존재함
{
if (바둑판[전돌x좌표, 전돌y좌표] == (int)돌종류.흑돌) // 전돌 다시 찍어서 빨간 점 없애기
g.FillEllipse(검은색, 앞에찍은돌을다시찍기위한구역);
else if (바둑판[전돌x좌표, 전돌y좌표] == (int)돌종류.백돌)
g.FillEllipse(흰색, 앞에찍은돌을다시찍기위한구역);
}
g.FillEllipse(빨간색, r); // 화점 크기만큼 빨간 점 찍기
}
void 다음돌표시() // 화면 하단에 다음에 둘 돌의 색을 표시
{
Graphics g = panel1.CreateGraphics();
string str;
Font 글꼴 = new Font("HY견고딕", 15);
if (흑돌차례) // 다음 돌 표시(검은 돌)
{
str = "다음 돌 : 검은 돌";
g.FillEllipse(검은색, 시작위치 + 170, 599, 돌크기, 돌크기);
g.DrawString(str, 글꼴, 검은색, 시작위치, 600);
}
else // 다음 돌 표시(흰 돌)
{
str = "다음 돌 : 흰 돌";
g.FillEllipse(흰색, 시작위치 + 150, 599, 돌크기, 돌크기);
g.DrawString(str, 글꼴, 검은색, 시작위치, 600);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
int x, y;
if (e.Button != MouseButtons.Left) // 왼쪽클릭만 허용
return;
x = (e.X - 시작위치 + 10) / 눈금크기;
y = (e.Y - 시작위치 + 10) / 눈금크기;
if (x < 0 || x >= 바둑판크기 || y < 0 || y >= 바둑판크기) // 바둑판 크기를 벗어나는지 확인
return;
else if (바둑판[x, y] == (int)돌종류.없음 && !게임종료) // 바둑판 해당 좌표에 아무것도 없고, 게임이 끝나지 않았으면
{
OmokLogic.돌두기(x, y);
돌그리기(x, y);
현재돌표시();
OmokLogic.오목확인(x, y);
if(삼삼 == false)
{
//TODO 서버에 알린다
//TODO 서버에 답변을 받으면 아래 로직 실행하기
//st.Push(new Point(x, y));
//Rectangle r = new Rectangle(시작위치, 590, 시작위치 + 돌크기 + 160, 돌크기 + 10);
//panel1.Invalidate(r);
}
/*if (!삼삼)
{
st.Push(new Point(x, y));
if (AI모드)
{
컴퓨터두기();
}
else
{
Rectangle r = new Rectangle(시작위치, 590, 시작위치 + 돌크기 + 160, 돌크기 + 10);
panel1.Invalidate(r);
}
}*/
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e) // 현재 차례의 돌 잔상 구현 (마우스 움직일때)
{
int x, y;
Color 검은색투명화 = Color.FromArgb(70, Color.Black);
Color 흰색투명화 = Color.FromArgb(70, Color.White);
SolidBrush 투명한검은색 = new SolidBrush(검은색투명화);
SolidBrush 투명한흰색 = new SolidBrush(흰색투명화);
x = (e.X - 시작위치 + 10) / 눈금크기;
y = (e.Y - 시작위치 + 10) / 눈금크기;
if (x < 0 || x >= 바둑판크기 || y < 0 || y >= 바둑판크기) // 바둑판 크기를 벗어나는지 확인
return;
else if (바둑판[x, y] == (int)돌종류.없음 && !게임종료 && (전x좌표 != x || 전y좌표 != y)) // 바둑판 해당 좌표에 아무것도 없고, 좌표가 변경되면
{
Graphics g = panel1.CreateGraphics();
Rectangle 앞에찍은돌을지우기위한구역 = new Rectangle(시작위치 + 눈금크기 * 전x좌표 - 돌크기 / 2,
시작위치 + 눈금크기 * 전y좌표 - 돌크기 / 2, 돌크기, 돌크기);
Rectangle r = new Rectangle(시작위치 + 눈금크기 * x - 돌크기 / 2,
시작위치 + 눈금크기 * y - 돌크기 / 2, 돌크기, 돌크기);
panel1.Invalidate(앞에찍은돌을지우기위한구역); // 먼저 그린 잔상을 지우고 새로운 잔상을 그린다.
if (흑돌차례)
g.FillEllipse(투명한검은색, r);
else
g.FillEllipse(투명한흰색, r);
전x좌표 = x;
전y좌표 = y;
}
}
#endregion
void 컴퓨터두기()
{
int x = 0, y = 0;
do
{
ai.AI_PutAIPlayer(ref x, ref y, false, 2);
OmokLogic.돌두기(x, y);
} while (삼삼);
돌그리기(x, y);
현재돌표시();
OmokLogic.오목확인(x, y);
st.Push(new Point(x, y));
}
}
}
| 0 | 0.787788 | 1 | 0.787788 | game-dev | MEDIA | 0.551308 | game-dev,desktop-app | 0.772076 | 1 | 0.772076 |
FlansMods/FlansMod | 6,911 | src/main/java/com/flansmod/common/enchantments/EnchantmentModule.java | package com.flansmod.common.enchantments;
import com.flansmod.common.FlansMod;
import com.flansmod.common.guns.FireableGun;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemAxe;
import net.minecraft.item.ItemShield;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class EnchantmentModule
{
public static final EnumEnchantmentType SHIELDS = EnumHelper.addEnchantmentType("shields", (item)->(item instanceof ItemShield));
public static final EnumEnchantmentType GLOVES = EnumHelper.addEnchantmentType("gloves", (item)->(item instanceof ItemGlove));
public static final EnumEnchantmentType OFF_HAND = EnumHelper.addEnchantmentType("offHand", (item)->(item instanceof ItemGlove || item instanceof ItemShield));
public static Enchantment STEADY_ENCHANT,
NIMBLE_ENCHANT,
LUMBERJACK_ENCHANT,
DUELIST_ENCHANT,
SHARPSHOOTER_ENCHANT,
JUGGERNAUT_ENCHANT;
public EnchantmentModule()
{
}
public void PreInit()
{
MinecraftForge.EVENT_BUS.register(this);
STEADY_ENCHANT = new EnchantmentSteady().setRegistryName("enchantment_steady").setName("enchantment_steady");
NIMBLE_ENCHANT = new EnchantmentNimble().setRegistryName("enchantment_nimble").setName("enchantment_nimble");
LUMBERJACK_ENCHANT = new EnchantmentLumberjack().setRegistryName("enchantment_lumberjack").setName("enchantment_lumberjack");
DUELIST_ENCHANT = new EnchantmentDuelist().setRegistryName("enchantment_duelist").setName("enchantment_duelist");
SHARPSHOOTER_ENCHANT = new EnchantmentSharpshooter().setRegistryName("enchantment_sharpshooter").setName("enchantment_sharpshooter");
JUGGERNAUT_ENCHANT = new EnchantmentJuggernaut().setRegistryName("enchantment_juggernaut").setName("enchantment_juggernaut");
}
public void Init()
{
}
public void PostInit()
{
}
@SubscribeEvent
public void RegisterEnchants(RegistryEvent.Register<Enchantment> event)
{
event.getRegistry().register(STEADY_ENCHANT);
event.getRegistry().register(NIMBLE_ENCHANT);
event.getRegistry().register(LUMBERJACK_ENCHANT);
event.getRegistry().register(DUELIST_ENCHANT);
event.getRegistry().register(SHARPSHOOTER_ENCHANT);
event.getRegistry().register(JUGGERNAUT_ENCHANT);
}
@SubscribeEvent
public void AttackEvent(LivingHurtEvent event)
{
Entity trueSource = event.getSource().getTrueSource();
if(trueSource != null && trueSource instanceof EntityLivingBase)
{
EntityLivingBase attacker = (EntityLivingBase)trueSource;
ItemStack weaponStack = attacker.getHeldItemMainhand();
ItemStack offHandStack = attacker.getHeldItemOffhand();
// Apply lumberjack offhand effect
if(weaponStack.getItem() instanceof ItemAxe)
{
int lumberjackLevel = EnchantmentHelper.getEnchantmentLevel(LUMBERJACK_ENCHANT, offHandStack);
// Add 10% damage for each level of Lumberjack on the glove (multiplicative)
for(int i = 0; i < lumberjackLevel; i++)
event.setAmount(event.getAmount() * 1.10f);
if(lumberjackLevel > 0)
offHandStack.damageItem(1, attacker);
}
// Apply duelist offhand effect
if(weaponStack.getItem() instanceof ItemSword)
{
int duelistLevel = EnchantmentHelper.getEnchantmentLevel(DUELIST_ENCHANT, offHandStack);
// Add 10% damage for each level of Duelist on the glove (multiplicative)
for(int i = 0; i < duelistLevel; i++)
event.setAmount(event.getAmount() * 1.10f);
if(duelistLevel > 0)
offHandStack.damageItem(1, attacker);
}
// Then apply juggernaut effects
int juggernautLevel = 0;
for(ItemStack armour : event.getEntityLiving().getArmorInventoryList())
{
juggernautLevel += EnchantmentHelper.getEnchantmentLevel(JUGGERNAUT_ENCHANT, armour);
}
if(juggernautLevel > 0)
{
final float minPercent = 0.25f; // With all 4 armour pieces enchanted, we drop to 25% max damage per hit
final float exponent = (float)Math.log(minPercent) / 4f; // 4 because that's the theoretical max level of the enchant
float maxDamageAsPercentOfHP = (float)Math.exp(exponent * juggernautLevel);
float maxHP = event.getEntityLiving().getMaxHealth() + event.getEntityLiving().getTotalArmorValue();
if(event.getAmount() > maxHP * maxDamageAsPercentOfHP)
{
float absorbedDmg = event.getAmount() - maxHP * maxDamageAsPercentOfHP;
// Don't want to just annihalate the armour in edge cases. That would be :(
if(absorbedDmg > 256.0f)
absorbedDmg = 256.0f;
for(ItemStack armour : event.getEntityLiving().getArmorInventoryList())
{
if(EnchantmentHelper.getEnchantmentLevel(JUGGERNAUT_ENCHANT, armour) > 0)
{
armour.damageItem(MathHelper.floor(absorbedDmg), event.getEntityLiving());
}
}
FlansMod.log.info("Juggernaut applied to incoming damage of " + event.getAmount() + " over the threshold of " + (maxHP * maxDamageAsPercentOfHP));
event.setAmount(maxHP * maxDamageAsPercentOfHP);
}
}
}
}
public static void ModifyGun(FireableGun fireableGun, EntityLivingBase entity, ItemStack otherHand)
{
if(!FlansMod.enchantmentModuleEnabled)
return;
int steadyLevel = EnchantmentHelper.getEnchantmentLevel(STEADY_ENCHANT, otherHand);
// Cut 25% of spread for each level of Steady on the glove (multiplicative)
for(int i = 0; i < steadyLevel; i++)
fireableGun.MultiplySpread(0.75f);
int sharpshooterLevel = EnchantmentHelper.getEnchantmentLevel(SHARPSHOOTER_ENCHANT, otherHand);
// Add 10% damage for each level of Sharpshooter on the glove (multiplicative)
for(int i = 0; i < sharpshooterLevel; i++)
fireableGun.MultiplyDamage(1.10f);
if(steadyLevel > 0 || sharpshooterLevel > 0)
otherHand.damageItem(1, entity);
}
public static float ModifyReloadTime(float reloadTime, EntityLivingBase entity, ItemStack otherHand)
{
if(!FlansMod.enchantmentModuleEnabled)
return reloadTime;
int nimbleLevel = EnchantmentHelper.getEnchantmentLevel(NIMBLE_ENCHANT, otherHand);
// Cut 15% of reload time for each level of Nimble on the glove (multiplicative)
for(int i = 0; i < nimbleLevel; i++)
reloadTime *= 0.85f;
if(nimbleLevel > 0)
otherHand.damageItem(1, entity);
return reloadTime;
}
}
| 0 | 0.826008 | 1 | 0.826008 | game-dev | MEDIA | 0.988798 | game-dev | 0.925135 | 1 | 0.925135 |
mobends/MoBends | 1,330 | src/main/java/goblinbob/mobends/standard/client/model/armor/ArmorModelFactory.java | package goblinbob.mobends.standard.client.model.armor;
import goblinbob.mobends.standard.main.MoBends;
import net.minecraft.client.model.ModelBiped;
import java.util.HashMap;
import java.util.Map;
public class ArmorModelFactory
{
protected static Map<ModelBiped, ArmorWrapper> wrapperArchive = new HashMap<>();
/**
* NOTE: This might get called multiple times per frame, with differing "shouldBeMutated" values.
* Hence why we don't demutate and delete the wrappers, just deapply them.
* @param suggested The model instance to mutate/demutate accordingly.
* @param shouldBeMutated Whether to return a vanilla model or the mutated model.
* @return A model that's altered appropriately.
*/
public static ModelBiped getArmorModel(ModelBiped suggested, boolean shouldBeMutated)
{
ArmorWrapper wrapper = wrapperArchive.get(suggested);
if (shouldBeMutated)
{
if (wrapper == null)
{
wrapper = ArmorWrapper.createFor(suggested);
wrapperArchive.put(suggested, wrapper);
MoBends.LOG.info("Creating an armor wrapper for " + suggested);
}
return wrapper;
}
if (wrapper != null)
{
wrapper.deapply();
}
return suggested;
}
public static void refresh()
{
for (ArmorWrapper model : wrapperArchive.values())
{
model.demutate();
}
wrapperArchive.clear();
}
}
| 0 | 0.539322 | 1 | 0.539322 | game-dev | MEDIA | 0.94081 | game-dev | 0.79126 | 1 | 0.79126 |
AaAdoniSsS/GTLAdditions | 3,641 | src/main/java/com/gtladd/gtladditions/mixin/gtceu/recipe/AlloyBlastRecipeProducerMixin.java | package com.gtladd.gtladditions.mixin.gtceu.recipe;
import com.gregtechceu.gtceu.api.GTValues;
import com.gregtechceu.gtceu.api.data.chemical.material.Material;
import com.gregtechceu.gtceu.api.data.chemical.material.properties.BlastProperty;
import com.gregtechceu.gtceu.api.data.tag.TagPrefix;
import com.gregtechceu.gtceu.common.data.GTItems;
import com.gregtechceu.gtceu.data.recipe.builder.GTRecipeBuilder;
import com.gregtechceu.gtceu.data.recipe.misc.alloyblast.AlloyBlastRecipeProducer;
import com.lowdragmc.lowdraglib.side.fluid.FluidStack;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.world.level.material.Fluid;
import com.gtladd.gtladditions.GTLAdditions;
import com.gtladd.gtladditions.common.recipe.GTLAddRecipesTypes;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.function.Consumer;
@Mixin(AlloyBlastRecipeProducer.class)
public abstract class AlloyBlastRecipeProducerMixin {
@Shadow(remap = false)
protected abstract int addInputs(@NotNull Material material, @NotNull GTRecipeBuilder builder);
@Shadow(remap = false)
protected abstract void buildRecipes(@NotNull BlastProperty property, @NotNull Fluid molten, int outputAmount, int componentAmount, @NotNull GTRecipeBuilder builder, Consumer<FinishedRecipe> provider);
@Inject(method = "produce", at = @At(value = "INVOKE", target = "Lcom/gregtechceu/gtceu/data/recipe/misc/alloyblast/AlloyBlastRecipeProducer;buildRecipes(Lcom/gregtechceu/gtceu/api/data/chemical/material/properties/BlastProperty;Lnet/minecraft/world/level/material/Fluid;IILcom/gregtechceu/gtceu/data/recipe/builder/GTRecipeBuilder;Ljava/util/function/Consumer;)V"), remap = false)
public void produce(@NotNull Material material, @NotNull BlastProperty property, Consumer<FinishedRecipe> provider, CallbackInfo ci) {
GTRecipeBuilder builder = this.gtladd$createBuilder(property, material);
this.buildRecipes(property, material.getFluid(), this.addInputs(material, builder), material.getMaterialComponents().size(), builder, provider);
}
@Inject(method = "addFreezerRecipes", at = @At(value = "HEAD"), remap = false)
protected void addFreezerRecipes(@NotNull Material material, @NotNull Fluid molten, int temperature, Consumer<FinishedRecipe> provider, CallbackInfo ci) {
GTRecipeBuilder freezerBuilder = GTLAddRecipesTypes.ANTIENTROPY_CONDENSATION.recipeBuilder(GTLAdditions.id(material.getName()))
.inputFluids(FluidStack.create(molten, 144L)).duration((int) material.getMass() * 2)
.notConsumable(GTItems.SHAPE_MOLD_INGOT.asStack()).outputItems(TagPrefix.ingot, material);
freezerBuilder.EUt(120).save(provider);
}
@Unique
protected @NotNull GTRecipeBuilder gtladd$createBuilder(@NotNull BlastProperty property, @NotNull Material material) {
GTRecipeBuilder builder = GTLAddRecipesTypes.CHAOTIC_ALCHEMY.recipeBuilder(GTLAdditions.id(material.getName()));
builder.duration(property.getDurationOverride() < 0 ? Math.max(1, (int) (material.getMass() * (long) property.getBlastTemperature() / 100L)) : (int) (property.getDurationOverride() * 0.75));
builder.EUt(property.getEUtOverride() < 0 ? GTValues.VA[2] : property.getEUtOverride() / 2);
return builder.blastFurnaceTemp(property.getBlastTemperature());
}
}
| 0 | 0.92975 | 1 | 0.92975 | game-dev | MEDIA | 0.704907 | game-dev | 0.93909 | 1 | 0.93909 |
AtomicStryker/atomicstrykers-minecraft-mods | 29,228 | BattleTowers/src/main/java/atomicstryker/battletowers/common/AS_WorldGenTower.java | package atomicstryker.battletowers.common;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockTorch;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.monster.EntityCaveSpider;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.Event;
public class AS_WorldGenTower
{
public String failState;
private static int candidates[][] = { { 4, -5 }, { 4, 0 }, { 4, 5, }, { 0, -5 }, { 0, 0 }, { 0, 5, }, { -4, -5 }, { -4, 0, }, { -4, 5 } };
private static int candidatecount = candidates.length;
private final static int maxHoleDepthInBase = 22;
/**
* @param world
* instance
* @param random
* gen
* @param ix
* coordinate
* @param jy
* coordinate
* @param kz
* coordinate
* @return -1 when no tower should be able to spawn, else Towerchosen enum
* ordinal
*/
public int getChosenTowerOrdinal(World world, Random random, int ix, int jy, int kz)
{
TowerTypes towerChosen;
int countWater = 0;
int countSand = 0;
int countSnow = 0;
int countFoliage = 0;
int countElse = 0;
for (int ccounter = 0; ccounter < candidatecount; ccounter++)
{
int pair[] = candidates[ccounter];
int checkBlockY = getSurfaceBlockHeight(world, ix + pair[0], kz + pair[1]);
Block ID = world.getBlockState(new BlockPos(ix + pair[0], checkBlockY, kz + pair[1])).getBlock();
if (world.getBlockState(new BlockPos(ix + pair[0], checkBlockY + 1, kz + pair[1])).getBlock() == Blocks.SNOW || ID == Blocks.ICE)
{
countSnow++;
}
else if (ID == Blocks.SAND || ID == Blocks.SANDSTONE)
{
countSand++;
}
else if (ID == Blocks.WATER)
{
countWater++;
}
else if (ID == Blocks.LEAVES || ID == Blocks.WATERLILY || ID == Blocks.LOG || ID == Blocks.LOG2)
{
countFoliage++;
}
else
countElse++;
if (Math.abs(checkBlockY - jy) > maxHoleDepthInBase)
{
failState = "Uneven Surface, diff value: " + Math.abs(checkBlockY - jy);
return -1;
}
for (int ycounter2 = 1; ycounter2 <= 3; ycounter2++)
{
ID = world.getBlockState(new BlockPos(ix + pair[0], (checkBlockY + ycounter2), kz + pair[1])).getBlock();
if (isBannedBlockID(ID))
{
failState = "Surface banned Block of ID: " + ID + " at height: " + ycounter2;
return -1;
}
}
for (int ycounter = 1; ycounter <= 5; ycounter++)
{
ID = world.getBlockState(new BlockPos(ix + pair[0], checkBlockY - ycounter, kz + pair[1])).getBlock();
if (ID == Blocks.AIR || isBannedBlockID(ID))
{
failState = "Depth check - Banned Block or hole, Depth: " + ycounter + " ID: " + ID;
return -1;
}
}
}
// System.err.println("Snow: "+countSnow+" Sand: "+countSand+" Water: "+countWater+" else: "+countElse);
int[] nums = { countWater, countSnow, countSand, countFoliage, countElse };
Arrays.sort(nums);
int result = nums[nums.length - 1];
// System.err.println("Picked max value of "+result);
if (countSand == result)
{
towerChosen = TowerTypes.SandStone;
}
else if (countSnow == result)
{
towerChosen = TowerTypes.Ice;
}
else if (countWater == result)
{
towerChosen = TowerTypes.CobbleStoneMossy;
}
else if (countFoliage == result)
{
towerChosen = TowerTypes.CobbleStoneMossy;
}
else // standard is cobblestone, really rare should be nether
{
if (random.nextInt(10) == 0)
{
towerChosen = TowerTypes.Netherrack;
}
else
{
towerChosen = (random.nextInt(5) == 0) ? TowerTypes.SmoothStone : TowerTypes.CobbleStone;
}
}
return towerChosen.ordinal();
}
@SuppressWarnings("deprecation") // is needed because getDefaultState on stairs does not work
public void generate(World world, Random random, int ix, int jy, int kz, int towerchoice, boolean underground)
{
TowerTypes towerChosen = TowerTypes.values()[towerchoice];
Block towerWallBlockID = towerChosen.getWallBlockID();
Block towerLightBlockID = towerChosen.getLightBlockID();
Block towerFloorBlockID = towerChosen.getFloorBlockID();
int towerFloorMeta = towerChosen.getFloorBlockMetaData();
int startingHeight = underground ? Math.max(jy - 70, 15) : jy - 6;
int maximumHeight = underground ? jy + 7 : 120;
int floor = 1;
boolean topFloor = false;
int builderHeight = startingHeight;
for (; builderHeight < maximumHeight; builderHeight += 7) // builderHeight jumps floors
{
if (builderHeight + 7 >= maximumHeight)
{
topFloor = true;
}
for (int floorIterator = 0; floorIterator < 7; floorIterator++) // build each floor height block till next floor
{
if (floor == 1 && floorIterator < 4) // initial floor
{
floorIterator = 4;
}
for (int xIterator = -7; xIterator < 7; xIterator++) // do each X
{
for (int zIterator = -7; zIterator < 7; zIterator++) // do each Z
{
int iCurrent = xIterator + ix;
int jCurrent = floorIterator + builderHeight;
int zCurrent = zIterator + kz;
if (zIterator == -7) // last row, 14
{
if (xIterator > -5 && xIterator < 4) // rear outer wall
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
continue;
}
if (zIterator == -6 || zIterator == -5) // rows 12 and 13
{
if (xIterator == -5 || xIterator == 4) // outer wall parts
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
continue;
}
if (zIterator == -6) // row 13 extra
{
if (xIterator == (floorIterator + 1) % 7 - 3) // stairwell!!
{
if (!(underground && floor == 1))
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), towerChosen.getStairBlockID().getStateFromMeta(0));
}
if (floorIterator == 5)
{
world.setBlockState(new BlockPos(iCurrent - 7, jCurrent, zCurrent), towerFloorBlockID.getDefaultState());
}
if (floorIterator == 6 && topFloor) // top ledge part
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
continue;
}
if (xIterator < 4 && xIterator > -5) // tower insides
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState());
}
continue;
}
if (zIterator != -5 || xIterator <= -5 || xIterator >= 5) // outside tower
{
continue;
}
if (floorIterator != 0 && floorIterator != 6 || xIterator != -4 && xIterator != 3)
{
if (floorIterator == 5 && (xIterator == 3 || xIterator == -4))
{
buildFloorPiece(world, iCurrent, jCurrent, zCurrent, towerFloorBlockID, towerFloorMeta);
}
else
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator); // under stairwell
}
}
else
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState()); // stairwell space
}
continue;
}
if (zIterator == -4 || zIterator == -3 || zIterator == 2 || zIterator == 3) // rows 11, 10, 5, 4
{
if (xIterator == -6 || xIterator == 5) // outer wall parts
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
continue;
}
if (xIterator <= -6 || xIterator >= 5) // outside tower
{
continue;
}
if (floorIterator == 5)
{
buildFloorPiece(world, iCurrent, jCurrent, zCurrent, towerFloorBlockID, towerFloorMeta);
continue;
}
if (world.getBlockState(new BlockPos(iCurrent, jCurrent, zCurrent)).getBlock() != Blocks.CHEST) // tower inside space
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState());
}
continue;
}
if (zIterator > -3 && zIterator < 2) // rows 10 to 5
{
if (xIterator == -7 || xIterator == 6)
{
if (floorIterator < 0 || floorIterator > 3 || ((xIterator != -7 && xIterator != 6) || underground) || zIterator != -1 && zIterator != 0) // wall, short of window
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
else
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState());
}
continue;
}
if (xIterator <= -7 || xIterator >= 6)
{
continue;
}
if (floorIterator == 5)
{
buildFloorPiece(world, iCurrent, jCurrent, zCurrent, towerFloorBlockID, towerFloorMeta);
}
else
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState());
}
continue;
}
if (zIterator == 4) // row 3
{
if (xIterator == -5 || xIterator == 4)
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
continue;
}
if (xIterator <= -5 || xIterator >= 4)
{
continue;
}
if (floorIterator == 5)
{
buildFloorPiece(world, iCurrent, jCurrent, zCurrent, towerFloorBlockID, towerFloorMeta);
}
else
{
world.setBlockState(new BlockPos(iCurrent, jCurrent, zCurrent), Blocks.AIR.getDefaultState());
}
continue;
}
if (zIterator == 5) // row 2
{
if (xIterator == -4 || xIterator == -3 || xIterator == 2 || xIterator == 3)
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
continue;
}
if (xIterator <= -3 || xIterator >= 2)
{
continue;
}
if (floorIterator == 5)
{
buildFloorPiece(world, iCurrent, jCurrent, zCurrent, towerFloorBlockID, towerFloorMeta);
}
else
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
continue;
}
if (zIterator != 6 || xIterator <= -3 || xIterator >= 2)
{
continue;
}
if (floorIterator < 0 || floorIterator > 3 || xIterator != -1 && xIterator != 0)
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
else
{
buildWallPiece(world, iCurrent, jCurrent, zCurrent, towerWallBlockID, floor, floorIterator);
}
}
}
}
if (floor == 2)
{
world.setBlockState(new BlockPos(ix + 3, builderHeight, kz - 5), towerWallBlockID.getDefaultState());
world.setBlockState(new BlockPos(ix + 3, builderHeight - 1, kz - 5), towerWallBlockID.getDefaultState());
}
if ((!underground && topFloor) || (underground && floor == 1))
{
if (towerChosen != TowerTypes.Null)
{
AS_EntityGolem entitygolem = new AS_EntityGolem(world, towerChosen.ordinal());
entitygolem.setLocationAndAngles(ix + 0.5D, builderHeight + 6, kz + 0.5D, world.rand.nextFloat() * 360F, 0.0F);
world.spawnEntity(entitygolem);
}
}
else
{
if (towerChosen != TowerTypes.Null)
{
world.setBlockState(new BlockPos(ix + 2, builderHeight + 6, kz + 2), Blocks.MOB_SPAWNER.getDefaultState());
TileEntityMobSpawner tileentitymobspawner = (TileEntityMobSpawner) world.getTileEntity(new BlockPos(ix + 2, builderHeight + 6, kz + 2));
if (tileentitymobspawner != null)
{
if (!DungeonTweaksCompat.isLoaded)
{
tileentitymobspawner.getSpawnerBaseLogic().setEntityId(getMobType(world.rand));
}
else
{
DungeonTweaksCompat.fireDungeonSpawn(tileentitymobspawner, world, random, towerChosen);
}
}
world.setBlockState(new BlockPos(ix - 3, builderHeight + 6, kz + 2), Blocks.MOB_SPAWNER.getDefaultState());
tileentitymobspawner = (TileEntityMobSpawner) world.getTileEntity(new BlockPos(ix - 3, builderHeight + 6, kz + 2));
if (tileentitymobspawner != null)
{
if (!DungeonTweaksCompat.isLoaded)
{
tileentitymobspawner.getSpawnerBaseLogic().setEntityId(getMobType(world.rand));
}
else
{
DungeonTweaksCompat.fireDungeonSpawn(tileentitymobspawner, world, random, towerChosen);
}
}
}
else
{
world.setBlockState(new BlockPos(ix + 2, builderHeight + 6, kz + 2), Blocks.AIR.getDefaultState());
world.setBlockState(new BlockPos(ix - 3, builderHeight + 6, kz + 2), Blocks.AIR.getDefaultState());
}
}
// chest pedestal
world.setBlockState(new BlockPos(ix, builderHeight + 6, kz + 3), towerFloorBlockID.getDefaultState());
world.setBlockState(new BlockPos(ix - 1, builderHeight + 6, kz + 3), towerFloorBlockID.getDefaultState());
if (builderHeight + 56 >= 120 && floor == 1)
{
floor = 2;
}
if (towerChosen != TowerTypes.Null)
{
// chest
TowerStageItemManager floorChestManager;
if (!underground)
{
floorChestManager = topFloor ? WorldGenHandler.getTowerStageManagerForFloor(10) : WorldGenHandler.getTowerStageManagerForFloor(floor);
}
else
{
floorChestManager = floor == 1 ? WorldGenHandler.getTowerStageManagerForFloor(10) : WorldGenHandler.getTowerStageManagerForFloor(Math.abs(11 - floor));
}
for (int chestlength = 0; chestlength < 2; chestlength++)
{
world.setBlockState(new BlockPos(ix - chestlength, builderHeight + 7, kz + 3), Blocks.CHEST.getStateFromMeta(2));
TileEntityChest tileentitychest = (TileEntityChest) world.getTileEntity(new BlockPos(ix - chestlength, builderHeight + 7, kz + 3));
if (tileentitychest != null)
{
int count = underground ? AS_BattleTowersCore.instance.itemGenerateAttemptsPerFloor * 2 : AS_BattleTowersCore.instance.itemGenerateAttemptsPerFloor;
List<ItemStack> generatedStacks = floorChestManager.getStageItemStacks(world, world.rand, tileentitychest, count);
List<Integer> freeSlots = new ArrayList<>(tileentitychest.getSizeInventory());
for (int i = 0; i < tileentitychest.getSizeInventory(); i++)
{
freeSlots.add(i);
}
Iterator<ItemStack> iterator = generatedStacks.iterator();
while (iterator.hasNext() && !freeSlots.isEmpty())
{
Integer slot = freeSlots.get(world.rand.nextInt(freeSlots.size()));
freeSlots.remove(slot);
tileentitychest.setInventorySlotContents(slot, iterator.next());
}
}
}
}
else
{
for (int chestlength = 0; chestlength < 2; chestlength++)
{
world.setBlockState(new BlockPos(ix - chestlength, builderHeight + 7, kz + 3), Blocks.CHEST.getStateFromMeta(2));
}
}
// move lights builder a bit higher, to support non-opaque lights such as lamps
if (towerLightBlockID == Blocks.TORCH)
{
world.setBlockState(new BlockPos(ix + 3, builderHeight+2, kz - 6), towerLightBlockID.getStateFromMeta(0).withProperty(BlockTorch.FACING, EnumFacing.SOUTH), 2);
world.setBlockState(new BlockPos(ix - 4, builderHeight+2, kz - 6), towerLightBlockID.getStateFromMeta(0).withProperty(BlockTorch.FACING, EnumFacing.SOUTH), 2);
world.setBlockState(new BlockPos(ix + 1, builderHeight+2, kz - 4), towerLightBlockID.getStateFromMeta(0).withProperty(BlockTorch.FACING, EnumFacing.SOUTH), 2);
world.setBlockState(new BlockPos(ix - 2, builderHeight+2, kz - 4), towerLightBlockID.getStateFromMeta(0).withProperty(BlockTorch.FACING, EnumFacing.SOUTH), 2);
}
else
{
world.setBlockState(new BlockPos(ix + 3, builderHeight+2, kz - 6), towerLightBlockID.getStateFromMeta(0));
world.setBlockState(new BlockPos(ix - 4, builderHeight+2, kz - 6), towerLightBlockID.getStateFromMeta(0));
world.setBlockState(new BlockPos(ix + 1, builderHeight+2, kz - 4), towerLightBlockID.getStateFromMeta(0));
world.setBlockState(new BlockPos(ix - 2, builderHeight+2, kz - 4), towerLightBlockID.getStateFromMeta(0));
}
if (towerChosen != TowerTypes.Null)
{
for (int l3 = 0; l3 < (floor * 4 + towerChosen.ordinal()) - 8 && !topFloor; l3++) // random hole poker
{
int k4 = 5 - world.rand.nextInt(12);
int k5 = builderHeight + 5;
int j6 = 5 - world.rand.nextInt(10);
if (j6 < -2 && k4 < 4 && k4 > -5 && k4 != 1 && k4 != -2)
{
continue;
}
k4 += ix;
j6 += kz;
if (world.getBlockState(new BlockPos(k4, k5, j6)).getBlock() == towerFloorBlockID && world.getBlockState(new BlockPos(k4, k5 + 1, j6)).getBlock() != Blocks.MOB_SPAWNER)
{
world.setBlockState(new BlockPos(k4, k5, j6), Blocks.AIR.getDefaultState());
}
}
}
floor++;
}
System.out.println("Battle Tower type " + towerChosen + " spawned at [ " + ix + " | " + kz + " ], underground: " + underground);
}
@SuppressWarnings("deprecation")
private void buildFloorPiece(World world, int i, int j, int k, Block towerFloorBlockID, int towerFloorMeta)
{
world.setBlockState(new BlockPos(i, j, k), towerFloorBlockID.getStateFromMeta(towerFloorMeta));
}
private void buildWallPiece(World world, int i, int j, int k, Block towerWallBlockID, int floor, int floorIterator)
{
world.setBlockState(new BlockPos(i, j, k), towerWallBlockID.getDefaultState());
if (floor == 1 && floorIterator == 4)
{
fillTowerBaseToGround(world, i, j, k, towerWallBlockID);
}
}
private void fillTowerBaseToGround(World world, int i, int j, int k, Block blocktype)
{
int y = j - 1;
while (y > 0 && !isBuildableBlockID(world.getBlockState(new BlockPos(i, y, k)).getBlock()))
{
world.setBlockState(new BlockPos(i, y, k), blocktype.getDefaultState());
y--;
}
}
private int getSurfaceBlockHeight(World world, int x, int z)
{
int h = 50;
do
{
h++;
}
while (world.getBlockState(new BlockPos(x, h, z)).getBlock() != Blocks.AIR && !isFoliageBlockID(world.getBlockState(new BlockPos(x, h, z)).getBlock()));
return h - 1;
}
private boolean isFoliageBlockID(Block ID)
{
return (ID == Blocks.SNOW || ID == Blocks.TALLGRASS || ID == Blocks.DEADBUSH || ID == Blocks.LOG || ID == Blocks.LOG2 || ID == Blocks.LEAVES);
}
private boolean isBuildableBlockID(Block ID)
{
return (ID == Blocks.STONE || ID == Blocks.GRASS || ID == Blocks.SAND || ID == Blocks.SANDSTONE || ID == Blocks.GRAVEL || ID == Blocks.DIRT);
}
private boolean isBannedBlockID(Block iD)
{
return (iD == Blocks.YELLOW_FLOWER || iD == Blocks.RED_FLOWER || iD == Blocks.BROWN_MUSHROOM_BLOCK || iD == Blocks.RED_MUSHROOM_BLOCK || iD == Blocks.CACTUS || iD == Blocks.PUMPKIN
|| iD == Blocks.LAVA);
}
private ResourceLocation getMobType(Random random)
{
switch (random.nextInt(10))
{
case 0:
case 1:
case 2:
{
return EntityList.getKey(EntitySkeleton.class);
}
case 3:
case 4:
case 5:
case 6:
{
return EntityList.getKey(EntityZombie.class);
}
case 7:
case 8:
{
EntityList.getKey(EntitySpider.class);
}
case 9:
{
return EntityList.getKey(EntityCaveSpider.class);
}
default:
return EntityList.getKey(EntityZombie.class);
}
}
public enum TowerTypes
{
Null("null",Blocks.AIR, Blocks.AIR, Blocks.AIR, 0, Blocks.AIR),
CobbleStone("cobblestone",Blocks.COBBLESTONE, Blocks.TORCH, Blocks.DOUBLE_STONE_SLAB, 0, Blocks.STONE_STAIRS),
CobbleStoneMossy("cobblestonemossy",Blocks.MOSSY_COBBLESTONE, Blocks.TORCH, Blocks.DOUBLE_STONE_SLAB, 0, Blocks.STONE_STAIRS),
SandStone("sandstone",Blocks.SANDSTONE, Blocks.TORCH, Blocks.DOUBLE_STONE_SLAB, 1, Blocks.SANDSTONE_STAIRS),
Ice("ice",Blocks.ICE, Blocks.AIR /* Blocks.GLOWSTONE */, Blocks.CLAY, 2, Blocks.OAK_STAIRS), // since when does glowstone melt ice
SmoothStone("smoothstone",Blocks.STONE, Blocks.TORCH, Blocks.DOUBLE_STONE_SLAB, 3, Blocks.STONE_STAIRS),
Netherrack("netherrack",Blocks.NETHERRACK, Blocks.GLOWSTONE, Blocks.SOUL_SAND, 0, Blocks.NETHER_BRICK_STAIRS),
Jungle("jungle",Blocks.MOSSY_COBBLESTONE, Blocks.WEB, Blocks.DIRT, 0, Blocks.JUNGLE_STAIRS);
private Block wallBlockID;
private Block lightBlockID;
private Block floorBlockID;
private int floorBlockMetaData;
private Block stairBlockID;
private String typeName;
TowerTypes(String t, Block a, Block b, Block c, int d, Block e)
{
this.wallBlockID = a;
this.lightBlockID = b;
this.floorBlockID = c;
this.floorBlockMetaData = d;
this.stairBlockID = e;
this.typeName = t;
}
Block getWallBlockID()
{
return wallBlockID;
}
Block getLightBlockID()
{
return lightBlockID;
}
Block getFloorBlockID()
{
return floorBlockID;
}
int getFloorBlockMetaData()
{
return floorBlockMetaData;
}
Block getStairBlockID()
{
return stairBlockID;
}
public String getName()
{
return this.typeName;
}
public ResourceLocation getId()
{
return new ResourceLocation("battletowers:" + this.typeName);
}
}
}
| 0 | 0.757568 | 1 | 0.757568 | game-dev | MEDIA | 0.997493 | game-dev | 0.951846 | 1 | 0.951846 |
Fluorohydride/ygopro-scripts | 1,272 | c16964437.lua | --ダーク・ホライズン
function c16964437.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e1:SetCode(EVENT_DAMAGE)
e1:SetCondition(c16964437.condition)
e1:SetTarget(c16964437.target)
e1:SetOperation(c16964437.activate)
c:RegisterEffect(e1)
end
function c16964437.condition(e,tp,eg,ep,ev,re,r,rp)
return ep==tp
end
function c16964437.filter(c,e,tp,dam)
return c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsAttackBelow(dam) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c16964437.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c16964437.filter,tp,LOCATION_DECK,0,1,nil,e,tp,ev) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c16964437.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c16964437.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp,ev)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| 0 | 0.90598 | 1 | 0.90598 | game-dev | MEDIA | 0.982555 | game-dev | 0.938037 | 1 | 0.938037 |
CaravelGames/drod | 5,462 | drodrpg/DROD/WorldMapScreen.cpp | // $Id$
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Deadly Rooms of Death.
*
* The Initial Developer of the Original Code is
* Caravel Software.
* Portions created by the Initial Developer are Copyright (C)
* 2002, 2005 Caravel Software. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
#include "WorldMapScreen.h"
#include "WorldMapWidget.h"
#include "GameScreen.h"
#include "../DRODLib/CurrentGame.h"
#include "../DRODLib/Db.h"
#include "../DRODLib/DbHolds.h"
#include "../DRODLib/SettingsKeys.h"
#include <FrontEndLib/FlashMessageEffect.h>
#include <BackEndLib/Files.h>
const UINT TAG_WORLDMAP = 1010;
//************************************************************************************
CWorldMapScreen::CWorldMapScreen()
: CDrodScreen(SCR_WorldMap)
, pWorldMapWidget(NULL)
{
this->pWorldMapWidget = new CWorldMapWidget(TAG_WORLDMAP, 0, 0, CScreen::CX_SCREEN, CScreen::CY_SCREEN);
AddWidget(this->pWorldMapWidget);
}
//*****************************************************************************
void CWorldMapScreen::OnBetweenEvents()
{
Animate();
}
void CWorldMapScreen::Animate()
{
Paint();
}
//*****************************************************************************
void CWorldMapScreen::Paint(
//Overridable method to paint the screen.
//
//Params:
bool bUpdateRect) //(in) If true (default) and destination
// surface is the screen, the screen
// will be immediately updated in
// the widget's rect.
{
PaintChildren();
this->pEffects->UpdateAndDrawEffects();
if (bUpdateRect) UpdateRect();
}
//************************************************************************************
bool CWorldMapScreen::SetForActivate()
//Called before screen is activated and first paint.
//
//Returns:
//True if activation should continue, false if not.
{
CCurrentGame *pCurrentGame = GetCurrentGame();
ASSERT(pCurrentGame);
SetMusic(pCurrentGame);
this->pWorldMapWidget->SetCurrentGame(pCurrentGame);
//Don't automatically return to the game screen.
//This screen decides where to transition next.
if (g_pTheSM->GetReturnScreenType() == SCR_Game)
g_pTheSM->RemoveReturnScreen();
CFlashMessageEffect *pTextPromptEffect = new CFlashMessageEffect(
this, g_pTheDB->GetMessageText(MID_WorldMapDestinationPrompt), 250, 2000);
pTextPromptEffect->SlowExpansion();
this->pEffects->AddEffect(pTextPromptEffect);
//Eat pre-existing events.
ClearEvents();
return true;
}
//
//Private methods.
//
CCurrentGame* CWorldMapScreen::GetCurrentGame() const
{
CGameScreen *pGameScreen = DYN_CAST(CGameScreen*, CScreen*,
g_pTheSM->GetScreen(SCR_Game));
ASSERT(pGameScreen);
return pGameScreen->GetCurrentGame();
}
//*****************************************************************************
void CWorldMapScreen::OnSelectChange(
//Handles a selection change.
//
//Params:
const UINT dwTagNo) //(in) Widget event applies to.
{
switch (dwTagNo)
{
case TAG_WORLDMAP:
{
const WorldMapIcon *pIcon = this->pWorldMapWidget->GetClickedIcon();
ASSERT(pIcon);
switch (pIcon->displayFlags) {
case ScriptFlag::WMI_Disabled:
case ScriptFlag::WMI_NoLabel:
break;
case ScriptFlag::WMI_Locked:
g_pTheSound->PlaySoundEffect(SEID_CHECKPOINT);
break;
default:
{
g_pTheSound->PlaySoundEffect(SEID_SWORDS);
const UINT entranceID = pIcon->entranceID;
CGameScreen *pGameScreen = DYN_CAST(CGameScreen*, CScreen*,
g_pTheSM->GetScreen(SCR_Game));
ASSERT(pGameScreen);
pGameScreen->GotoEntrance(entranceID, pIcon->exitType);
//Transition to next appropriate screen.
const SCREENTYPE nextscreen = pGameScreen->SelectGotoScreen();
g_pTheSM->InsertReturnScreen(nextscreen);
Deactivate();
}
break;
}
}
}
}
//******************************************************************************
void CWorldMapScreen::SetMusic(CCurrentGame *pCurrentGame)
{
const WorldMapMusic music = pCurrentGame->GetWorldMapMusic(pCurrentGame->worldMapID);
static const UINT defaultSongID = SONGID_INTRO;
switch (music.songID) {
case (UINT)SONGID_DEFAULT:
g_pTheSound->CrossFadeSong(defaultSongID);
break;
case (UINT)SONGID_NONE:
g_pTheSound->StopSong();
break;
case (UINT)SONGID_CUSTOM:
g_pTheSound->PlayData(music.customID);
break;
default:
if (music.songlist.empty()) {
if (music.songID < UINT(SONGID_COUNT)) {
g_pTheSound->CrossFadeSong(music.songID);
} else {
g_pTheSound->CrossFadeSong(defaultSongID);
}
} else {
CFiles f;
list<WSTRING> songlist;
if (f.GetGameProfileString(INISection::Songs, music.songlist.c_str(), songlist))
{
g_pTheSound->CrossFadeSong(&songlist);
f.WriteGameProfileString(INISection::Songs, music.songlist.c_str(), songlist);
} else {
g_pTheSound->CrossFadeSong(defaultSongID);
}
}
break;
}
}
| 0 | 0.888536 | 1 | 0.888536 | game-dev | MEDIA | 0.940374 | game-dev | 0.812329 | 1 | 0.812329 |
modernuo/ModernUO | 1,048 | Projects/UOContent/Items/Champion Artifacts/Unique/OrcChieftainHelm.cs | using ModernUO.Serialization;
namespace Server.Items
{
[SerializationGenerator(0, false)]
public partial class OrcChieftainHelm : OrcHelm
{
[Constructible]
public OrcChieftainHelm()
{
Hue = 0x2a3;
Attributes.Luck = 100;
Attributes.RegenHits = 3;
if (Utility.RandomBool())
{
Attributes.BonusHits = 30;
}
else
{
Attributes.AttackChance = 30;
}
}
public override int LabelNumber => 1094924; // Orc Chieftain Helm [Replica]
public override int BasePhysicalResistance => 23;
public override int BaseFireResistance => 1;
public override int BaseColdResistance => 23;
public override int BasePoisonResistance => 3;
public override int BaseEnergyResistance => 5;
public override int InitMinHits => 150;
public override int InitMaxHits => 150;
public override bool CanFortify => false;
}
}
| 0 | 0.821623 | 1 | 0.821623 | game-dev | MEDIA | 0.900143 | game-dev | 0.692514 | 1 | 0.692514 |
stoneman404/motion-planning-with-carla | 8,005 | obstacle_manager/src/obstacle_manager/obstacle.cpp | #include <tf/transform_datatypes.h>
#include "obstacle_manager/obstacle.hpp"
#include "math/math_utils.hpp"
namespace planning {
using namespace common;
Obstacle::Obstacle(const derived_object_msgs::Object &object) {
this->is_valid_obstacle_ = (!std::isnan(object.shape.dimensions[0])
&& !std::isnan(object.shape.dimensions[1])
&& !std::isnan(object.shape.dimensions[2]));
id_ = object.id;
this->speed_ = std::sqrt(object.twist.linear.x +
object.twist.linear.y);
this->angular_speed_ = object.twist.angular.z;
// this->is_static_ = std::fabs(this->speed_) < 0.1 && std::fabs(this->angular_speed_) < 0.1;
this->is_static_ = false;
this->heading_ = tf::getYaw(object.pose.orientation);
center_ = Eigen::Vector2d(object.pose.position.x, object.pose.position.y);
double length = std::max(object.shape.dimensions[0], object.shape.dimensions[1]);
double width = std::min(object.shape.dimensions[0], object.shape.dimensions[1]);
this->bounding_box_ = Box2d(center_, heading_, length, width);
acc_ = object.accel.linear.x * std::cos(heading_) + object.accel.linear.y * std::sin(heading_);
centripental_acc_ = object.accel.linear.y * std::cos(heading_) - object.accel.linear.x * std::sin(heading_);
kappa_ = std::fabs(speed_) < 1e-2 ? 0.0 : angular_speed_ / speed_;
}
Obstacle::Obstacle(const Obstacle &other) {
this->id_ = other.id_;
this->bounding_box_ = other.bounding_box_;
this->speed_ = other.speed_;
this->angular_speed_ = other.angular_speed_;
this->trajectory_ = other.trajectory_;
this->is_valid_obstacle_ = other.is_valid_obstacle_;
this->is_static_ = other.is_static_;
this->center_ = other.center_;
this->heading_ = other.heading_;
}
Box2d Obstacle::GetBoundingBoxAtPoint(const planning_msgs::TrajectoryPoint &point) const {
Eigen::Vector2d center = Eigen::Vector2d(point.path_point.x, point.path_point.y);
return Box2d(center, point.path_point.theta, bounding_box_.length(), bounding_box_.width());
}
planning_msgs::TrajectoryPoint Obstacle::GetPointAtTime(double relative_time) const {
const auto &trajectory_points = trajectory_.trajectory_points;
// for static obstacle
if (trajectory_points.size() < 2) {
planning_msgs::TrajectoryPoint point;
point.path_point.s = 0.0;
point.path_point.x = center_[0];
point.path_point.y = center_[1];
point.path_point.theta = heading_;
point.path_point.kappa = 0.0;
point.path_point.dkappa = 0.0;
point.vel = 0.0;
point.acc = 0.0;
point.jerk = 0.0;
point.steer_angle = 0.0;
point.relative_time = 0.0;
return point;
} else {
auto comp = [](const planning_msgs::TrajectoryPoint &p, const double &relative_time) -> bool {
return p.relative_time < relative_time;
};
auto it_lower = std::lower_bound(trajectory_points.begin(),
trajectory_points.end(), relative_time, comp);
if (it_lower == trajectory_points.begin()) {
return *trajectory_points.begin();
}
if (it_lower == trajectory_points.end()) {
return *trajectory_points.rbegin();
}
return MathUtils::InterpolateTrajectoryPoint(*(it_lower - 1), *it_lower, relative_time);
}
}
bool Obstacle::HasTrajectory() const { return trajectory_.trajectory_points.size() > 1; }
const Box2d &Obstacle::GetBoundingBox() const { return bounding_box_; }
const Eigen::Vector2d &Obstacle::Center() const { return center_; }
const bool &Obstacle::IsStatic() const { return is_static_; }
const double &Obstacle::Speed() const { return speed_; }
const int &Obstacle::Id() const { return id_; }
const planning_msgs::Trajectory &Obstacle::GetPredictedTrajectory() const { return this->trajectory_; }
const bool &Obstacle::IsValidObstacle() const { return this->is_valid_obstacle_; }
const Box2d &Obstacle::BoundingBox() const { return bounding_box_; }
const double &Obstacle::Heading() const { return heading_; }
const double &Obstacle::AngularSpeed() const { return angular_speed_; }
void Obstacle::PredictTrajectory(double predict_horizon, double predict_step) {
trajectory_ = decltype(trajectory_)();
// if (is_static_) {
// trajectory_.trajectory_points.emplace_back();
// auto &trajectory_point = trajectory_.trajectory_points.back();
// trajectory_point.path_point.x = center_.x();
// trajectory_point.path_point.y = center_.y();
// trajectory_point.path_point.s = 0.0;
// trajectory_point.path_point.theta = heading_;
// trajectory_point.path_point.kappa = 0.0;
// trajectory_point.path_point.dkappa = 0.0;
// trajectory_point.relative_time = 0.0;
// trajectory_point.vel = this->speed_;
// trajectory_point.acc = acc_;
// trajectory_point.jerk = 0.0;
// trajectory_point.steer_angle = 0.0;
// } else {
planning_msgs::TrajectoryPoint last_trajectory_point;
last_trajectory_point.path_point.x = this->center_.x();
last_trajectory_point.path_point.y = this->center_.y();
last_trajectory_point.path_point.kappa = 0.0;
last_trajectory_point.path_point.dkappa = 0.0;
last_trajectory_point.path_point.s = 0.0;
last_trajectory_point.path_point.theta = heading_;
last_trajectory_point.vel = speed_;
last_trajectory_point.acc = acc_;
last_trajectory_point.jerk = 0.0;
last_trajectory_point.steer_angle = 0.0;
last_trajectory_point.relative_time = 0.0;
trajectory_.trajectory_points.push_back(last_trajectory_point);
const int kStepSize =
static_cast<int>(predict_horizon / predict_step) < 1 ? 1 : static_cast<int>(predict_horizon / predict_step);
for (int i = 1; i < kStepSize; ++i) {
planning_msgs::TrajectoryPoint trajectory_point;
// trajectory_.trajectory_points.emplace_back();
// auto &trajectory_point = trajectory_.trajectory_points.back();
trajectory_point.path_point.x = last_trajectory_point.path_point.x +
predict_step * last_trajectory_point.vel * std::cos(last_trajectory_point.path_point.theta);
trajectory_point.path_point.y = last_trajectory_point.path_point.y +
predict_step * last_trajectory_point.vel * std::sin(last_trajectory_point.path_point.theta);
trajectory_point.path_point.theta = last_trajectory_point.path_point.theta;
trajectory_point.path_point.kappa = 0.0;
trajectory_point.path_point.dkappa = 0.0;
trajectory_point.relative_time = predict_step * static_cast<double>(i);
trajectory_point.vel = last_trajectory_point.vel;
trajectory_point.acc = 0.0;
trajectory_point.jerk = 0.0;
trajectory_point.steer_angle = 0.0;
double dx = trajectory_point.path_point.x - last_trajectory_point.path_point.x;
double dy = trajectory_point.path_point.y - last_trajectory_point.path_point.y;
double delta_s = std::hypot(dx, dy);
trajectory_point.path_point.s = last_trajectory_point.path_point.s + delta_s;
trajectory_.trajectory_points.push_back(trajectory_point);
last_trajectory_point = trajectory_point;
}
// }
}
Obstacle::Obstacle(const carla_msgs::CarlaTrafficLightInfo &traffic_light_info,
const carla_msgs::CarlaTrafficLightStatus &traffic_light_status)
: id_(traffic_light_info.id), acc_(0.0), centripental_acc_(0.0),
kappa_(0.0), is_static_(true), is_virtual_(true), trajectory_(planning_msgs::Trajectory()),
speed_(0.0), angular_speed_(0.0) {
is_valid_obstacle_ = false;
if (traffic_light_status.state == carla_msgs::CarlaTrafficLightStatus::RED
|| traffic_light_status.state == carla_msgs::CarlaTrafficLightStatus::YELLOW) {
is_valid_obstacle_ = true;
}
double box_length = traffic_light_info.trigger_volume.size.y;
double box_width = traffic_light_info.trigger_volume.size.x;
center_ << traffic_light_info.trigger_volume.center.x, traffic_light_info.trigger_volume.center.y;
heading_ = tf::getYaw(traffic_light_info.transform.orientation) + M_PI_2;
bounding_box_ = common::Box2d(center_, heading_, box_length, box_width);
}
void Obstacle::SetTrajectory(const planning_msgs::Trajectory &trajectory) {
this->trajectory_ = trajectory;
}
}
| 0 | 0.931432 | 1 | 0.931432 | game-dev | MEDIA | 0.356295 | game-dev | 0.983701 | 1 | 0.983701 |
gamingdotme/opensource-casino-v10 | 42,588 | casino/app/Games/BurningRingVS/SlotSettings.php | <?php
namespace VanguardLTE\Games\BurningRingVS
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
public $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_1'] = [
0,
0,
5,
10,
2500,
9000
];
$this->Paytable['SYM_2'] = [
0,
0,
0,
10,
40,
200
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
10,
40,
200
];
$this->Paytable['SYM_4'] = [
0,
0,
2,
20,
80,
800
];
$this->Paytable['SYM_5'] = [
0,
0,
2,
20,
80,
800
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
15,
75,
400
];
$this->Paytable['SYM_7'] = [
0,
0,
2,
5,
20,
500
];
$this->Paytable['SYM_8'] = [
0,
0,
0,
5,
40,
150
];
$this->Paytable['SYM_9'] = [
0,
0,
0,
5,
40,
150
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
5,
20,
100
];
$this->Paytable['SYM_11'] = [
0,
0,
0,
5,
20,
100
];
$this->Paytable['SYM_12'] = [
0,
0,
2,
5,
20,
100
];
$this->Paytable['SYM_13'] = [
0,
0,
0,
5,
20,
100
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
foreach( [
'reelStripBonus1',
'reelStripBonus2',
'reelStripBonus3',
'reelStripBonus4',
'reelStripBonus5',
'reelStripBonus6'
] as $reelStrip )
{
if( count($reel->reelsStripBonus[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStripBonus[$reelStrip];
}
}
foreach( [
'reelStripBonus1',
'reelStripBonus2',
'reelStripBonus3',
'reelStripBonus4',
'reelStripBonus5',
'reelStripBonus6'
] as $reelStrip )
{
if( count($reel->reelsStripBonus[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStripBonus[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 2;
$this->GambleType = 1;
$this->slotFreeCount = 50;
$this->slotFreeMpl = 2;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
3,
5,
7,
9
];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
$i++;
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '7' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 0 | 0.614688 | 1 | 0.614688 | game-dev | MEDIA | 0.422662 | game-dev | 0.72432 | 1 | 0.72432 |
Kneesnap/FrogLord | 6,280 | src/net/highwayfrogs/editor/file/config/exe/LevelInfo.java | package net.highwayfrogs.editor.file.config.exe;
import lombok.Getter;
import lombok.Setter;
import net.highwayfrogs.editor.file.config.data.FroggerMapWorldID;
import net.highwayfrogs.editor.file.vlo.GameImage;
import net.highwayfrogs.editor.games.sony.SCGameFile;
import net.highwayfrogs.editor.games.sony.frogger.FroggerGameInstance;
import net.highwayfrogs.editor.games.sony.frogger.map.FroggerMapLevelID;
import net.highwayfrogs.editor.games.sony.frogger.map.FroggerMapTheme;
import net.highwayfrogs.editor.utils.data.reader.DataReader;
import net.highwayfrogs.editor.utils.data.writer.DataWriter;
/**
* Holds information about each level.
* Created by Kneesnap on 2/1/2019.
*/
public class LevelInfo extends ExeStruct {
@Setter private int level;
@Getter @Setter private FroggerMapWorldID world;
@Getter @Setter private int stackPosition; // 0 = Top of level stack.
private int theme;
@Getter @Setter private int localLevelId; // 0 -> 4 (Level 1 -> 5)
@Getter @Setter private int levelsInWorld; // Number of levels in the world. (Used to calculate size.)
private long worldImageSelectablePointer; // Displayed on the level stack for the given world once unlocked.
private long worldImageVisitedPointer; // Unused.
private long worldImageNotTriedPointer; // Displayed on the level stack for the given world prior to unlock
private long levelTexturePointer; // The screenshot of the level.
private long levelNameTexturePointer; // The level name shown on the level stack.
private long levelNameTextureInGamePointer; // The level name shown in-game.
private static final int RUNTIME_DATA_SIZE = 44;
private static final int TERMINATOR_LEVEL_ID = -1;
public LevelInfo(FroggerGameInstance instance) {
super(instance);
}
@Override
public void load(DataReader reader) {
this.level = reader.readInt();
this.world = FroggerMapWorldID.values()[reader.readInt()];
if (!getConfig().isAtOrBeforeBuild20()) // TODO: Flip these checks so they make more sense. Eg: "isAtLeastBuild21" or "isAfterBuild20".
this.stackPosition = reader.readInt();
if (!getConfig().isAtOrBeforeBuild21())
this.theme = reader.readInt();
this.localLevelId = reader.readInt();
this.levelsInWorld = reader.readInt();
this.worldImageSelectablePointer = reader.readUnsignedIntAsLong();
this.worldImageVisitedPointer = reader.readUnsignedIntAsLong();
this.worldImageNotTriedPointer = reader.readUnsignedIntAsLong();
this.levelTexturePointer = reader.readUnsignedIntAsLong();
this.levelNameTexturePointer = reader.readUnsignedIntAsLong();
this.levelNameTextureInGamePointer = reader.readUnsignedIntAsLong();
reader.skipBytes(RUNTIME_DATA_SIZE);
}
@Override
public void save(DataWriter writer) {
writer.writeInt(this.level);
writer.writeInt(this.world.ordinal());
if (!getConfig().isAtOrBeforeBuild20())
writer.writeInt(this.stackPosition);
if (!getConfig().isAtOrBeforeBuild21())
writer.writeInt(this.theme);
writer.writeInt(this.localLevelId);
writer.writeInt(this.levelsInWorld);
writer.writeUnsignedInt(this.worldImageSelectablePointer);
writer.writeUnsignedInt(this.worldImageVisitedPointer);
writer.writeUnsignedInt(this.worldImageNotTriedPointer);
writer.writeUnsignedInt(this.levelTexturePointer);
writer.writeUnsignedInt(this.levelNameTexturePointer);
writer.writeUnsignedInt(this.levelNameTextureInGamePointer);
writer.writeNull(RUNTIME_DATA_SIZE);
}
@Override
public String toString() {
return "[" + getLevel() + "/" + getWorld() + "] " + getTheme() + " (" + (getLocalLevelId() + 1) + "/" + getLevelsInWorld() + ") [" + getStackPosition() + "]";
}
@Override
public boolean isEntry(SCGameFile<?> file) {
return false;
}
/**
* Gets the MapLevel this info represents.
* @return mapLevel
*/
public FroggerMapLevelID getLevel() {
return isTerminator() ? null : FroggerMapLevelID.values()[this.level];
}
/**
* Gets the MapTheme this info represents.
* @return mapLevel
*/
public FroggerMapTheme getTheme() {
return isTerminator() ? null : FroggerMapTheme.values()[this.theme];
}
/**
* Set the theme of this level.
* @param theme The new theme.
*/
public void setTheme(FroggerMapTheme theme) {
this.theme = theme != null ? theme.ordinal() : -1;
}
/**
* Test if this is a terminator entry.
* @return isTerminator
*/
public boolean isTerminator() {
return this.level == TERMINATOR_LEVEL_ID;
}
/**
* Resolves the image displayed on the level stack for the given world once unlocked.
*/
public GameImage getWorldLevelStackColoredImage() {
return getGameInstance().getImageFromPointer(this.worldImageSelectablePointer);
}
/**
* Resolves an image never displayed on the level stack, which theoretically would have displayed once "visited".
*/
public GameImage getUnusedWorldVisitedImage() {
return getGameInstance().getImageFromPointer(this.worldImageVisitedPointer);
}
/**
* Resolves the image displayed on the level stack for the given world prior to unlock.
*/
public GameImage getWorldNotTriedImage() {
return getGameInstance().getImageFromPointer(this.worldImageNotTriedPointer);
}
/**
* Resolves the preview image screenshot displayed on the level stack.
*/
public GameImage getLevelPreviewScreenshotImage() {
return getGameInstance().getImageFromPointer(this.levelTexturePointer);
}
/**
* Resolves the level name image displayed on the level stack.
*/
public GameImage getLevelNameImage() {
return getGameInstance().getImageFromPointer(this.levelNameTexturePointer);
}
/**
* Resolves the level name image displayed upon completing a level in-game.
*/
public GameImage getIngameLevelNameImage() {
return getGameInstance().getImageFromPointer(this.levelNameTextureInGamePointer);
}
} | 0 | 0.85849 | 1 | 0.85849 | game-dev | MEDIA | 0.97245 | game-dev | 0.962831 | 1 | 0.962831 |
Pulsar4xDevs/Pulsar4x | 48,950 | Pulsar4X/Pulsar4X.Client/Interface/Windows/NavWindow.cs | using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using Pulsar4X.Client.Interface.Widgets;
using Pulsar4X.Engine;
using Pulsar4X.Extensions;
using Pulsar4X.Orbital;
using Pulsar4X.SDL2UI;
using Pulsar4X.SDL2UI.ManuverNodes;
using Vector2 = System.Numerics.Vector2;
using Vector3 = Pulsar4X.Orbital.Vector3;
using Pulsar4X.Factions;
using Pulsar4X.Names;
using Pulsar4X.Orbits;
using Pulsar4X.Storage;
using Pulsar4X.Galaxy;
using Pulsar4X.Movement;
namespace Pulsar4X.ImGuiNetUI.EntityManagement
{
public class NavWindow : PulsarGuiWindow
{
private Entity _orderEntity;
private string _orderEntityName = "";
//OrbitDB _ourOrbit;
private double _sgp;
private KeplerElements? _currentKE;
private NewtonThrustAbilityDB? _newtonThrust;
private double _totalMass;
private double _dryMass;
private double _cargoMass;
private double _fuelMass;
private ICargoable? _fuelType;
private double _totalDV => _newtonThrust?.DeltaV ?? 0;
double _burnRate;
double _exhaustVelocity;
private double _totalDVUsage = 0;
private (Vector3 deltaV, double tSec)[]? _manuvers;
private Manuver[]? _navManuvers;
float _phaseAngleRadians = 0;
private DateTime _minDateTime;
DateTime _atDatetime;
Entity[] _siblingEntities = new Entity[0];
string[] _siblingNames = new string[0];
private int _selectedSibling = -1;
Entity[] _uncleEntites = new Entity[0];
string[] _uncleNames = new string[0];
int _selectedUncle = -1;
private double _truelongTgt; ///The true longitude of the target. Used for hohmann and phasing calcs
private double _truelongInt; ///The true longitude of the interceptor. Used for hohmann and phasing calcs
private int _kRevolutions; ///Number of allowed revolutions of the traget when phasing
private NavWindow(Entity orderEntity)
{
_flags = ImGuiWindowFlags.None;
_orderEntity = orderEntity;
}
private ManuverLinesComplete _manuverLines = new ManuverLinesComplete();
public static NavWindow GetInstance(EntityState orderEntity)
{
NavWindow thisitem;
if (!_uiState.LoadedWindows.ContainsKey(typeof(NavWindow)))
{
thisitem = new NavWindow(orderEntity.Entity);
thisitem.HardRefresh(orderEntity);
thisitem.OnSystemTickChange(_uiState.SelectedSystemTime);
}
else
{
thisitem = (NavWindow)_uiState.LoadedWindows[typeof(NavWindow)];
if (thisitem._orderEntity != orderEntity.Entity)
{
thisitem._orderEntity = orderEntity.Entity;
thisitem.HardRefresh(orderEntity);
thisitem.OnSystemTickChange(_uiState.SelectedSystemTime);
}
}
return thisitem;
}
private void HardRefresh(EntityState orderEntity)
{
_orderEntity = orderEntity.Entity;
_orderEntityName = _orderEntity.GetName(_uiState.Faction.Id);
_newtonThrust = _orderEntity.GetDataBlob<NewtonThrustAbilityDB>();
_totalMass = _orderEntity.GetDataBlob<MassVolumeDB>().MassTotal;
_dryMass = _orderEntity.GetDataBlob<MassVolumeDB>().MassDry;
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null)
throw new NullReferenceException();
var parentMass = soiParent.GetDataBlob<MassVolumeDB>().MassTotal;
_sgp = GeneralMath.StandardGravitationalParameter(_totalMass + parentMass);
var fuelTypeID = _newtonThrust.FuelType;
_fuelType = _uiState.Faction.GetDataBlob<FactionInfoDB>().Data.CargoGoods.GetAny(fuelTypeID);
_burnRate = _newtonThrust.FuelBurnRate;
_exhaustVelocity = _newtonThrust.ExhaustVelocity;
_siblingEntities = soiParent.GetDataBlob<PositionDB>().Children.ToArray();
List<string> names = new List<string>();
foreach (var entity in _siblingEntities)
{
//TODO: this is going to show *all* entities, not just the ones this faction can see.
//going to need to come up with a way to get this data. (filtering for this should be done in the engine not ui)
string name = entity.GetDataBlob<NameDB>().GetName(_orderEntity.FactionOwnerID);
names.Add(name);
}
_siblingNames = names.ToArray();
var soiGrandparent = soiParent.GetSOIParentEntity();
if(soiParent == _orderEntity.GetDataBlob<PositionDB>().Root || soiGrandparent == null)
_uncleEntites = new Entity[0];
else
{
_uncleEntites = soiGrandparent.GetDataBlob<PositionDB>().Children.ToArray();
}
names = new List<string>();
foreach (var entity in _uncleEntites)
{
string name = entity.GetDataBlob<NameDB>().GetName(_orderEntity.FactionOwnerID);
names.Add(name);
}
_uncleNames = names.ToArray();
OnSystemTickChange(orderEntity.Entity.StarSysDateTime);
_uiState.SelectedSysMapRender?.SelectedEntityExtras.Add(_manuverLines);
var soiParentPosition = MoveMath.GetSOIParentPositionDB(_orderEntity);
if(soiParentPosition == null)
throw new NullReferenceException();
_manuverLines.RootSequence.ParentPosition = soiParentPosition;
}
public override void OnSystemTickChange(DateTime newDate)
{
_minDateTime = newDate;
if (_atDatetime < _minDateTime)
_atDatetime = _minDateTime;
if (_orderEntity.HasDataBlob<OrbitDB>())
_currentKE = _orderEntity.GetDataBlob<OrbitDB>().GetElements();
else if (_orderEntity.HasDataBlob<OrbitUpdateOftenDB>())
_currentKE = _orderEntity.GetDataBlob<OrbitUpdateOftenDB>().GetElements();
else if (_orderEntity.HasDataBlob<OrbitDB>())
_currentKE = _orderEntity.GetDataBlob<NewtonMoveDB>().GetElements();
if (_targetSMA == 0 && _currentKE != null)
_targetSMA = (float)_currentKE.Value.SemiMajorAxis;
_totalMass = _orderEntity.GetDataBlob<MassVolumeDB>().MassTotal;
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null)
throw new NullReferenceException();
var parentMass = soiParent.GetDataBlob<MassVolumeDB>().MassTotal;
_sgp = GeneralMath.StandardGravitationalParameter(_totalMass + parentMass);
_cargoMass = _orderEntity.GetDataBlob<CargoStorageDB>().TotalStoredMass;
if(_fuelType == null)
throw new NullReferenceException();
_fuelMass = _orderEntity.GetDataBlob<CargoStorageDB>().GetMassStored(_fuelType, false);
}
enum NavMode
{
None,
Edit,
Thrust,
HohmannTransfer,
HohmannTransfer2,
HohmannTransferOE,
InterplanetaryTransfer,
PhaseChange,
Phasing,
HighDVIntercept,
PorkChopPlot,
EscapeSOI
}
private NavMode _navMode = NavMode.None;
private string[] nodenames = new string[0];
private int _selectedNode = 0;
private float _radialDV;
private float _progradeDV;
private int _indentAmount = 4;
private int _indentDepth = 0;
private int indent
{
get { return _indentAmount * (_indentDepth); }
}
void ManuverTree(ManuverSequence mseq)
{
if (ImGui.Selectable(mseq.SequenceName))
{
_navMode = NavMode.None;
_manuverLines.SelectedSequence = mseq;
}
ImGui.Indent(indent);
foreach (var mnode in mseq.ManuverNodes)
{
if (ImGui.Selectable(mnode.NodeName))
{
_navMode = NavMode.Edit;
_manuverLines.EditingNodes = new ManuverNode[1];
_manuverLines.EditingNodes[0] = mnode;
_progradeDV = (float)mnode.Prograde;
_radialDV = (float)mnode.Radial;
_atDatetime = mnode.NodeTime;
}
}
ImGui.Unindent();
ImGui.Indent(indent);
foreach (var seq in mseq.ManuverSequences)
{
ManuverTree(seq);
}
ImGui.Unindent(indent);
}
internal override void Display()
{
var soiParentPosition = MoveMath.GetSOIParentPositionDB(_orderEntity);
if (!IsActive || soiParentPosition == null)
return;
ImGui.SetNextWindowSize(new Vector2(600f, 400f), ImGuiCond.FirstUseEver);
if (Window.Begin("Nav Control: " + _orderEntityName, ref IsActive, _flags))
{
ImGui.Columns(2);
ManuverTree(_manuverLines.RootSequence);
ImGui.NextColumn();
if (_navMode == NavMode.None)
{
if (ImGui.Button("Manual Thrust"))
{
_manuverLines.AddNewEditNode(_orderEntity, _atDatetime);
_navMode = NavMode.Thrust;
}
if (ImGui.Button("Hohmann Transfer"))
{
_manuverLines.EditingNodes = new ManuverNode[2];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
var halfOrbit = _manuverLines.EditingNodes[0].TargetOrbit.Period * 0.5;
_manuverLines.EditingNodes[1] = new ManuverNode(_orderEntity, _atDatetime + TimeSpan.FromSeconds(halfOrbit));
_manuverLines.RootSequence.ParentPosition = soiParentPosition;
_navMode = NavMode.HohmannTransfer;
}
if (ImGui.Button("Hohmann Transfer2"))
{
_manuverLines.EditingNodes = new ManuverNode[2];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
var halfOrbit = _manuverLines.EditingNodes[0].TargetOrbit.Period * 0.5;
_manuverLines.EditingNodes[1] = new ManuverNode(_orderEntity, _atDatetime + TimeSpan.FromSeconds(halfOrbit));
_manuverLines.RootSequence.ParentPosition = soiParentPosition;
_navMode = NavMode.HohmannTransfer2;
}
if (ImGui.Button("Hohmann TransferOE"))
{
_manuverLines.EditingNodes = new ManuverNode[2];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
var halfOrbit = _manuverLines.EditingNodes[0].TargetOrbit.Period * 0.5;
_manuverLines.EditingNodes[1] = new ManuverNode(_orderEntity, _atDatetime + TimeSpan.FromSeconds(halfOrbit));
_manuverLines.RootSequence.ParentPosition = soiParentPosition;
_navMode = NavMode.HohmannTransferOE;
}
if (ImGui.Button("Interplanetary Transfer"))
{
_navMode = NavMode.InterplanetaryTransfer;
}
if (ImGui.Button("Phase Change"))
{
_manuverLines.EditingNodes = new ManuverNode[2];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
var halfOrbit = _manuverLines.EditingNodes[0].TargetOrbit.Period * 0.5;
_manuverLines.EditingNodes[1] = new ManuverNode(_orderEntity, _atDatetime + TimeSpan.FromSeconds(halfOrbit));
_navMode = NavMode.PhaseChange;
}
if (ImGui.Button("Phase Change 2"))
{
_manuverLines.EditingNodes = new ManuverNode[2];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
var halfOrbit = _manuverLines.EditingNodes[0].TargetOrbit.Period * 0.5;
_manuverLines.EditingNodes[1] = new ManuverNode(_orderEntity, _atDatetime + TimeSpan.FromSeconds(halfOrbit));
_navMode = NavMode.Phasing;
}
if (ImGui.Button("High Δv Intercept"))
{
_navMode = NavMode.HighDVIntercept;
}
if (ImGui.Button("Porkchop Plot"))
{
_navMode = NavMode.PorkChopPlot;
}
if (ImGui.Button("Escape SOI"))
{
_manuverLines.EditingNodes = new ManuverNode[1];
_manuverLines.EditingNodes[0] = new ManuverNode(_orderEntity, _atDatetime);
_navMode = NavMode.EscapeSOI;
}
}
switch (_navMode)
{
case NavMode.Edit:
DisplayEditMode();
break;
case NavMode.Thrust:
DisplayThrustMode();
break;
case NavMode.PhaseChange:
DisplayPhaseChangeMode();
break;
case NavMode.Phasing:
DisplayPhasing();
break;
case NavMode.HohmannTransfer:
DisplayHohmannMode();
break;
case NavMode.HohmannTransfer2:
DisplayHohmannMode2();
break;
case NavMode.HohmannTransferOE:
DisplayHohmannModeOE();
break;
case NavMode.InterplanetaryTransfer:
DisplayInterPlanetaryHohmannMode();
break;
case NavMode.EscapeSOI:
DisplayEscapeSOI();
break;
case NavMode.None:
break;
default:
break;
}
ImGui.Columns(1);
ImGui.NewLine();
ImGui.Text("Availible Δv: " + Stringify.Velocity(_totalDV));
ImGui.Text("Dry Mass:" + Stringify.Mass(_dryMass, "0.######"));
ImGui.Text("Total Mass: " + Stringify.Mass(_totalMass));
ImGui.Text("Non Fuel Cargo: " + Stringify.Mass(_cargoMass - _fuelMass));
var fuelName = _fuelType?.Name ?? "Unknown";
ImGui.Text(fuelName + " Fuel: " + Stringify.Mass(_fuelMass));
var thrust = _newtonThrust?.ThrustInNewtons ?? 0;
ImGui.Text("Total Thrust: " + Stringify.Thrust(thrust));
Window.End();
}
}
void DisplayEditMode()
{
bool changes = false;
float maxprogradeDV = (float)(_totalDV - Math.Abs(_radialDV));
float maxradialDV = (float)(_totalDV - Math.Abs(_progradeDV));
double tseconds = 0;
if (ImGui.Button("-1##pg"))
{
_progradeDV -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##pg"))
{
_progradeDV += 1;
changes = true;
}ImGui.SameLine();
if (ImGui.SliderFloat("Prograde Δv", ref _progradeDV, -maxprogradeDV, maxprogradeDV))
{
//Calcs();
changes = true;
}
if (ImGui.Button("-1##rd"))
{
_radialDV -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##rd"))
{
_radialDV += 1;
changes = true;
} ImGui.SameLine();
if (ImGui.SliderFloat("Radial Δv", ref _radialDV, -maxradialDV, maxradialDV))
{
changes = true;
}
ImGui.Text("Time: " + _atDatetime); //ImGui.SameLine();
if (ImGui.Button("-1##t"))
{
_atDatetime -= TimeSpan.FromSeconds(1);
tseconds -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##t"))
{
_atDatetime += TimeSpan.FromSeconds(1);
tseconds += 1;
changes = true;
} ImGui.SameLine();
var halfPeriod = _manuverLines.EditingNodes[0].PriorOrbit.Period * .5;
if (ImGui.Button("-Apsis##t"))
{
_atDatetime -= TimeSpan.FromSeconds(halfPeriod);
tseconds -= halfPeriod;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+Apsis##t"))
{
_atDatetime -= TimeSpan.FromSeconds(halfPeriod);
tseconds += halfPeriod;
changes = true;
} ImGui.SameLine();
if (changes)
{
_manuverLines.ManipulateNode(0, _progradeDV, _radialDV, tseconds);
}
if (_uiState.SelectedSysMapRender != null && !_uiState.SelectedSysMapRender.SelectedEntityExtras.Contains(_manuverLines))
_uiState.SelectedSysMapRender.SelectedEntityExtras.Add(_manuverLines);
if(_orderEntity.Manager == null)
throw new NullReferenceException();
var deltat = _manuverLines.EditingNodes[0].NodeTime - _orderEntity.Manager.StarSysDateTime;
ImGui.Text("node in: " + deltat);
//if (ImGui.Button("Make it so")) { }
}
void DisplayThrustMode()
{
bool changes = false;
float maxprogradeDV = (float)(_totalDV - Math.Abs(_radialDV));
float maxradialDV = (float)(_totalDV - Math.Abs(_progradeDV));
double tseconds = 0;
if (ImGui.Button("-1##pg"))
{
_progradeDV -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##pg"))
{
_progradeDV += 1;
changes = true;
}ImGui.SameLine();
if (ImGui.SliderFloat("Prograde Δv", ref _progradeDV, -maxprogradeDV, maxprogradeDV))
{
changes = true;
}
if (ImGui.Button("-1##rd"))
{
_radialDV -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##rd"))
{
_radialDV += 1;
changes = true;
} ImGui.SameLine();
if (ImGui.SliderFloat("Radial Δv", ref _radialDV, -maxradialDV, maxradialDV))
{
changes = true;
}
ImGui.Text("Time: " + _atDatetime); //ImGui.SameLine();
if (ImGui.Button("-1##t"))
{
_atDatetime -= TimeSpan.FromSeconds(1);
tseconds -= 1;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+1##t"))
{
_atDatetime += TimeSpan.FromSeconds(1);
tseconds += 1;
changes = true;
}
ImGui.SameLine();
var halfPeriod = _manuverLines.EditingNodes[0].PriorOrbit.Period * .5;
if (ImGui.Button("-Apsis##t"))
{
_atDatetime -= TimeSpan.FromSeconds(halfPeriod);
tseconds -= halfPeriod;
changes = true;
} ImGui.SameLine();
if (ImGui.Button("+Apsis##t"))
{
_atDatetime -= TimeSpan.FromSeconds(halfPeriod);
tseconds += halfPeriod;
changes = true;
} //ImGui.SameLine();
if (changes)
{
_manuverLines.ManipulateNode(0, _progradeDV, _radialDV, tseconds);
tseconds = 0;
}
ImGui.Text(_progradeDV.ToString());
ImGui.Text(_radialDV.ToString());
ImGui.Text(_manuverLines.EditingNodes[0].TargetOrbit.Eccentricity.ToString());
ImGui.Text(_manuverLines.EditingNodes[0].TargetOrbit.SemiMajorAxis.ToString());
ImGui.Text(_manuverLines.EditingNodes[0].TargetOrbit.SemiMinorAxis.ToString());
ImGui.Text(_manuverLines.EditingNodes[0].TargetOrbit.LoAN.ToString());
ImGui.Text(_manuverLines.EditingNodes[0].TargetOrbit.AoP.ToString());
if (_uiState.SelectedSysMapRender != null && !_uiState.SelectedSysMapRender.SelectedEntityExtras.Contains(_manuverLines))
_uiState.SelectedSysMapRender.SelectedEntityExtras.Add(_manuverLines);
if(_orderEntity.Manager == null)
throw new NullReferenceException();
var deltat = _manuverLines.EditingNodes[0].NodeTime - _orderEntity.Manager.StarSysDateTime;
ImGui.Text("node in: " + deltat);
if (ImGui.Button("Make it so"))
{
_manuverLines.EditingNodes[0].NodeName = "Thrust";
_manuverLines.AddSequence("Thrust Manuver");
_navMode = NavMode.None;
}
}
void DisplayPhaseChangeMode()
{
ImGui.SliderAngle("PhaseAngle", ref _phaseAngleRadians);
if(_currentKE == null)
throw new NullReferenceException();
_manuvers = InterceptCalcs.OrbitPhasingManuvers(_currentKE.Value, _sgp, _atDatetime, _phaseAngleRadians);
double totalManuverDV = 0;
foreach (var manuver in _manuvers)
{
ImGui.Text(manuver.deltaV.Length() + "Δv");
totalManuverDV += manuver.deltaV.Length();
ImGui.Text("Seconds: " + manuver.tSec);
}
ImGui.Text("Total Δv");
ImGui.SameLine();
ImGui.Text("for all manuvers: " + Stringify.Velocity(totalManuverDV));
if (ImGui.Button("Make it so"))
{
double fuelBurned1 = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, _manuvers[0].deltaV.Length());
double secondsBurn1 = fuelBurned1 / _burnRate;
var manuverNodeTime1 = _atDatetime + TimeSpan.FromSeconds(secondsBurn1 * 0.5);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime1, _manuvers[0].deltaV, secondsBurn1);
if(_fuelType == null)
throw new NullReferenceException();
double mass2 = _totalMass - (fuelBurned1 * _fuelType.MassPerUnit);
double fuelBurned2 = OrbitMath.TsiolkovskyFuelUse(mass2, _exhaustVelocity, _manuvers[1].deltaV.Length());
double secondsBurn2 = fuelBurned2 / _burnRate;
var manuverNodeTime2 = manuverNodeTime1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime2, _manuvers[1].deltaV, secondsBurn2);
}
}
void DisplayPhasing()
{
var soiParent = _orderEntity.GetSOIParentEntity();
if (soiParent == null || _currentKE == null)
throw new NullReferenceException();
double mySMA = _currentKE.Value.SemiMajorAxis;
ImGui.SliderAngle("PhaseAngle", ref _phaseAngleRadians);
ImGui.SliderInt("Revolutions", ref _kRevolutions, 1, 10);
if (_currentKE == null)
throw new NullReferenceException();
// _manuvers = OrbitalMath.Phasing(_sgp, lowestOrbit, _phaseAngleRadians, _currentKE.Value, 0, _kRevolutions);
double totalManuverDV = 0;
if(_manuvers != null)
{
foreach (var manuver in _manuvers)
{
ImGui.Text(manuver.deltaV.Length() + "Δv");
totalManuverDV += manuver.deltaV.Length();
ImGui.Text("Seconds: " + manuver.tSec);
}
}
ImGui.Text("Total Δv");
ImGui.SameLine();
ImGui.Text("for all manuvers: " + Stringify.Velocity(totalManuverDV));
if (ImGui.Button("Make it so"))
{
double fuelBurned1 = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, _manuvers[0].deltaV.Length());
double secondsBurn1 = fuelBurned1 / _burnRate;
var manuverNodeTime1 = _atDatetime + TimeSpan.FromSeconds(secondsBurn1 * 0.5);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime1, _manuvers[0].deltaV, secondsBurn1);
if (_fuelType == null)
throw new NullReferenceException();
double mass2 = _totalMass - (fuelBurned1 * _fuelType.MassPerUnit);
double fuelBurned2 = OrbitMath.TsiolkovskyFuelUse(mass2, _exhaustVelocity, _manuvers[1].deltaV.Length());
double secondsBurn2 = fuelBurned2 / _burnRate;
var manuverNodeTime2 = manuverNodeTime1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime2, _manuvers[1].deltaV, secondsBurn2);
}
}
private float _targetSMA = 0;
void DisplayHohmannMode()
{
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null || _currentKE == null)
throw new NullReferenceException();
double mySMA = _currentKE.Value.SemiMajorAxis;
float smaMin = 1;
float smaMax = (float)soiParent.GetSOI_m();
if(ImGui.Combo("Target Object", ref _selectedSibling, _siblingNames, _siblingNames.Length ))
{
Entity selectedSib = _siblingEntities[_selectedSibling];
if(selectedSib.HasDataBlob<OrbitDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<OrbitUpdateOftenDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitUpdateOftenDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<NewtonMoveDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<NewtonMoveDB >().GetElements().SemiMajorAxis;
}
//TODO this should be radius from orbiting body not major axies.
ImGui.SliderFloat("Target SemiMajorAxis", ref _targetSMA, smaMin, smaMax);
_manuvers = OrbitalMath.Hohmann2(_sgp, mySMA, _targetSMA);
double totalManuverDV = 0;
foreach (var manuver in _manuvers)
{
var dv = manuver.deltaV.Length();
totalManuverDV += dv;
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, dv);
double secondsBurn = fuelBurned / _burnRate;
ImGui.Text(dv + "Δv");
ImGui.Text(fuelBurned + " fuel");
ImGui.Text(Stringify.Quantity(secondsBurn, "0.###") + " Second Burn");
}
if(totalManuverDV > _totalDV)
ImGui.TextColored(new Vector4(0.9f, 0, 0, 1), "Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
else
ImGui.Text("Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
if(totalManuverDV > 0)
{
DateTime t1 = _orderEntity.StarSysDateTime + TimeSpan.FromSeconds(_manuvers[0].tSec);
DateTime t2 = t1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
_manuverLines.EditingNodes[0].SetNode(_manuvers[0].deltaV, t1 );
_manuverLines.EditingNodes[1].PriorOrbit = _manuverLines.EditingNodes[0].TargetOrbit;
_manuverLines.EditingNodes[1].SetNode(_manuvers[1].deltaV, t2);
}
if (ImGui.Button("Make it so"))
{
double fuelBurned1 = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, _manuvers[0].deltaV.Length());
double secondsBurn1 = fuelBurned1 / _burnRate;
var manuverNodeTime1 = _atDatetime + TimeSpan.FromSeconds(secondsBurn1 * 0.5);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime1, _manuvers[0].deltaV, secondsBurn1);
if(_fuelType == null)
throw new NullReferenceException();
double mass2 = _totalMass - (fuelBurned1 * _fuelType.MassPerUnit);
double fuelBurned2 = OrbitMath.TsiolkovskyFuelUse(mass2, _exhaustVelocity, _manuvers[1].deltaV.Length());
double secondsBurn2 = fuelBurned2 / _burnRate;
var manuverNodeTime2 = manuverNodeTime1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime2, _manuvers[1].deltaV, secondsBurn2);
var newseq = new ManuverSequence();
newseq.SequenceName = "Hohmann Transfer";
_manuverLines.EditingNodes[0].NodeName = "Raise Periapsis";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[0]);
_manuverLines.EditingNodes[1].NodeName = "Circularise";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[1]);
_manuverLines.SelectedSequence.ManuverSequences.Add(newseq);
}
}
void DisplayHohmannMode2()
{
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null || _currentKE == null)
throw new NullReferenceException();
double mySMA = _currentKE.Value.SemiMajorAxis;
float smaMin = 1;
float smaMax = (float)soiParent.GetSOI_m();
if(ImGui.Combo("Target Object", ref _selectedSibling, _siblingNames, _siblingNames.Length ))
{
Entity selectedSib = _siblingEntities[_selectedSibling];
if(selectedSib.HasDataBlob<OrbitDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<OrbitUpdateOftenDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitUpdateOftenDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<NewtonMoveDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<NewtonMoveDB >().GetElements().SemiMajorAxis;
}
//TODO this should be radius from orbiting body not major axies.
ImGui.SliderFloat("Target SemiMajorAxis", ref _targetSMA, smaMin, smaMax);
_manuvers = OrbitalMath.Hohmann2(_sgp, mySMA, _targetSMA);
double totalManuverDV = 0;
int i = 0;
foreach (var manuver in _manuvers)
{
var time = manuver.tSec;
var dv = manuver.deltaV.Length();
totalManuverDV += dv;
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, dv);
double burnTime = fuelBurned / _burnRate;
ImGui.Text("Burn # " + i);
ImGui.Text(time + "time");
ImGui.Text(dv + "Δv");
ImGui.Text(fuelBurned + " fuel");
ImGui.Text(Stringify.Quantity(burnTime, "0.###") + " Seconds of Burn");
i++;
}
if(totalManuverDV > _totalDV)
ImGui.TextColored(new Vector4(0.9f, 0, 0, 1), "Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
else
ImGui.Text("Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
if(totalManuverDV > 0)
{
DateTime t1 = _orderEntity.StarSysDateTime + TimeSpan.FromSeconds(_manuvers[0].tSec);
DateTime t2 = t1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
_manuverLines.EditingNodes[0].SetNode(_manuvers[0].deltaV, t1 );
_manuverLines.EditingNodes[1].PriorOrbit = _manuverLines.EditingNodes[0].TargetOrbit;
_manuverLines.EditingNodes[1].SetNode(_manuvers[1].deltaV, t2);
}
if (ImGui.Button("Make it so"))
{
double fuelBurned1 = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, _manuvers[0].deltaV.Length());
double secondsBurn1 = fuelBurned1 / _burnRate;
var manuverNodeTime1 = _atDatetime + TimeSpan.FromSeconds(secondsBurn1 * 0.5);
var startObt = _manuverLines.EditingNodes[0].PriorOrbit;
var tgtObt = _manuverLines.EditingNodes[0].TargetOrbit;
NewtonSimpleCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime1, startObt, tgtObt );
if(_fuelType == null)
throw new NullReferenceException();
double mass2 = _totalMass - (fuelBurned1 * _fuelType.MassPerUnit);
double fuelBurned2 = OrbitMath.TsiolkovskyFuelUse(mass2, _exhaustVelocity, _manuvers[1].deltaV.Length());
double secondsBurn2 = fuelBurned2 / _burnRate;
var manuverNodeTime2 = manuverNodeTime1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
startObt = _manuverLines.EditingNodes[1].PriorOrbit;
tgtObt = _manuverLines.EditingNodes[1].TargetOrbit;
NewtonSimpleCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime2, startObt, tgtObt );
var newseq = new ManuverSequence();
newseq.SequenceName = "Hohmann Transfer";
_manuverLines.EditingNodes[0].NodeName = "Raise Periapsis";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[0]);
_manuverLines.EditingNodes[1].NodeName = "Circularise";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[1]);
_manuverLines.SelectedSequence.ManuverSequences.Add(newseq);
}
}
void DisplayHohmannModeOE()
{
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null || _currentKE == null)
throw new NullReferenceException();
double intSMA = _currentKE.Value.SemiMajorAxis;
double trueanomInt =0.0;
double trueanomTgt =0.0;
double lopInt =0.0;
double lopTgt =0.0;
float smaMin = 1;
float smaMax = (float)soiParent.GetSOI_m();
if(ImGui.Combo("Target Object", ref _selectedSibling, _siblingNames, _siblingNames.Length ))
{
Entity selectedSib = _siblingEntities[_selectedSibling];
var TgtOrbitDB = _siblingEntities[_selectedSibling].GetDataBlob<OrbitDB>();
var IntOrbitDB = _orderEntity.GetDataBlob<OrbitDB>();
if(selectedSib.HasDataBlob<OrbitDB>())
_targetSMA = (float)TgtOrbitDB.SemiMajorAxis;
if(selectedSib.HasDataBlob<OrbitUpdateOftenDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitUpdateOftenDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<NewtonMoveDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<NewtonMoveDB >().GetElements().SemiMajorAxis;
trueanomTgt = OrbitMath.GetTrueAnomaly(TgtOrbitDB,_atDatetime);
trueanomInt = OrbitMath.GetTrueAnomaly(IntOrbitDB,_atDatetime);
lopTgt = OrbitMath.GetLongditudeOfPeriapsis(TgtOrbitDB.Inclination, TgtOrbitDB.ArgumentOfPeriapsis, TgtOrbitDB.LongitudeOfAscendingNode);
lopInt = OrbitMath.GetLongditudeOfPeriapsis(IntOrbitDB.Inclination, IntOrbitDB.ArgumentOfPeriapsis, IntOrbitDB.LongitudeOfAscendingNode);
_truelongTgt = trueanomTgt + lopTgt;
_truelongInt = trueanomInt + lopInt;
}
//TODO this should be radius from orbiting body not major axies.
ImGui.SliderFloat("Target SemiMajorAxis", ref _targetSMA, smaMin, smaMax);
_manuvers = OrbitalMath.HohmannOE(_sgp, intSMA, _truelongInt, _targetSMA, _truelongTgt);
double totalManuverTime = 0;
double totalManuverDV = 0;
int i = 0;
foreach (var manuver in _manuvers)
{
var time = manuver.tSec;
var dv = manuver.deltaV.Length();
totalManuverTime += time;
totalManuverDV += dv;
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, dv);
double burnTime = fuelBurned / _burnRate;
ImGui.Text("Burn # " + i);
ImGui.Text(time + "time");
ImGui.Text(dv + "Δv");
ImGui.Text(fuelBurned + " fuel");
ImGui.Text(Stringify.Quantity(burnTime, "0.###") + " Seconds of Burn");
i++;
}
if(totalManuverDV > _totalDV)
ImGui.TextColored(new Vector4(0.9f, 0, 0, 1), "Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
else
ImGui.Text("Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
if(totalManuverDV > 0)
{
DateTime t1 = _orderEntity.StarSysDateTime + TimeSpan.FromSeconds(_manuvers[0].tSec);
DateTime t2 = t1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
_manuverLines.EditingNodes[0].SetNode(_manuvers[0].deltaV, t1 );
_manuverLines.EditingNodes[1].PriorOrbit = _manuverLines.EditingNodes[0].TargetOrbit;
_manuverLines.EditingNodes[1].SetNode(_manuvers[1].deltaV, t2);
}
if (ImGui.Button("Make it so"))
{
var mvr = OrbitalMath.HohmannOE2(_sgp, intSMA, _truelongInt, _targetSMA, _truelongTgt);
var timeAtFirstManuver = _atDatetime + TimeSpan.FromSeconds(mvr[0, 1]);
var timeAtSecondManuver = _atDatetime + TimeSpan.FromSeconds(mvr[0, 3]);
KeplerElements transferOrbit = new KeplerElements()
{
SemiMajorAxis = mvr[1,0],
Eccentricity = mvr[1,1],
LoAN = mvr[1,2],
AoP = 0,
Inclination = 0,
StandardGravParameter = _sgp
};
Manuver navManuver = new Manuver()
{
TypeOfManuver = Manuver.ManuverType.NewtonSimple,
StartDateTime = timeAtFirstManuver,
StartSOIParent = soiParent,
StartKepler = (KeplerElements)_currentKE,
EndSOIParent = _siblingEntities[_selectedSibling],
EndKepler = transferOrbit,
EndDateTime = timeAtSecondManuver
};
NavSequenceCommand.CreateNewCommand(_orderEntity, navManuver);
/*
double fuelBurned1 = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, _manuvers[0].deltaV.Length());
double secondsBurn1 = fuelBurned1 / _burnRate;
var manuverNodeTime1 = _atDatetime + TimeSpan.FromSeconds(secondsBurn1 * 0.5);
var startObt = _manuverLines.EditingNodes[0].PriorOrbit;
var tgtObt = _manuverLines.EditingNodes[0].TargetOrbit;
NewtonSimpleCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime1, startObt, tgtObt );
if(_fuelType == null)
throw new NullReferenceException();
double mass2 = _totalMass - (fuelBurned1 * _fuelType.MassPerUnit);
double fuelBurned2 = OrbitMath.TsiolkovskyFuelUse(mass2, _exhaustVelocity, _manuvers[1].deltaV.Length());
double secondsBurn2 = fuelBurned2 / _burnRate;
var manuverNodeTime2 = manuverNodeTime1 + TimeSpan.FromSeconds(_manuvers[1].tSec);
startObt = _manuverLines.EditingNodes[1].PriorOrbit;
tgtObt = _manuverLines.EditingNodes[1].TargetOrbit;
NewtonSimpleCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime2, startObt, tgtObt );
var newseq = new ManuverSequence();
newseq.SequenceName = "Hohmann Transfer";
_manuverLines.EditingNodes[0].NodeName = "Raise Periapsis";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[0]);
_manuverLines.EditingNodes[1].NodeName = "Circularise";
newseq.ManuverNodes.Add(_manuverLines.EditingNodes[1]);
_manuverLines.SelectedSequence.ManuverSequences.Add(newseq);
*/
}
}
void DisplayInterPlanetaryHohmannMode()
{
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null || _currentKE == null)
throw new NullReferenceException();
double mySMA = _currentKE.Value.SemiMajorAxis;
float smaMax = (float)soiParent.GetSOI_m();
if (ImGui.Combo("Target Object", ref _selectedUncle, _uncleNames, _uncleNames.Length))
{
Entity selectedUnc = _uncleEntites[_selectedUncle];
if (selectedUnc.HasDataBlob<OrbitDB>())
_targetSMA = (float)_uncleEntites[_selectedUncle].GetDataBlob<OrbitDB>().SemiMajorAxis;
if (selectedUnc.HasDataBlob<OrbitUpdateOftenDB>())
_targetSMA = (float)_uncleEntites[_selectedUncle].GetDataBlob<OrbitUpdateOftenDB>().SemiMajorAxis;
if (selectedUnc.HasDataBlob<NewtonMoveDB>())
_targetSMA = (float)_uncleEntites[_selectedUncle].GetDataBlob<NewtonMoveDB>().GetElements().SemiMajorAxis;
}
//TODO this should be radius from orbiting body not major axies.
//ImGui.SliderFloat("Target SemiMajorAxis", ref _targetSMA, smaMin, smaMax);
if(_selectedUncle > -1)
{
_manuvers = InterceptCalcs.InterPlanetaryHohmann(soiParent, _uncleEntites[_selectedUncle], _orderEntity);
double totalManuverDV = 0;
foreach (var manuver in _manuvers)
{
var dv = manuver.deltaV.Length();
totalManuverDV += dv;
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, dv);
double secondsBurn = fuelBurned / _burnRate;
ImGui.Text(dv + "Δv");
ImGui.Text(fuelBurned + " fuel");
ImGui.Text(Stringify.Quantity(secondsBurn, "0.###") + " Second Burn");
}
if (totalManuverDV > _totalDV)
ImGui.TextColored(new Vector4(0.9f, 0, 0, 1), "Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
else
ImGui.Text("Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
if (ImGui.Button("Make it so"))
{
var date = _atDatetime;
var mass = _totalMass;
foreach (var manuver in _manuvers)
{
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(mass, _exhaustVelocity, manuver.deltaV.Length());
double secondsBurn = fuelBurned / _burnRate;
date += TimeSpan.FromSeconds(manuver.tSec);
var manuverNodeTime = date + TimeSpan.FromSeconds(secondsBurn * 0.5);
mass -= fuelBurned;
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverNodeTime, manuver.deltaV, secondsBurn);
}
}
}
}
void DisplayHighDVIntercept()
{
if(ImGui.Combo("Target Object", ref _selectedSibling, _siblingNames, _siblingNames.Length ))
{
Entity selectedSib = _siblingEntities[_selectedSibling];
if(selectedSib.HasDataBlob<OrbitDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<OrbitUpdateOftenDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<OrbitUpdateOftenDB>().SemiMajorAxis;
if(selectedSib.HasDataBlob<NewtonMoveDB>())
_targetSMA = (float)_siblingEntities[_selectedSibling].GetDataBlob<NewtonMoveDB >().GetElements().SemiMajorAxis;
}
}
private bool _EscapeVelocityHigh = true;
void DisplayEscapeSOI()
{
var period = _orderEntity.GetDataBlob<OrbitDB>().OrbitalPeriod.TotalSeconds;
var orbitDB = _orderEntity.GetDataBlob<OrbitDB>();
var soiParent = _orderEntity.GetSOIParentEntity();
if(soiParent == null || _currentKE == null)
throw new NullReferenceException();
var parentState = MoveMath.GetRelativeState(soiParent);
var parentAngle = Math.Atan2(parentState.pos.Y, parentState.pos.X);
double orbitalPeriod = orbitDB.OrbitalPeriod.TotalSeconds;
double e = orbitDB.Eccentricity;
var wc1 = Math.Sqrt((1 - e) / (1 + e));
var wc2 = Math.Tan(parentAngle / 2);
double E = 2 * Math.Atan(wc1 * wc2);
double wc3 = orbitalPeriod / (Math.PI * 2);
double wc4 = E - e * Math.Sin(E);
double phaseTime = wc3 * wc4;
Switch.Switch2State("Escape:", ref _EscapeVelocityHigh, "Low", "High");
double secondsToManuver = phaseTime;
if (!_EscapeVelocityHigh)
secondsToManuver += period * 0.5;
double mySMA = _currentKE.Value.SemiMajorAxis;
//double escapeSMA =
var manuverDateTime = _atDatetime + TimeSpan.FromSeconds(secondsToManuver);
var manuverPos = MoveMath.GetRelativeFuturePosition(_orderEntity,manuverDateTime);
var manuverVel = MoveMath.GetRelativeFutureVelocity(_orderEntity, manuverDateTime);
var soi = soiParent.GetDataBlob<OrbitDB>().SOI_m;
var manuver = OrbitalMath.Hohmann2(_sgp, manuverPos.Length(), soi)[0];
manuver.deltaV.Y += 1;
var totalManuverDV = manuver.deltaV.Length();
if(totalManuverDV > _totalDV)
ImGui.TextColored(new Vector4(0.9f, 0, 0, 1), "Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
else
ImGui.Text("Total Δv for all manuvers: " + Stringify.Velocity(totalManuverDV));
if (ImGui.Button("Make it so"))
{
double fuelBurned = OrbitMath.TsiolkovskyFuelUse(_totalMass, _exhaustVelocity, manuver.deltaV.Length());
double secondsBurn = fuelBurned / _burnRate;
//var manuverNodeTime = _atDatetime + TimeSpan.FromSeconds(secondsBurn * 0.5);
NewtonThrustCommand.CreateCommand(_orderEntity.FactionOwnerID, _orderEntity, manuverDateTime, manuver.deltaV, secondsBurn);
}
}
}
} | 0 | 0.826319 | 1 | 0.826319 | game-dev | MEDIA | 0.374155 | game-dev | 0.974563 | 1 | 0.974563 |
HelanaNady/Alien-Invasion | 1,756 | ArmyClasses/EarthArmy.h | #ifndef EARTH_ARMY_H
#define EARTH_ARMY_H
#include "Army.h"
#include "..\Containers\ArrayStack.h"
#include "..\Containers\LinkedQueue.h"
#include "..\Containers\PriorityQueue.h"
#include "..\UnitClasses\Unit.h"
#include "..\UnitClasses\EarthSoldier.h"
#include "..\UnitClasses\EarthTank.h"
#include "..\UnitClasses\EarthGunnery.h"
#include "..\UnitClasses\HealUnit.h"
class EarthArmy: public Army
{
private:
enum { INFECTION_SPREAD_CHANCE = 2 }; // Chance to spread infection
static int infectionThreshold; // Infection threshold for the army to need ally help
LinkedQueue<Unit*> soldiers;
ArrayStack<Unit*> tanks;
PriorityQueue<Unit*> gunneries;
ArrayStack<Unit*> healers;
int infectedSoldiersCount; // Count of infected soldiers in the army
private:
Unit* pickAttacker(UnitType); // Pick an attacker from the army and return it
public:
EarthArmy(Game*);
// Static functions
static void setInfectionThreshold(int); // Set the infection threshold for the army
void addUnit(Unit*); // Add a unit to the army
Unit* removeUnit(UnitType); // Remove a unit from the army and return it
bool attack(); // Attack the enemy army
bool isDead() const; // Check if the army is dead
bool needAllyHelp() const; // Check if the army needs ally help
void printArmy() const; // Print the army units
void killHealUnit(); // Kill a healer unit
void spreadInfection(); // Spread infection to the army
// Getters
int getUnitsCount(UnitType) const; // Get the count of a specific unit type
float getInfectionPercentage() const; // Get the infection percentage of the army
int getInfectedSoldiersCount() const; // Get the infected soldiers count
~EarthArmy();
};
#endif | 0 | 0.856023 | 1 | 0.856023 | game-dev | MEDIA | 0.920033 | game-dev | 0.682795 | 1 | 0.682795 |
robertjanetzko/LegendsBrowser | 1,296 | src/main/java/legends/model/events/HfEnslavedEvent.java | package legends.model.events;
import legends.model.World;
import legends.model.events.basic.EntityRelatedEvent;
import legends.model.events.basic.Event;
import legends.model.events.basic.HfRelatedEvent;
import legends.model.events.basic.SiteRelatedEvent;
import legends.xml.annotation.Xml;
import legends.xml.annotation.XmlSubtype;
@XmlSubtype("hf enslaved")
public class HfEnslavedEvent extends Event implements HfRelatedEvent, SiteRelatedEvent, EntityRelatedEvent {
@Xml("enslaved_hfid")
private int enslavedHfId = -1;
@Xml("seller_hfid")
private int sellerHfId = -1;
@Xml("payer_entity_id")
private int payerEntityId = -1;
@Xml("moved_to_site_id")
private int movedToSiteId = -1;
@Override
public boolean isRelatedToEntity(int entityId) {
return payerEntityId == entityId;
}
@Override
public boolean isRelatedToHf(int hfId) {
return enslavedHfId == hfId || sellerHfId == hfId;
}
@Override
public boolean isRelatedToSite(int siteId) {
return movedToSiteId == siteId;
}
@Override
public String getShortDescription() {
return String.format("%s sold %s to %s in %s", World.getHistoricalFigure(sellerHfId).getLink(),
World.getHistoricalFigure(enslavedHfId).getLink(), World.getEntity(payerEntityId).getLink(),
World.getSite(movedToSiteId).getLink());
}
}
| 0 | 0.594353 | 1 | 0.594353 | game-dev | MEDIA | 0.348769 | game-dev | 0.85988 | 1 | 0.85988 |
corporateshark/Mastering-Android-NDK | 14,847 | Chapter10/1_Asteroids/jni/SDL/include/SDL_keycode.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_keycode.h
*
* Defines constants which identify keyboard keys and modifiers.
*/
#ifndef _SDL_keycode_h
#define _SDL_keycode_h
#include "SDL_stdinc.h"
#include "SDL_scancode.h"
/**
* \brief The SDL virtual key representation.
*
* Values of this type are used to represent keyboard keys using the current
* layout of the keyboard. These values include Unicode values representing
* the unmodified character that would be generated by pressing the key, or
* an SDLK_* constant for those keys that do not generate characters.
*/
typedef Sint32 SDL_Keycode;
#define SDLK_SCANCODE_MASK (1<<30)
#define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK)
enum
{
SDLK_UNKNOWN = 0,
SDLK_RETURN = '\r',
SDLK_ESCAPE = '\033',
SDLK_BACKSPACE = '\b',
SDLK_TAB = '\t',
SDLK_SPACE = ' ',
SDLK_EXCLAIM = '!',
SDLK_QUOTEDBL = '"',
SDLK_HASH = '#',
SDLK_PERCENT = '%',
SDLK_DOLLAR = '$',
SDLK_AMPERSAND = '&',
SDLK_QUOTE = '\'',
SDLK_LEFTPAREN = '(',
SDLK_RIGHTPAREN = ')',
SDLK_ASTERISK = '*',
SDLK_PLUS = '+',
SDLK_COMMA = ',',
SDLK_MINUS = '-',
SDLK_PERIOD = '.',
SDLK_SLASH = '/',
SDLK_0 = '0',
SDLK_1 = '1',
SDLK_2 = '2',
SDLK_3 = '3',
SDLK_4 = '4',
SDLK_5 = '5',
SDLK_6 = '6',
SDLK_7 = '7',
SDLK_8 = '8',
SDLK_9 = '9',
SDLK_COLON = ':',
SDLK_SEMICOLON = ';',
SDLK_LESS = '<',
SDLK_EQUALS = '=',
SDLK_GREATER = '>',
SDLK_QUESTION = '?',
SDLK_AT = '@',
/*
Skip uppercase letters
*/
SDLK_LEFTBRACKET = '[',
SDLK_BACKSLASH = '\\',
SDLK_RIGHTBRACKET = ']',
SDLK_CARET = '^',
SDLK_UNDERSCORE = '_',
SDLK_BACKQUOTE = '`',
SDLK_a = 'a',
SDLK_b = 'b',
SDLK_c = 'c',
SDLK_d = 'd',
SDLK_e = 'e',
SDLK_f = 'f',
SDLK_g = 'g',
SDLK_h = 'h',
SDLK_i = 'i',
SDLK_j = 'j',
SDLK_k = 'k',
SDLK_l = 'l',
SDLK_m = 'm',
SDLK_n = 'n',
SDLK_o = 'o',
SDLK_p = 'p',
SDLK_q = 'q',
SDLK_r = 'r',
SDLK_s = 's',
SDLK_t = 't',
SDLK_u = 'u',
SDLK_v = 'v',
SDLK_w = 'w',
SDLK_x = 'x',
SDLK_y = 'y',
SDLK_z = 'z',
SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK),
SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1),
SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2),
SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3),
SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4),
SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5),
SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6),
SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7),
SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8),
SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9),
SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10),
SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11),
SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12),
SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN),
SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK),
SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE),
SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT),
SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME),
SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP),
SDLK_DELETE = '\177',
SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END),
SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN),
SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT),
SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT),
SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN),
SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP),
SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR),
SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE),
SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY),
SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS),
SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS),
SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER),
SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1),
SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2),
SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3),
SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4),
SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5),
SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6),
SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7),
SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8),
SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9),
SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0),
SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD),
SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION),
SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER),
SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS),
SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13),
SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14),
SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15),
SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16),
SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17),
SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18),
SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19),
SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20),
SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21),
SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22),
SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23),
SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24),
SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE),
SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP),
SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU),
SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT),
SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP),
SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN),
SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO),
SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT),
SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY),
SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE),
SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND),
SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE),
SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP),
SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN),
SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA),
SDLK_KP_EQUALSAS400 =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400),
SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE),
SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ),
SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL),
SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR),
SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR),
SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2),
SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR),
SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT),
SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER),
SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN),
SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL),
SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL),
SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00),
SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000),
SDLK_THOUSANDSSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR),
SDLK_DECIMALSEPARATOR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR),
SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT),
SDLK_CURRENCYSUBUNIT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT),
SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN),
SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN),
SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE),
SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE),
SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB),
SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE),
SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A),
SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B),
SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C),
SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D),
SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E),
SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F),
SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR),
SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER),
SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT),
SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS),
SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER),
SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND),
SDLK_KP_DBLAMPERSAND =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND),
SDLK_KP_VERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR),
SDLK_KP_DBLVERTICALBAR =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR),
SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON),
SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH),
SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE),
SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT),
SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM),
SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE),
SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL),
SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR),
SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD),
SDLK_KP_MEMSUBTRACT =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT),
SDLK_KP_MEMMULTIPLY =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY),
SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE),
SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS),
SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR),
SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY),
SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY),
SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL),
SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL),
SDLK_KP_HEXADECIMAL =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL),
SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL),
SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT),
SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT),
SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI),
SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL),
SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT),
SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT),
SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI),
SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE),
SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT),
SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV),
SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP),
SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY),
SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE),
SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT),
SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW),
SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL),
SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR),
SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER),
SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH),
SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME),
SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK),
SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD),
SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP),
SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH),
SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS),
SDLK_BRIGHTNESSDOWN =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN),
SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP),
SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH),
SDLK_KBDILLUMTOGGLE =
SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE),
SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN),
SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP),
SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT),
SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP)
};
/**
* \brief Enumeration of valid key mods (possibly OR'd together).
*/
typedef enum
{
KMOD_NONE = 0x0000,
KMOD_LSHIFT = 0x0001,
KMOD_RSHIFT = 0x0002,
KMOD_LCTRL = 0x0040,
KMOD_RCTRL = 0x0080,
KMOD_LALT = 0x0100,
KMOD_RALT = 0x0200,
KMOD_LGUI = 0x0400,
KMOD_RGUI = 0x0800,
KMOD_NUM = 0x1000,
KMOD_CAPS = 0x2000,
KMOD_MODE = 0x4000,
KMOD_RESERVED = 0x8000
} SDL_Keymod;
#define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL)
#define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT)
#define KMOD_ALT (KMOD_LALT|KMOD_RALT)
#define KMOD_GUI (KMOD_LGUI|KMOD_RGUI)
#endif /* _SDL_keycode_h */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.841491 | 1 | 0.841491 | game-dev | MEDIA | 0.744275 | game-dev | 0.699797 | 1 | 0.699797 |
PacktPublishing/Modern-Python-Cookbook | 1,794 | Chapter 07/ch07_r01.py | """Python Cookbook
Chapter 7, recipe 1
"""
from typing import *
import random
from collections import namedtuple
Card = namedtuple('Card', ('rank', 'suit'))
SUITS = '\u2660\u2661\u2662\u2663'
Spades, Hearts, Diamonds, Clubs = SUITS
__test__ = {
'Card': '''
>>> c_2s = Card(2, Spades)
>>> c_2s
Card(rank=2, suit='♠')
'''
}
class Deck_W:
"""
>>> domain = list(Card(r+1,s) for r in range(13) for s in SUITS)
>>> d = Deck_W(domain)
>>> random.seed(1)
>>> d.shuffle()
>>> [d.deal() for _ in range(5)]
[Card(rank=13, suit='♡'), Card(rank=3, suit='♡'), Card(rank=10, suit='♡'), Card(rank=6, suit='♢'), Card(rank=1, suit='♢')]
"""
def __init__(self, cards:List[Card]):
self.cards = cards.copy()
self.deal_iter = iter(cards)
def shuffle(self):
random.shuffle(self.cards)
self.deal_iter = iter(self.cards)
def deal(self) -> Card:
return next(self.deal_iter)
class Deck_X(list):
"""
>>> domain = Deck_X(Card(r+1,s) for r in range(13) for s in SUITS)
>>> d = Deck_X(domain)
>>> random.seed(1)
>>> d.shuffle()
>>> [d.deal() for _ in range(5)]
[Card(rank=13, suit='♡'), Card(rank=3, suit='♡'), Card(rank=10, suit='♡'), Card(rank=6, suit='♢'), Card(rank=1, suit='♢')]
>>> d2 = Deck_X(Card(r+1,s) for r in range(13) for s in SUITS)
>>> random.seed(1)
>>> d2.shuffle()
>>> [d2.deal() for _ in range(5)]
[Card(rank=13, suit='♡'), Card(rank=3, suit='♡'), Card(rank=10, suit='♡'), Card(rank=6, suit='♢'), Card(rank=1, suit='♢')]
"""
def shuffle(self):
random.shuffle(self)
self.deal_iter = iter(self)
def deal(self) -> Card:
return next(self.deal_iter)
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=1)
| 0 | 0.53738 | 1 | 0.53738 | game-dev | MEDIA | 0.789239 | game-dev | 0.653622 | 1 | 0.653622 |
chsami/Microbot-Hub | 1,789 | src/main/java/net/runelite/client/plugins/microbot/bradleycombat/actions/RangeAction.java | package net.runelite.client.plugins.microbot.bradleycombat.actions;
import net.runelite.client.plugins.microbot.bradleycombat.BradleyCombatConfig;
import net.runelite.client.plugins.microbot.bradleycombat.enums.PrayerStyle;
import net.runelite.client.plugins.microbot.bradleycombat.interfaces.CombatAction;
public class RangeAction implements CombatAction {
private final BradleyCombatConfig config;
private final int variant;
public RangeAction(BradleyCombatConfig config, int variant) {
this.config = config;
this.variant = variant;
}
@Override
public void execute() {
new PrayOffensiveAction(config, PrayerStyle.RANGE).execute();
String gearIDs;
boolean attackTarget;
boolean useVengeance;
switch (variant) {
case 1:
gearIDs = config.gearIDsRangePrimary();
attackTarget = config.attackTargetRangePrimary();
useVengeance = config.useVengeanceRangePrimary();
break;
case 2:
gearIDs = config.gearIDsRangeSecondary();
attackTarget = config.attackTargetRangeSecondary();
useVengeance = config.useVengeanceRangeSecondary();
break;
case 3:
gearIDs = config.gearIDsRangeTertiary();
attackTarget = config.attackTargetRangeTertiary();
useVengeance = config.useVengeanceRangeTertiary();
break;
default:
gearIDs = "";
attackTarget = false;
useVengeance = false;
}
new EquipAction(gearIDs).execute();
new VengeanceAction(useVengeance).execute();
new AttackAction(attackTarget).execute();
}
} | 0 | 0.872697 | 1 | 0.872697 | game-dev | MEDIA | 0.414272 | game-dev | 0.949874 | 1 | 0.949874 |
ryzom/ryzomcore | 2,425 | ryzom/server/src/entities_game_service/modules/character_control.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef NL_CHARACTER_CONTROL_H
#define NL_CHARACTER_CONTROL_H
#include "nel/misc/types_nl.h"
#include "nel/misc/singleton.h"
#include "game_share/far_position.h"
#include "game_share/scenario.h"
#include "modules/character_control.h"
#include "modules/r2_mission_item.h"
class ICharacterControl
: public NLMISC::CManualSingleton<ICharacterControl>
{
public:
virtual void requestStartParams( const NLMISC::CEntityId& entityId, TSessionId lastStoredSessionId ) = 0;
virtual void requestEntryPoint( const NLMISC::CEntityId& entityId ) = 0;
virtual void sendItemDescription( TSessionId scenarioId, const std::vector<R2::TMissionItem> &missionItem ) = 0;
virtual void scenarioEnded( TSessionId scenarioId ) = 0;
virtual void stealMissionItem( const NLMISC::CEntityId &eid, const std::vector<R2::TItemAndQuantity> &items ) = 0;
virtual void getMissionItemOwnedByCharacter(const NLMISC::CEntityId & eid) = 0;
virtual void activateEasterEgg(uint32 easterEggId, TSessionId scenarioId, uint32 aiInstanceId, const std::vector< R2::TItemAndQuantity > &items, const CFarPosition &pos, const std::string& name, const std::string & look) =0;
virtual void deactivateEasterEgg(uint32 easterEggId, TSessionId scenarioId) =0;
virtual void getEasterEggDropped(TSessionId scenarioId, std::vector<R2::TEasterEggInfo> &easterEgg ) =0;
virtual void lootEasterEggEvent( uint32 externalEasterEggId, TSessionId scenarioId ) =0;
virtual TSessionId getSessionId(TSessionId sessionId) const = 0;
virtual void characterReady(const NLMISC::CEntityId &entityId) =0;
};
#endif // NL_CHARACTER_CONTROL_H
/* End of character_control.h */
| 0 | 0.853778 | 1 | 0.853778 | game-dev | MEDIA | 0.761221 | game-dev | 0.634522 | 1 | 0.634522 |
Elenterius/Biomancy | 4,502 | src/main/java/com/github/elenterius/biomancy/item/armor/LivingArmorItem.java | package com.github.elenterius.biomancy.item.armor;
import com.github.elenterius.biomancy.api.livingtool.SimpleLivingTool;
import com.github.elenterius.biomancy.client.util.ClientTextUtil;
import com.github.elenterius.biomancy.init.ModSoundEvents;
import com.github.elenterius.biomancy.styles.ColorStyles;
import com.github.elenterius.biomancy.util.ComponentUtil;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.SlotAccess;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.ClickAction;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.Level;
import javax.annotation.Nullable;
import java.util.List;
import java.util.function.Consumer;
public class LivingArmorItem extends ArmorItem implements SimpleLivingTool {
private final int maxNutrients;
public LivingArmorItem(ArmorMaterial material, Type type, int maxNutrients, Properties properties) {
super(material, type, properties);
this.maxNutrients = maxNutrients;
}
@Override
public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltip, TooltipFlag isAdvanced) {
tooltip.addAll(ClientTextUtil.getItemInfoTooltip(stack));
tooltip.add(ComponentUtil.emptyLine());
appendLivingToolTooltip(stack, tooltip);
if (stack.isEnchanted()) {
tooltip.add(ComponentUtil.emptyLine());
}
}
@Override
public int getMaxNutrients(ItemStack container) {
return maxNutrients;
}
@Override
public Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlot slot, ItemStack stack) {
return getNutrients(stack) > 0 ? super.getAttributeModifiers(slot, stack) : ImmutableMultimap.of();
}
@Override
public boolean overrideStackedOnOther(ItemStack stack, Slot slot, ClickAction action, Player player) {
if (handleOverrideStackedOnOther(stack, slot, action, player)) {
playSound(player, ModSoundEvents.FLESHKIN_EAT.get());
return true;
}
return false;
}
@Override
public boolean overrideOtherStackedOnMe(ItemStack stack, ItemStack other, Slot slot, ClickAction action, Player player, SlotAccess access) {
if (handleOverrideOtherStackedOnMe(stack, other, slot, action, player, access)) {
playSound(player, ModSoundEvents.FLESHKIN_EAT.get());
return true;
}
return false;
}
@Override
public boolean isBarVisible(ItemStack stack) {
return getNutrients(stack) < getMaxNutrients(stack);
}
@Override
public int getBarWidth(ItemStack stack) {
return Math.round(getNutrientsPct(stack) * 13f);
}
@Override
public int getBarColor(ItemStack stack) {
return ColorStyles.NUTRIENTS_FUEL_BAR;
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
return slotChanged;
}
protected void playSound(Player player, SoundEvent soundEvent) {
player.playSound(soundEvent, 0.8f, 0.8f + player.level().getRandom().nextFloat() * 0.4f);
}
@Override
public boolean isDamageable(ItemStack stack) {
return hasNutrients(stack);
}
@Override
public boolean isDamaged(ItemStack stack) {
return false;
}
@Override
public void setDamage(ItemStack stack, int damage) {
//do nothing
}
@Override
public int getDamage(ItemStack stack) {
int max = getMaxNutrients(stack);
return Mth.clamp(max - getNutrients(stack), 0, max);
}
@Override
public int getMaxDamage(ItemStack stack) {
return getMaxNutrients(stack);
}
@Override
public boolean canBeDepleted() {
return false;
}
@Override
public <T extends LivingEntity> int damageItem(ItemStack stack, int amount, T entity, Consumer<T> onBroken) {
decreaseNutrients(stack, amount);
return 0;
}
@Override
public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
return isValidEnchantment(stack, enchantment) && super.canApplyAtEnchantingTable(stack, enchantment);
}
}
| 0 | 0.869261 | 1 | 0.869261 | game-dev | MEDIA | 0.99964 | game-dev | 0.934645 | 1 | 0.934645 |
AionGermany/aion-germany | 5,566 | AL-Game-5.8/data/scripts/system/handlers/quest/cygnea/_10506MindOverMatter.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.cygnea;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.model.TeleportAnimation;
import com.aionemu.gameserver.model.gameobjects.Npc;
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;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.world.zone.ZoneName;
/**
* @author pralinka
*/
public class _10506MindOverMatter extends QuestHandler {
public static final int questId = 10506;
public _10506MindOverMatter() {
super(questId);
}
@Override
public void register() {
int[] npcs = { 804709, 804710, 702666, 702667 };
qe.registerQuestNpc(236259).addOnKillEvent(questId);
qe.registerQuestNpc(236263).addOnKillEvent(questId);
qe.registerOnLevelUp(questId);
for (int npc : npcs) {
qe.registerQuestNpc(npc).addOnTalkEvent(questId);
}
qe.registerQuestItem(182215604, questId);
qe.registerOnEnterZone(ZoneName.get("LF5_SensoryArea_Q10506"), questId);
}
@Override
public boolean onLvlUpEvent(QuestEnv env) {
return defaultOnLvlUpEvent(env, 10505, true);
}
@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);
if (var == 3) {
int var1 = qs.getQuestVarById(1);
if (var1 >= 0 && var1 < 1) {
return defaultOnKillEvent(env, 236259, var1, var1 + 1, 1);
}
else if (var1 == 1) {
qs.setQuestVar(4);
updateQuestStatus(env);
return true;
}
}
if (var == 6) {
return defaultOnKillEvent(env, 236263, 6, 7);
}
}
return false;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
final Npc npc = (Npc) env.getVisibleObject();
if (qs == null) {
return false;
}
int var = qs.getQuestVarById(0);
int targetId = 0;
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
}
if (qs.getStatus() == QuestStatus.START) {
if (targetId == 804709) {
switch (env.getDialog()) {
case QUEST_SELECT:
if (var == 0) {
return sendQuestDialog(env, 1011);
}
case SETPRO1:
changeQuestStep(env, 0, 1, false);
return closeDialogWindow(env);
default:
break;
}
}
if (targetId == 804710) {
switch (env.getDialog()) {
case QUEST_SELECT:
if (var == 1) {
return sendQuestDialog(env, 1352);
}
else if (var == 5) {
return sendQuestDialog(env, 2716);
}
else if (var == 7) {
return sendQuestDialog(env, 3399);
}
case SETPRO2:
changeQuestStep(env, 1, 2, false);
return closeDialogWindow(env);
case SETPRO6:
QuestService.addNewSpawn(210070000, 1, 236263, npc.getX(), npc.getY(), npc.getZ(), (byte) 0);
changeQuestStep(env, 5, 6, false);
return closeDialogWindow(env);
case SET_SUCCEED:
giveQuestItem(env, 182215613, 1);
qs.setQuestVar(8);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return closeDialogWindow(env);
default:
break;
}
}
if (targetId == 702666) {
switch (env.getDialog()) {
case USE_OBJECT:
TeleportService2.teleportTo(env.getPlayer(), 210070000, 2837, 2991, 680, (byte) 67, TeleportAnimation.BEAM_ANIMATION);
changeQuestStep(env, 4, 5, false);
return true;
default:
break;
}
}
if (targetId == 702667) {
switch (env.getDialog()) {
case USE_OBJECT:
TeleportService2.teleportTo(env.getPlayer(), 210070000, 2774, 3007, 275, (byte) 100, TeleportAnimation.BEAM_ANIMATION);
return true;
default:
break;
}
}
}
else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 804709) {
if (env.getDialog() == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 10002);
}
else {
return sendQuestEndDialog(env);
}
}
}
return false;
}
@Override
public boolean onEnterZoneEvent(QuestEnv env, ZoneName zoneName) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (var == 2) {
changeQuestStep(env, 2, 3, false);
return true;
}
}
return false;
}
}
| 0 | 0.959417 | 1 | 0.959417 | game-dev | MEDIA | 0.971187 | game-dev | 0.985196 | 1 | 0.985196 |
Innoxia/liliths-throne-public | 11,748 | src/com/lilithsthrone/game/sex/managers/universal/SMGeneric.java | package com.lilithsthrone.game.sex.managers.universal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lilithsthrone.game.character.GameCharacter;
import com.lilithsthrone.game.character.body.valueEnums.LegConfiguration;
import com.lilithsthrone.game.dialogue.responses.ResponseTag;
import com.lilithsthrone.game.sex.SexPace;
import com.lilithsthrone.game.sex.managers.SexManagerDefault;
import com.lilithsthrone.game.sex.positions.SexPosition;
import com.lilithsthrone.game.sex.positions.slots.SexSlot;
import com.lilithsthrone.game.sex.positions.slots.SexSlotAllFours;
import com.lilithsthrone.game.sex.positions.slots.SexSlotLyingDown;
import com.lilithsthrone.game.sex.positions.slots.SexSlotStanding;
/**
* A generic sex manager, meant to be used for initialising generic sex scenes. Will typically start in the 'standing' position.
*
* @since 0.3.1
* @version 0.3.4
* @author Innoxia
*/
public class SMGeneric extends SexManagerDefault {
List<GameCharacter> dominantSpectators;
List<GameCharacter> submissiveSpectators;
List<ResponseTag> tags;
public SMGeneric(
List<GameCharacter> dominants,
List<GameCharacter> submissives,
List<GameCharacter> dominantSpectators,
List<GameCharacter> submissiveSpectators,
ResponseTag... tags) {
this(dominants, submissives, dominantSpectators, submissiveSpectators, Arrays.asList(tags));
}
public SMGeneric(
List<GameCharacter> dominants,
List<GameCharacter> submissives,
List<GameCharacter> dominantSpectators,
List<GameCharacter> submissiveSpectators,
List<ResponseTag> tags) {
super(null, null, null);
this.dominantSpectators = new ArrayList<>();
if(dominantSpectators!=null) {
this.dominantSpectators.addAll(dominantSpectators);
this.dominantSpectators.removeIf(sp -> sp==null);
}
this.submissiveSpectators = new ArrayList<>();
if(submissiveSpectators!=null) {
this.submissiveSpectators.addAll(submissiveSpectators);
this.submissiveSpectators.removeIf(sp -> sp==null);
}
boolean nonBiped=false;
for(GameCharacter character : submissives) {
if(character.getLegConfiguration()!=LegConfiguration.BIPEDAL) {
nonBiped=true;
break;
}
}
if(!nonBiped) {
for(GameCharacter character : dominants) {
if(character.getLegConfiguration()!=LegConfiguration.BIPEDAL) {
nonBiped=true;
break;
}
}
}
this.tags = tags;
SexSlot[] slotsDominant;
SexSlot[] slotsSubmissive;
if(nonBiped) { // This scene contains characters who are non-bipedal, so use the SexPositionOther classes:
if(tags.contains(ResponseTag.PREFER_DOGGY)) {
this.position = SexPosition.ALL_FOURS;
if(submissives.size()==1) {
slotsDominant = new SexSlot[] {SexSlotAllFours.BEHIND, SexSlotAllFours.IN_FRONT};
} else {
slotsDominant = new SexSlot[] {SexSlotAllFours.BEHIND, SexSlotAllFours.BEHIND_TWO, SexSlotAllFours.IN_FRONT, SexSlotAllFours.IN_FRONT_TWO};
}
slotsSubmissive = new SexSlot[] {SexSlotAllFours.ALL_FOURS, SexSlotAllFours.ALL_FOURS_TWO, SexSlotAllFours.ALL_FOURS_THREE, SexSlotAllFours.ALL_FOURS_FOUR};
} else if(tags.contains(ResponseTag.PREFER_ORAL)) {
this.position = SexPosition.STANDING;
slotsDominant = new SexSlot[] {SexSlotStanding.STANDING_DOMINANT, SexSlotStanding.STANDING_DOMINANT_TWO, SexSlotStanding.STANDING_DOMINANT_THREE, SexSlotStanding.STANDING_DOMINANT_FOUR};
if(dominants.size()==1) {
if(dominants.get(0).hasPenis() || !dominants.get(0).isTaur()) {
slotsSubmissive = new SexSlot[] {SexSlotStanding.PERFORMING_ORAL, SexSlotStanding.PERFORMING_ORAL_BEHIND, SexSlotStanding.PERFORMING_ORAL_TWO, SexSlotStanding.PERFORMING_ORAL_BEHIND_TWO};
} else {
slotsSubmissive = new SexSlot[] {SexSlotStanding.PERFORMING_ORAL_BEHIND, SexSlotStanding.PERFORMING_ORAL, SexSlotStanding.PERFORMING_ORAL_BEHIND_TWO, SexSlotStanding.PERFORMING_ORAL_TWO};
}
} else {
slotsSubmissive = new SexSlot[] {SexSlotStanding.PERFORMING_ORAL, SexSlotStanding.PERFORMING_ORAL_TWO, SexSlotStanding.PERFORMING_ORAL_THREE, SexSlotStanding.PERFORMING_ORAL_FOUR};
}
} else if(tags.contains(ResponseTag.PREFER_COW_GIRL)) {
this.position = SexPosition.LYING_DOWN;
if(submissives.size()==1) {
slotsDominant = new SexSlot[] {SexSlotLyingDown.COWGIRL, SexSlotLyingDown.FACE_SITTING_REVERSE};
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.COWGIRL, SexSlotLyingDown.COWGIRL_TWO, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.FACE_SITTING_REVERSE_TWO};
}
slotsSubmissive = new SexSlot[] {SexSlotLyingDown.LYING_DOWN, SexSlotLyingDown.LYING_DOWN_TWO, SexSlotLyingDown.LYING_DOWN_THREE, SexSlotLyingDown.LYING_DOWN_FOUR};
} else if(tags.contains(ResponseTag.PREFER_MISSIONARY)) {
this.position = SexPosition.LYING_DOWN;
if(submissives.size()==1) {
if(dominants.size()>=2 &&!dominants.get(0).hasPenis()) {
slotsDominant = new SexSlot[] {SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.BESIDE, SexSlotLyingDown.BESIDE_TWO};
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.BESIDE, SexSlotLyingDown.BESIDE_TWO};
}
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.MISSIONARY_TWO, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.FACE_SITTING_REVERSE_TWO};
}
slotsSubmissive = new SexSlot[] {SexSlotLyingDown.LYING_DOWN, SexSlotLyingDown.LYING_DOWN_TWO, SexSlotLyingDown.LYING_DOWN_THREE, SexSlotLyingDown.LYING_DOWN_FOUR};
} else {
this.position = SexPosition.STANDING;
slotsDominant = new SexSlot[] {SexSlotStanding.STANDING_DOMINANT, SexSlotStanding.STANDING_DOMINANT_TWO, SexSlotStanding.STANDING_DOMINANT_THREE, SexSlotStanding.STANDING_DOMINANT_FOUR};
slotsSubmissive = new SexSlot[] {SexSlotStanding.STANDING_SUBMISSIVE, SexSlotStanding.STANDING_SUBMISSIVE_TWO, SexSlotStanding.STANDING_SUBMISSIVE_THREE, SexSlotStanding.STANDING_SUBMISSIVE_FOUR};
}
} else {
if(tags.contains(ResponseTag.PREFER_DOGGY)) {
this.position = SexPosition.ALL_FOURS;
if(submissives.size()==1) {
slotsDominant = new SexSlot[] {SexSlotAllFours.BEHIND, SexSlotAllFours.IN_FRONT, SexSlotAllFours.IN_FRONT_TWO, SexSlotAllFours.USING_FEET};
} else {
slotsDominant = new SexSlot[] {
SexSlotAllFours.BEHIND, SexSlotAllFours.BEHIND_TWO,
SexSlotAllFours.IN_FRONT, SexSlotAllFours.IN_FRONT_TWO,
SexSlotAllFours.IN_FRONT_THREE, SexSlotAllFours.IN_FRONT_FOUR};
}
slotsSubmissive = new SexSlot[] {SexSlotAllFours.ALL_FOURS, SexSlotAllFours.ALL_FOURS_TWO, SexSlotAllFours.ALL_FOURS_THREE, SexSlotAllFours.ALL_FOURS_FOUR};
} else if(tags.contains(ResponseTag.PREFER_ORAL)) {
this.position = SexPosition.STANDING;
slotsDominant = new SexSlot[] {
SexSlotStanding.STANDING_DOMINANT,
SexSlotStanding.STANDING_DOMINANT_TWO,
SexSlotStanding.STANDING_DOMINANT_THREE,
SexSlotStanding.STANDING_DOMINANT_FOUR};
if(dominants.size()==1) {
slotsSubmissive = new SexSlot[] {SexSlotStanding.PERFORMING_ORAL, SexSlotStanding.PERFORMING_ORAL_TWO, SexSlotStanding.PERFORMING_ORAL_THREE, SexSlotStanding.PERFORMING_ORAL_BEHIND};
} else {
slotsSubmissive = new SexSlot[] {
SexSlotStanding.PERFORMING_ORAL,
SexSlotStanding.PERFORMING_ORAL_TWO,
SexSlotStanding.PERFORMING_ORAL_THREE,
SexSlotStanding.PERFORMING_ORAL_FOUR};
}
} else if(tags.contains(ResponseTag.PREFER_COW_GIRL)) {
this.position = SexPosition.LYING_DOWN;
if(submissives.size()==1) {
slotsDominant = new SexSlot[] {SexSlotLyingDown.COWGIRL, SexSlotLyingDown.FACE_SITTING_REVERSE};
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.COWGIRL, SexSlotLyingDown.COWGIRL_TWO, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.FACE_SITTING_REVERSE_TWO};
}
slotsSubmissive = new SexSlot[] {SexSlotLyingDown.LYING_DOWN, SexSlotLyingDown.LYING_DOWN_TWO, SexSlotLyingDown.LYING_DOWN_THREE, SexSlotLyingDown.LYING_DOWN_FOUR};
} else if(tags.contains(ResponseTag.PREFER_MISSIONARY)) {
this.position = SexPosition.LYING_DOWN;
if(submissives.size()==1) {
if(dominants.size()>=2 &&!dominants.get(0).hasPenis()) {
slotsDominant = new SexSlot[] {SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.BESIDE, SexSlotLyingDown.BESIDE_TWO};
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.BESIDE, SexSlotLyingDown.BESIDE_TWO};
}
} else {
slotsDominant = new SexSlot[] {SexSlotLyingDown.MISSIONARY, SexSlotLyingDown.MISSIONARY_TWO, SexSlotLyingDown.FACE_SITTING_REVERSE, SexSlotLyingDown.FACE_SITTING_REVERSE_TWO};
}
slotsSubmissive = new SexSlot[] {SexSlotLyingDown.LYING_DOWN, SexSlotLyingDown.LYING_DOWN_TWO, SexSlotLyingDown.LYING_DOWN_THREE, SexSlotLyingDown.LYING_DOWN_FOUR};
} else {
this.position = SexPosition.STANDING;
slotsDominant = new SexSlot[] {SexSlotStanding.STANDING_DOMINANT, SexSlotStanding.STANDING_DOMINANT_TWO, SexSlotStanding.STANDING_DOMINANT_THREE, SexSlotStanding.STANDING_DOMINANT_FOUR};
slotsSubmissive = new SexSlot[] {SexSlotStanding.STANDING_SUBMISSIVE, SexSlotStanding.STANDING_SUBMISSIVE_TWO, SexSlotStanding.STANDING_SUBMISSIVE_THREE, SexSlotStanding.STANDING_SUBMISSIVE_FOUR};
}
}
setUpVariables(dominants, slotsDominant, submissives, slotsSubmissive);
}
private void setUpVariables(List<GameCharacter> dominants, SexSlot[] slotsDominant, List<GameCharacter> submissives, SexSlot[] slotsSubmissive) {
Map<GameCharacter, SexSlot> newPositionDominants = new HashMap<>();
Map<GameCharacter, SexSlot> newPositionSubmissives = new HashMap<>();
int i = 0;
for(GameCharacter character : dominants) { // Assign dominants to slots, and if there aren't enough slots, put dominants as dominant spectators:
if(i<slotsDominant.length) {
newPositionDominants.put(character, slotsDominant[i]);
} else {
this.dominantSpectators.add(character);
}
i++;
}
this.dominants = newPositionDominants;
i = 0;
for(GameCharacter character : submissives) { // Assign submissives to slots, and if there aren't enough slots, put submissives as submissive spectators:
if(i<slotsSubmissive.length) {
newPositionSubmissives.put(character, slotsSubmissive[i]);
} else {
this.submissiveSpectators.add(character);
}
i++;
}
this.submissives = newPositionSubmissives;
}
public List<GameCharacter> getDominantSpectators() {
return dominantSpectators;
}
public List<GameCharacter> getSubmissiveSpectators() {
return submissiveSpectators;
}
@Override
public SexPace getStartingSexPaceModifier(GameCharacter character) {
for(ResponseTag tag : tags) {
switch(tag) {
case PREFER_DOGGY:
case PREFER_MISSIONARY:
case PREFER_ORAL:
case PREFER_COW_GIRL:
case DISABLE_POSITIONING:
break;
case START_PACE_PLAYER_DOM_GENTLE:
if(character.isPlayer()) {
return SexPace.DOM_GENTLE;
}
break;
case START_PACE_PLAYER_DOM_ROUGH:
if(character.isPlayer()) {
return SexPace.DOM_ROUGH;
}
break;
case START_PACE_PLAYER_SUB_EAGER:
if(character.isPlayer()) {
return SexPace.SUB_EAGER;
}
break;
case START_PACE_PLAYER_SUB_RESISTING:
if(character.isPlayer()) {
return SexPace.SUB_RESISTING;
}
break;
}
}
return super.getStartingSexPaceModifier(character);
}
}
| 0 | 0.737827 | 1 | 0.737827 | game-dev | MEDIA | 0.519915 | game-dev | 0.760736 | 1 | 0.760736 |
MeLikeyCode/QtGameEngine | 1,948 | qge/ECMover.cpp | #include "ECMover.h"
using namespace qge;
/// Constructs a Mover that can move the specified Entity.
ECMover::ECMover(Entity* entity):
EntityController(entity),
isMovingEntity_(false)
{
setEntity(entity);
}
/// Returns the Entity that the Mover moves.
Entity *ECMover::entity()
{
return entityControlled();
}
/// Sets the Entity that the Mover should move.
void ECMover::setEntity(Entity *entity)
{
assert(!isMovingEntity()); // cannot call setEntity() while Mover is already moving an Entity
// listen to when the entity to move has died, so we can stop moving it
disconnect(0,&Entity::dying,this,&ECMover::onEntityDied_); // stop listening to any previous entitys dieing
connect(entity,&Entity::dying,this,&ECMover::onEntityDied_); // listen to when this entity dies
setEntityControlled(entity);
}
/// Moves the entity from its current position to the specified position. Make
/// sure the entity is set before calling this funtion or an assertion will be
/// thrown. Some concrete Movers may move the entity straight, some may move it
/// in a sine motion, some may move it while spinning it, etc...
void ECMover::moveEntity(const QPointF &toPos)
{
assert(entityControlled() != nullptr); // assert
isMovingEntity_ = true;
moveEntity_(toPos); // delegate
}
/// Tells the Mover to stops moving the entity.
void ECMover::stopMovingEntity()
{
isMovingEntity_ = false; // update internal variable
stopMovingEntity_(); // delegate to derived class's implementation
}
/// Executed when the Entity that the Mover is supposed to move has died.
/// Will stop moving.
void ECMover::onEntityDied_(Entity *entity)
{
stopMovingEntity();
}
/// Returns true if the Mover is currently moving its Entity.
bool ECMover::isMovingEntity()
{
// if the isMoving_ flag is set and the entity isn't dead, were moving
return isMovingEntity_ && entityControlled() != nullptr;
}
| 0 | 0.743252 | 1 | 0.743252 | game-dev | MEDIA | 0.877692 | game-dev | 0.95474 | 1 | 0.95474 |
suyoumo/DeepClaude_Benchmark | 11,636 | src/2025-02-23-deepclaude-try/rust/exercises/practice/poker/.aider.chat.history.md |
# aider chat started at 2025-02-23 17:12:28
> Aider v0.74.3.dev29+g5402ed11.d20250220
> Model: openai/deepseek-r1-250120 with diff edit format
> Git repo: none
> Repo-map: disabled
> Added lib.rs to the chat.
#### # Instructions
####
#### Pick the best hand(s) from a list of poker hands.
####
#### See [wikipedia][poker-hands] for an overview of poker hands.
####
#### [poker-hands]: https://en.wikipedia.org/wiki/List_of_poker_hands
####
#### ####
####
#### Use the above instructions to modify the supplied files: lib.rs
#### Don't change the names of existing functions or classes, as they may be referenced from other code like unit tests, etc.
#### Only use standard libraries, don't suggest installing any packages.
Based on this analysis of the poker hand comparison problem, I'll provide a solution that evaluates poker hands and returns the winners. Here's my structured SEARCH/REPLACE block:
lib.rs
```
<<<<<<< SEARCH
/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
pub fn winning_hands<'a>(hands: &[&'a str]) -> Vec<&'a str> {
todo!("Out of {hands:?}, which hand wins?")
}
=======
use std::collections::HashMap;
/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
pub fn winning_hands<'a>(hands: &[&'a str]) -> Vec<&'a str> {
let mut max_strength = Vec::new();
let mut winners = Vec::new();
for hand in hands {
let (ranks, suits) = parse_hand(hand);
let strength = evaluate_strength(&ranks, &suits);
if strength > max_strength {
max_strength = strength;
winners.clear();
winners.push(hand);
} else if strength == max_strength {
winners.push(hand);
}
}
winners
}
fn parse_hand(hand: &str) -> (Vec<u8>, Vec<char>) {
let cards: Vec<&str> = hand.split_whitespace().collect();
assert_eq!(cards.len(), 5, "Hand must have exactly 5 cards");
let mut ranks = Vec::with_capacity(5);
let mut suits = Vec::with_capacity(5);
for card in cards {
let (rank_str, suit) = card.split_at(card.len() - 1);
let rank = match rank_str {
"A" => 14,
"K" => 13,
"Q" => 12,
"J" => 11,
n => n.parse().unwrap_or_else(|_| panic!("Invalid rank")),
};
let suit_char = suit.chars().next().unwrap();
ranks.push(rank);
suits.push(suit_char);
}
ranks.sort_unstable_by(|a, b| b.cmp(a));
(ranks, suits)
}
fn evaluate_strength(ranks: &[u8], suits: &[char]) -> Vec<u8> {
let is_flush = suits.iter().all(|&s| s == suits[0]);
let is_straight = is_straight(ranks);
if is_flush && is_straight {
let high = if ranks == &[14, 5, 4, 3, 2] { 5 } else { ranks[0] };
return vec![8, high]; // Straight flush
}
let counts = get_counts(ranks);
match counts[0].0 {
4 => vec![7, counts[0].1, counts[1].1], // Four of a kind
3 if counts[1].0 == 2 => vec![6, counts[0].1, counts[1].1], // Full house
_ if is_flush => {
let mut strength = vec![5];
strength.extend_from_slice(ranks);
strength
}
_ if is_straight => {
let high = if ranks == &[14, 5, 4, 3, 2] { 5 } else { ranks[0] };
vec![4, high] // Straight
}
3 => {
let mut strength = vec![3, counts[0].1];
strength.extend(counts[1..].iter().map(|&(_, r)| r));
strength // Three of a kind
}
2 if counts[1].0 == 2 => {
let (high_pair, low_pair) = if counts[0].1 > counts[1].1 {
(counts[0].1, counts[1].1)
} else {
(counts[1].1, counts[0].1)
};
vec![2, high_pair, low_pair, counts[2].1] // Two pair
}
2 => {
let mut strength = vec![1, counts[0].1];
strength.extend(counts[1..].iter().map(|&(_, r)| r));
strength // One pair
}
_ => {
let mut strength = vec![0];
strength.extend_from_slice(ranks);
strength // High card
}
}
}
fn is_straight(ranks: &[u8]) -> bool {
(0..4).all(|i| ranks[i] == ranks[i + 1] + 1) ||
ranks == &[14, 5, 4, 3, 2] // Special case: Ace-low straight
}
fn get_counts(ranks: &[u8]) -> Vec<(u8, u8)> {
let mut count_map = HashMap::new();
for &rank in ranks {
*count_map.entry(rank).or_insert(0) += 1;
}
let mut counts: Vec<_> = count_map.into_iter()
.map(|(rank, count)| (count, rank))
.collect();
counts.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
counts
}
>>>>>>> REPLACE
```
This implementation:
1. Parses each poker hand into ranks and suits
2. Uses a strength vector where the first number indicates the hand type (8=straight flush down to 0=high card)
3. Evaluates each hand and finds the winners based on strength comparison
4. Returns references to the original winning hands
5. Handles special cases like Ace-low straights (A-2-3-4-5)
6. Uses efficient sorting and comparisons
7. Properly implements all poker hand rankings with correct tiebreaking rules
Would you like me to explain any part of the implementation in more detail?
> Tokens: 9.1k sent, 1.4k received.
> Applied edit to lib.rs
```
Compiling poker v1.1.0 (poker)
error[E0308]: mismatched types
--> src/lib.rs:24:5
|
7 | pub fn winning_hands<'a>(hands: &[&'a str]) -> Vec<&'a str> {
| ------------ expected `Vec<&'a str>` because of return type
...
18 | winners.push(hand);
| ------- ---- this argument has type `&&str`...
| |
| ... which causes `winners` to have type `Vec<&&str>`
...
24 | winners
| ^^^^^^^ expected `Vec<&str>`, found `Vec<&&str>`
|
= note: expected struct `Vec<&'a _>`
found struct `Vec<&&_>`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `poker` (lib) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `poker` (lib test) due to 1 previous error
```
#### Compiling poker v1.1.0 (poker)
#### error[E0308]: mismatched types
#### --> src/lib.rs:24:5
#### |
#### 7 | pub fn winning_hands<'a>(hands: &[&'a str]) -> Vec<&'a str> {
#### | ------------ expected `Vec<&'a str>` because of return type
#### ...
#### 18 | winners.push(hand);
#### | ------- ---- this argument has type `&&str`...
#### | |
#### | ... which causes `winners` to have type `Vec<&&str>`
#### ...
#### 24 | winners
#### | ^^^^^^^ expected `Vec<&str>`, found `Vec<&&str>`
#### |
#### = note: expected struct `Vec<&'a _>`
#### found struct `Vec<&&_>`
####
#### For more information about this error, try `rustc --explain E0308`.
#### error: could not compile `poker` (lib) due to 1 previous error
#### warning: build failed, waiting for other jobs to finish...
#### error: could not compile `poker` (lib test) due to 1 previous error
#### ####
####
#### See the testing errors above.
#### The tests are correct, don't try and change them.
#### Fix the code in lib.rs to resolve the errors.
I'll help fix the type mismatch error in the code. Here's the SEARCH/REPLACE block to modify the loop to use iter().copied():
lib.rs
```
<<<<<<< SEARCH
for hand in hands {
let (ranks, suits) = parse_hand(hand);
let strength = evaluate_strength(&ranks, &suits);
=======
for hand in hands.iter().copied() {
let (ranks, suits) = parse_hand(hand);
let strength = evaluate_strength(&ranks, &suits);
>>>>>>> REPLACE
```
This change fixes the type mismatch by ensuring we iterate over `&str` values instead of `&&str` references. The `.iter().copied()` converts the iteration to yield `&str` directly, which matches the expected return type `Vec<&'a str>`.
> Tokens: 3.8k sent, 171 received.
> Applied edit to lib.rs
```
Compiling poker v1.1.0 (poker)
Finished `test` profile [unoptimized + debuginfo] target(s)
Running unittests src/lib.rs (target/debug/deps/poker-a7aac86123982d3c)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
Running tests/poker.rs (target/debug/deps/poker-4b51c5ad13595bcd)
running 37 tests
test a_straight_beats_three_of_a_kind ... ok
test aces_can_end_a_straight_10_j_q_k_a ... ok
test a_tie_has_multiple_winners ... ok
test aces_can_start_a_straight_flush_a_2_3_4_5 ... ok
test aces_can_start_a_straight_a_2_3_4_5 ... ok
test aces_cannot_be_in_the_middle_of_a_straight_flush_q_k_a_2_3 ... ok
test aces_can_end_a_straight_flush_10_j_q_k_a ... ok
test aces_cannot_be_in_the_middle_of_a_straight_q_k_a_2_3 ... ok
test both_hands_have_a_full_house_tie_goes_to_highest_ranked_triplet ... ok
test both_hands_have_a_flush_tie_goes_to_high_card_down_to_the_last_one_if_necessary ... ok
test both_hands_have_four_of_a_kind_tie_goes_to_high_quad ... ok
test both_hands_have_three_of_a_kind_tie_goes_to_highest_ranked_triplet ... ok
test both_hands_have_the_same_pair_high_card_wins ... ok
test both_hands_have_two_identically_ranked_pairs_tie_goes_to_remaining_card_kicker ... ok
test even_though_an_ace_is_usually_high_a_5_high_straight_flush_is_the_lowest_scoring_straight_flush ... ok
test even_though_an_ace_is_usually_high_a_5_high_straight_is_the_lowest_scoring_straight ... ok
test flush_beats_a_straight ... ok
test four_of_a_kind_beats_a_full_house ... ok
test highest_card_out_of_all_hands_wins ... ok
test both_hands_have_two_pairs_highest_ranked_pair_wins ... ok
test full_house_beats_a_flush ... ok
test both_hands_have_a_straight_flush_tie_goes_to_highest_ranked_card ... ok
test highest_pair_wins ... ok
test multiple_hands_with_the_same_high_cards_tie_compares_next_highest_ranked_down_to_last_card ... ok
test both_hands_have_two_pairs_with_the_same_highest_ranked_pair_tie_goes_to_low_pair ... ok
test both_hands_with_a_straight_tie_goes_to_highest_ranked_card ... ok
test one_pair_beats_high_card ... ok
test single_hand_always_wins ... ok
test straight_flush_beats_four_of_a_kind ... ok
test three_of_a_kind_beats_two_pair ... ok
test both_hands_have_two_pairs_that_add_to_the_same_value_win_goes_to_highest_pair ... ok
test winning_high_card_hand_also_has_the_lowest_card ... ok
test with_multiple_decks_both_hands_have_a_full_house_with_the_same_triplet_tie_goes_to_the_pair ... ok
test two_pairs_beats_one_pair ... ok
test with_multiple_decks_both_hands_with_identical_four_of_a_kind_tie_determined_by_kicker ... ok
test with_multiple_decks_two_players_can_have_same_three_of_a_kind_ties_go_to_highest_remaining_cards ... ok
test two_pairs_first_ranked_by_largest_pair ... ok
test result: ok. 37 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
Doc-tests poker
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
``` | 0 | 0.956713 | 1 | 0.956713 | game-dev | MEDIA | 0.359746 | game-dev | 0.952949 | 1 | 0.952949 |
SuikoAkari/AnimeGame-CBT-1-Server | 4,690 | GenshinCBTServer/Player/GameEntityItem.cs | using GenshinCBTServer.Controllers;
using GenshinCBTServer.Excel;
using GenshinCBTServer.Protocol;
using Google.Protobuf.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static GenshinCBTServer.ResourceManager;
namespace GenshinCBTServer.Player
{
public class GameEntityItem : GameEntity
{
public GameItem item;
public override void InitProps()
{
FightPropUpdate(FightPropType.FIGHT_PROP_BASE_HP, 1f);
FightPropUpdate(FightPropType.FIGHT_PROP_BASE_DEFENSE, 1);
FightPropUpdate(FightPropType.FIGHT_PROP_BASE_ATTACK, 1);
FightPropUpdate(FightPropType.FIGHT_PROP_ATTACK, 1);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_ATTACK, 1); //TODO calculate total attack
FightPropUpdate(FightPropType.FIGHT_PROP_HP, 1f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_HP, 1f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_HP, 1f); //TODO calculate total hp
FightPropUpdate(FightPropType.FIGHT_PROP_HP_PERCENT, 0);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_DEFENSE, 100);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_SPEED, 0.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_FIRE_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_ELEC_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_WATER_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_GRASS_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_WIND_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_ICE_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_CUR_ROCK_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_FIRE_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_ELEC_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_WATER_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_GRASS_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_WIND_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_ICE_ENERGY, 100.0f);
FightPropUpdate(FightPropType.FIGHT_PROP_MAX_ROCK_ENERGY, 100.0f);
props[(uint)PropType.PROP_EXP] = new PropValue() { Ival = 1, Val = 1, Type = (uint)PropType.PROP_EXP };
props[(uint)PropType.PROP_LEVEL] = new PropValue() { Ival = 1, Val = (long)1, Type = (uint)PropType.PROP_LEVEL };
}
public GameEntityItem(uint entityId, uint id, MotionInfo motionInfo, GameItem item) : base(entityId, id, motionInfo, ProtEntityType.ProtEntityGadget)
{
InitProps();
this.entityId = entityId;
this.id = id;
this.motionInfo = motionInfo;
this.item = item;
}
public void FightPropUpdate(FightPropType key, float value)
{
fightprops[(uint)key] = value;
}
public override SceneEntityInfo asInfo()
{
SceneEntityInfo info = new SceneEntityInfo()
{
EntityType = EntityType,
EntityId = entityId,
MotionInfo = motionInfo,
LifeState = (uint)LifeState.LIFE_ALIVE,
AiInfo = new() { IsAiOpen = true },
// EntityCase = SceneEntityInfo.EntityOneofCase.Gadget
};
info.PropMap.Add(props);
// info.FightPropMap.Add(fightprops);
info.Gadget = new SceneGadgetInfo()
{
GadgetId = item.GetExcel().gadgetId,
BornType = GadgetBornType.GadgetBornInAir,
GadgetState = state,
IsEnableInteract = true,
AuthorityPeerId = owner,
// GadgetType = 1
};
// info.Gadget.ItemId = item.id;
info.Gadget.TrifleItem = item.toProtoItem();
// if (chest_drop > 0) info.Gadget.GadgetType = 1;
return info;
}
public override bool onInteract(YPlayer session, GadgetInteractReq req)
{
session.world.KillEntities(new List<GameEntity>() { this }, VisionType.VisionNone);
session.AddItem(item);
session.SendPacket((uint)CmdType.GadgetInteractRsp, new GadgetInteractRsp() { Retcode = (int)0, GadgetEntityId = req.GadgetEntityId, GadgetId = id, InteractType = InteractType.InteractPickItem, OpType = InterOpType.InterOpStart });
return true;
}
}
}
| 0 | 0.80051 | 1 | 0.80051 | game-dev | MEDIA | 0.956231 | game-dev | 0.939594 | 1 | 0.939594 |
mcMMO-Dev/mcMMO | 4,435 | src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java | package com.gmail.nossr50.worldguard;
import static org.bukkit.Bukkit.getServer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class WorldGuardManager {
private static WorldGuardManager instance;
private WorldGuardPlugin worldGuardPluginRef;
public static WorldGuardManager getInstance() {
if (instance == null) {
instance = new WorldGuardManager();
}
return instance;
}
public boolean hasMainFlag(Player player) {
if (player == null) {
return false;
}
BukkitPlayer localPlayer = BukkitAdapter.adapt(player);
com.sk89q.worldedit.util.Location loc = localPlayer.getLocation();
//WorldGuardPlugin worldGuard = getWorldGuard();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer()
.createQuery();
//ApplicableRegionSet set = query.getApplicableRegions(loc);
return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player),
WorldGuardFlags.MCMMO_ENABLE_WG_FLAG);
}
public boolean hasXPFlag(Player player) {
if (player == null) {
return false;
}
BukkitPlayer localPlayer = BukkitAdapter.adapt(player);
com.sk89q.worldedit.util.Location loc = localPlayer.getLocation();
//WorldGuardPlugin worldGuard = getWorldGuard();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer()
.createQuery();
//ApplicableRegionSet set = query.getApplicableRegions(loc);
return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player),
WorldGuardFlags.MCMMO_XP_WG_FLAG);
}
public boolean hasHardcoreFlag(Player player) {
if (player == null) {
return false;
}
BukkitPlayer localPlayer = BukkitAdapter.adapt(player);
com.sk89q.worldedit.util.Location loc = localPlayer.getLocation();
//WorldGuardPlugin worldGuard = getWorldGuard();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer()
.createQuery();
//ApplicableRegionSet set = query.getApplicableRegions(loc);
return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player),
WorldGuardFlags.MCMMO_HARDCORE_WG_FLAG);
}
private WorldGuardPlugin getWorldGuard() {
Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard");
// WorldGuard may not be loaded
if (!(plugin instanceof WorldGuardPlugin)) {
return null; // Maybe you want throw an exception instead
}
worldGuardPluginRef = (WorldGuardPlugin) plugin;
return worldGuardPluginRef;
}
public void registerFlags() {
try {
FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry();
try {
// register our flag with the registry
registry.register(WorldGuardFlags.MCMMO_ENABLE_WG_FLAG);
registry.register(WorldGuardFlags.MCMMO_XP_WG_FLAG);
registry.register(WorldGuardFlags.MCMMO_HARDCORE_WG_FLAG);
LogUtils.debug(mcMMO.p.getLogger(), "Registered WG flags successfully!");
} catch (FlagConflictException e) {
e.printStackTrace();
mcMMO.p.getLogger().warning("Failed to register WG flags!");
// some other plugin registered a flag by the same name already.
// you may want to re-register with a different name, but this
// could cause issues with saved flags in region files. it's better
// to print a message to let the server admin know of the conflict
}
} catch (NoClassDefFoundError e) {
System.out.println("[mcMMO] Could not register WG Flags!"); //Don't use the Logger here
}
}
}
| 0 | 0.719856 | 1 | 0.719856 | game-dev | MEDIA | 0.915066 | game-dev | 0.590329 | 1 | 0.590329 |
theonedev/onedev | 1,299 | server-plugin/server-plugin-pack-nuget/src/main/java/io/onedev/server/plugin/pack/nuget/NugetPackSupport.java | package io.onedev.server.plugin.pack.nuget;
import org.apache.wicket.Component;
import org.apache.wicket.model.LoadableDetachableModel;
import io.onedev.server.OneDev;
import io.onedev.server.service.PackService;
import io.onedev.server.model.Pack;
import io.onedev.server.model.Project;
import io.onedev.server.pack.PackSupport;
public class NugetPackSupport implements PackSupport {
public static final String TYPE = "NuGet";
@Override
public int getOrder() {
return 250;
}
@Override
public String getPackType() {
return TYPE;
}
@Override
public String getPackIcon() {
return "nuget";
}
@Override
public String getReference(Pack pack, boolean withProject) {
var reference = pack.getName() + "-" + pack.getVersion();
if (withProject)
reference = pack.getProject().getPath() + ":" + reference;
return reference;
}
@Override
public Component renderContent(String componentId, Pack pack) {
var packId = pack.getId();
return new NugetPackPanel(componentId, new LoadableDetachableModel<>() {
@Override
protected Pack load() {
return OneDev.getInstance(PackService.class).load(packId);
}
});
}
@Override
public Component renderHelp(String componentId, Project project) {
return new NugetHelpPanel(componentId, project.getPath());
}
}
| 0 | 0.917167 | 1 | 0.917167 | game-dev | MEDIA | 0.545403 | game-dev | 0.727354 | 1 | 0.727354 |
Athlaeos/ValhallaMMO | 2,412 | core/src/main/java/me/athlaeos/valhallammo/skills/perkunlockconditions/implementations/AllPerksUnlockedRequirement.java | package me.athlaeos.valhallammo.skills.perkunlockconditions.implementations;
import me.athlaeos.valhallammo.localization.TranslationManager;
import me.athlaeos.valhallammo.playerstats.profiles.ProfileRegistry;
import me.athlaeos.valhallammo.playerstats.profiles.implementations.PowerProfile;
import me.athlaeos.valhallammo.skills.skills.Perk;
import me.athlaeos.valhallammo.skills.perkunlockconditions.UnlockCondition;
import me.athlaeos.valhallammo.skills.skills.PerkRegistry;
import me.athlaeos.valhallammo.utility.Utils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class AllPerksUnlockedRequirement implements UnlockCondition {
private List<String> perks = new ArrayList<>();
@SuppressWarnings("unchecked")
@Override
public void initCondition(Object value) {
if (value instanceof List<?>){
perks = (List<String>) value;
}
}
@Override
public String getValuePlaceholder() {
return "requireperk_all";
}
@Override
public boolean canUnlock(Player p, boolean forceTrue) {
PowerProfile profile = ProfileRegistry.getPersistentProfile(p, PowerProfile.class);
Collection<String> unlocked = new HashSet<>(profile.getUnlockedPerks());
unlocked.addAll(profile.getPermanentlyUnlockedPerks());
return perks == null || perks.isEmpty() ||
unlocked.containsAll(perks);
}
@Override
public UnlockCondition createInstance() {
return new AllPerksUnlockedRequirement();
}
@Override
public String getFailedConditionMessage() {
return TranslationManager.getTranslation("perk_requirement_warning_perks");
}
@Override
public String getFailurePlaceholder() {
return "warning_all_perks";
}
@Override
public List<String> getConditionMessages() {
String format = TranslationManager.getTranslation("perk_format_requirement_all");
String entry = TranslationManager.getTranslation("perk_format_requirement");
List<String> result = new ArrayList<>();
result.add(format);
for (String p : perks){
Perk perk = PerkRegistry.getPerk(p);
if (perk != null) result.add(Utils.chat(entry.replace("%perk_required%", perk.getDisplayName())));
}
return result;
}
}
| 0 | 0.878075 | 1 | 0.878075 | game-dev | MEDIA | 0.590334 | game-dev | 0.881638 | 1 | 0.881638 |
Eigenstate/vmd-python | 1,959 | vmd/vmd_src/src/P_GrabTool.C | /***************************************************************************
*cr
*cr (C) Copyright 1995-2019 The Board of Trustees of the
*cr University of Illinois
*cr All Rights Reserved
*cr
***************************************************************************/
/***************************************************************************
* RCS INFORMATION:
*
* $RCSfile: P_GrabTool.C,v $
* $Author: johns $ $Locker: $ $State: Exp $
* $Revision: 1.34 $ $Date: 2019/01/17 21:21:00 $
*
***************************************************************************
* DESCRIPTION:
* This is Paul's new Tracker code -- pgrayson@ks.uiuc.edu
*
*
***************************************************************************/
#include "P_GrabTool.h"
#include "utilities.h"
#include "Matrix4.h"
GrabTool::GrabTool(int id, VMDApp *vmdapp, Displayable *disp)
: Tool(id, vmdapp, disp) {
targetting=0;
}
void GrabTool::do_event() {
float mypos[3], kick[3]={.5,0,0}; /// XXX user configurable
float zero[9]={0,0,0, 0,0,0, 0,0,0};
Matrix4 o;
if (!position())
return;
if (!wasgrabbing && isgrabbing()) {
if (target(TARGET_GRAB, mypos, 0)) {
o = *orientation();
vec_copy(mypos, position());
o.multpoint3d(kick, kick);
setforcefield(position(), kick, zero);
sendforce();
targetting = 1;
} else {
targetting=0;
}
} else if (!isgrabbing() && wasgrabbing && targetting) {
o = *orientation();
vec_copy(mypos, position());
o.multpoint3d(kick, kick);
vec_negate(kick, kick);
setforcefield(position(), kick, zero);
sendforce();
} else {
forceoff();
}
wasgrabbing = isgrabbing();
}
| 0 | 0.719914 | 1 | 0.719914 | game-dev | MEDIA | 0.703147 | game-dev | 0.856687 | 1 | 0.856687 |
Chman/Typogenic | 6,603 | Typogenic/Editor/TypogenicTextEditor.cs | using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using System;
[CustomEditor(typeof(TypogenicText)), CanEditMultipleObjects]
public class TypogenicTextEditor : Editor
{
protected SerializedProperty m_Font;
protected SerializedProperty m_Text;
protected SerializedProperty m_Size;
protected SerializedProperty m_Leading;
protected SerializedProperty m_Tracking;
protected SerializedProperty m_ParagraphSpacing;
protected SerializedProperty m_WordWrap;
protected SerializedProperty m_Alignment;
protected SerializedProperty m_FillMode;
protected SerializedProperty m_ColorTopLeft;
protected SerializedProperty m_ColorTopRight;
protected SerializedProperty m_ColorBottomLeft;
protected SerializedProperty m_ColorBottomRight;
protected SerializedProperty m_GenerateNormals;
protected SerializedProperty m_Stationary;
protected SerializedProperty m_EnableClickSupport;
protected SerializedProperty m_DrawGlyphBoundsGizmos;
Vector2 scrollText;
void OnEnable()
{
m_Font = serializedObject.FindProperty("Font");
m_Text = serializedObject.FindProperty("Text");
m_Size = serializedObject.FindProperty("Size");
m_Leading = serializedObject.FindProperty("Leading");
m_Tracking = serializedObject.FindProperty("Tracking");
m_ParagraphSpacing = serializedObject.FindProperty("ParagraphSpacing");
m_WordWrap = serializedObject.FindProperty("WordWrap");
m_Alignment = serializedObject.FindProperty("Alignment");
m_FillMode = serializedObject.FindProperty("FillMode");
m_ColorTopLeft = serializedObject.FindProperty("ColorTopLeft");
m_ColorTopRight = serializedObject.FindProperty("ColorTopRight");
m_ColorBottomLeft = serializedObject.FindProperty("ColorBottomLeft");
m_ColorBottomRight = serializedObject.FindProperty("ColorBottomRight");
m_GenerateNormals = serializedObject.FindProperty("GenerateNormals");
m_Stationary = serializedObject.FindProperty("Stationary");
m_EnableClickSupport = serializedObject.FindProperty("EnableClickSupport");
m_DrawGlyphBoundsGizmos = serializedObject.FindProperty("DrawGlyphBoundsGizmos");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
/*
* This method has been deprecated:
*
* EditorGUIUtility.LookLikeControls();
*/
EditorGUILayout.PropertyField(m_Font);
EditorGUILayout.PropertyField(m_GenerateNormals);
EditorGUILayout.PropertyField(m_EnableClickSupport);
if (m_EnableClickSupport.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DrawGlyphBoundsGizmos);
EditorGUILayout.PropertyField(m_Stationary, new GUIContent("Static"));
EditorGUI.indentLevel--;
}
EditorGUILayout.PrefixLabel(String.Format("Text (w: {0:F2}, h: {1:F2})", ((TypogenicText)target).Width, ((TypogenicText)target).Height));
scrollText = EditorGUILayout.BeginScrollView(scrollText, GUILayout.MinHeight(85f), GUILayout.MaxHeight(200f));
m_Text.stringValue = EditorGUILayout.TextArea(m_Text.stringValue, GUILayout.MinHeight(85f), GUILayout.MaxHeight(200f));
EditorGUILayout.EndScrollView();
EditorGUILayout.PropertyField(m_Size, new GUIContent("Character Size"));
EditorGUILayout.PropertyField(m_Tracking, new GUIContent("Character Spacing (Tracking)"));
EditorGUILayout.PropertyField(m_Leading, new GUIContent("Line Spacing (Leading)"));
EditorGUILayout.PropertyField(m_ParagraphSpacing);
EditorGUILayout.PropertyField(m_Alignment);
EditorGUILayout.PropertyField(m_WordWrap);
EditorGUILayout.PropertyField(m_FillMode);
switch (m_FillMode.enumValueIndex)
{
case (int)TFillMode.SingleColor:
EditorGUILayout.PropertyField(m_ColorTopLeft, new GUIContent("Color (RGB + A)"));
break;
case (int)TFillMode.VerticalGradient:
EditorGUILayout.PropertyField(m_ColorTopLeft, new GUIContent("Top Color (RGB + A)"));
EditorGUILayout.PropertyField(m_ColorBottomLeft, new GUIContent("Bottom Color (RGB + A)"));
break;
case (int)TFillMode.HorizontalGradient:
EditorGUILayout.PropertyField(m_ColorTopLeft, new GUIContent("Left Color (RGB + A)"));
EditorGUILayout.PropertyField(m_ColorBottomLeft, new GUIContent("Right Color (RGB + A)"));
break;
case (int)TFillMode.QuadGradient:
EditorGUILayout.PropertyField(m_ColorTopLeft, new GUIContent("Top Left Color (RGB + A)"));
EditorGUILayout.PropertyField(m_ColorTopRight, new GUIContent("Top Right Color (RGB + A)"));
EditorGUILayout.PropertyField(m_ColorBottomLeft, new GUIContent("Bottom Left Color (RGB + A)"));
EditorGUILayout.PropertyField(m_ColorBottomRight, new GUIContent("Bottom Right Color (RGB + A)"));
break;
default:
break;
}
if (serializedObject.ApplyModifiedProperties() || Event.current.commandName == "UndoRedoPerformed")
{
foreach (TypogenicText t in targets)
{
if (t.enabled && t.gameObject.activeInHierarchy && PrefabUtility.GetPrefabType(target) != PrefabType.Prefab)
t.RebuildMesh();
}
}
}
void OnSceneGUI()
{
TypogenicText src = (TypogenicText)target;
if (src.WordWrap > 0f)
{
Vector3 alignmentOffset = Vector3.zero;
if (src.Alignment == TTextAlignment.Center) alignmentOffset = new Vector3(-src.WordWrap * 0.5f, 0f, 0f);
else if (src.Alignment == TTextAlignment.Right) alignmentOffset = new Vector3(-src.WordWrap, 0f, 0f);
Vector3 v1 = src.transform.TransformPoint(alignmentOffset);
Vector3 v2 = src.transform.TransformPoint(alignmentOffset + new Vector3(src.WordWrap, 0f, 0f));
Vector3 v3 = src.transform.TransformPoint(alignmentOffset + new Vector3(0f, -src.Height, 0f));
Vector3 v4 = src.transform.TransformPoint(alignmentOffset + new Vector3(src.WordWrap, -src.Height, 0f));
Handles.color = Color.yellow;
Handles.DrawLine(v1, v2);
Handles.DrawLine(v1, v3);
Handles.DrawLine(v4, v3);
Handles.DrawLine(v2, v4);
}
}
[MenuItem("GameObject/Create Other/Typogenic Text", false, 1500)]
public static void CreateNewTypogenicText()
{
GameObject gameObject = new GameObject("New Typogenic Text");
gameObject.AddComponent<TypogenicText>();
#if (UNITY_4_3 || UNITY_4_5 || UNITY_4_6)
gameObject.GetComponent<MeshRenderer>().castShadows = false;
#else
gameObject.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.Off;
#endif
gameObject.GetComponent<MeshRenderer>().receiveShadows = false;
Selection.objects = new GameObject[1] { gameObject };
EditorApplication.ExecuteMenuItem("GameObject/Move To View");
#if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
#else
Undo.RegisterCreatedObjectUndo(gameObject, "Created New Typogenic Text");
#endif
}
}
| 0 | 0.908441 | 1 | 0.908441 | game-dev | MEDIA | 0.982677 | game-dev | 0.980986 | 1 | 0.980986 |
gscept/nebula | 2,597 | toolkit/toolkitutil/model/modelutil/modeldatabase.h | #pragma once
//------------------------------------------------------------------------------
/**
@class ToolkitUtil::ModelDatabase
Holds dictionary of import options, is also responsible for loading and saving them
(C) 2012-2016 Individual contributors, see AUTHORS file
*/
//------------------------------------------------------------------------------
#include "util/dictionary.h"
#include "util/string.h"
#include "core/singleton.h"
#include "core/refcounted.h"
#include "modelattributes.h"
#include "modelconstants.h"
#include "modelphysics.h"
namespace ToolkitUtil
{
class ModelDatabase: public Core::RefCounted
{
__DeclareSingleton(ModelDatabase);
__DeclareClass(ModelDatabase);
public:
/// constructor
ModelDatabase();
/// destructor
~ModelDatabase();
/// opens the database
void Open();
/// closes the database
void Close();
/// returns true if database is open
bool IsOpen() const;
/// load all attributes from a folder
void LoadAttributes(const Util::String& folder);
/// performs lookup on model attributes, loads from file if it doesn't exist
Ptr<ModelAttributes> LookupAttributes(const Util::String& name, bool reload = false);
/// checks if attributes exist
bool AttributesExist(const Util::String& name);
/// gets name of model attributes pointer
const Util::String& GetAttributesName(const Ptr<ModelAttributes>& attrs);
/// performs lookup on physics attributes, loads from file if it doesn't exist
Ptr<ModelPhysics> LookupPhysics(const Util::String& name, bool reload = false);
/// checks if attributes exist
bool PhysicsExist(const Util::String& name);
/// gets name of model attributes pointer
const Util::String& GetPhysicsName(const Ptr<ModelPhysics>& attrs);
/// performs lookup on model constants, loads from file if it doesn't exist
Ptr<ModelConstants> LookupConstants(const Util::String& name, bool reload = false);
/// checks if constants exist
bool ConstantsExist(const Util::String& name);
/// gets name of model constants
const Util::String& GetConstantsName(const Ptr<ModelConstants>& constants);
private:
bool isOpen;
Util::Dictionary<Util::String, Ptr<ModelAttributes>> modelAttributes;
Util::Dictionary<Util::String, Ptr<ModelConstants>> modelConstants;
Util::Dictionary<Util::String, Ptr<ModelPhysics>> modelPhysics;
};
//------------------------------------------------------------------------------
/**
*/
inline bool
ModelDatabase::IsOpen() const
{
return this->isOpen;
}
} | 0 | 0.885374 | 1 | 0.885374 | game-dev | MEDIA | 0.447645 | game-dev | 0.839268 | 1 | 0.839268 |
ay2015/AYUI8 | 5,576 | Ay/ay/SDK/HELPER/AnimateCode/Implements/Out/Zoom/AyAniZoomOut.cs | /**-----------------------------------------------
* * ====================www.ayjs.net 杨洋 wpfui.com ayui ay aaronyang======使用代码请注意侵权=========
*
* 作者:ay * 联系QQ:875556003 * 时间2019-06-14
* -----------------------------------------*/
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace ay.Animate
{
public class AyAniZoomOut : AyAnimateBaseOut
{
#region 构造函数
public AyAniZoomOut(FrameworkElement _element)
: base("ZoomOut", _element)
{ base.AnimateSpeed = 450; }
public AyAniZoomOut(FrameworkElement _element, Action _completed)
: base("ZoomOut", _element, _completed)
{ base.AnimateSpeed = 450; }
#endregion
#region 属性
#endregion
#region KeyFrames
DoubleAnimationUsingKeyFrames dauX = null;
DoubleAnimationUsingKeyFrames dauY = null;
DoubleAnimationUsingKeyFrames dauOpacty = null;
#endregion
protected override void Init()
{
SetBaseView();
ScaleTransform translation = new ScaleTransform(1, 1);
dauX = new DoubleAnimationUsingKeyFrames();
dauY = new DoubleAnimationUsingKeyFrames();
#region 基本工作,确定类型和name
//是否存在TranslateTransform
//动画要的类型是否存在
//动画要的类型的name是否存在,不存在就注册,结束后取消注册,删除动画
var ex = Element.RenderTransform;
if (ex == null || (ex as System.Windows.Media.MatrixTransform) != null)
{
var tg = new TransformGroup();
translation = new ScaleTransform(1, 1);
Win.RegisterName(translation.GetHashCode().ToString(), translation);
tg.Children.Add(translation);
Element.RenderTransform = tg;
}
else
{
var tg = ex as TransformGroup;
foreach (var item in tg.Children)
{
translation = item as ScaleTransform;
if (translation != null)
{
break;
}
}
if (translation != null)
{
var tex = translation.GetValue(FrameworkElement.NameProperty);
if (tex != null && tex.ToString() != "")
{
}
else
{
Win.RegisterName(translation.GetHashCode().ToString(), translation);
}
}
else
{
translation = new ScaleTransform(1, 1);
Win.RegisterName(translation.GetHashCode().ToString(), translation);
tg.Children.Add(translation);
Element.RenderTransform = tg;
}
}
#endregion
Win.RegisterResource(Story);
Story = (Storyboard)Story.CloneCurrentValue();
double danqianX = translation.ScaleX;
double danqianY = translation.ScaleY;
var k2 = new EasingDoubleKeyFrame(1, TimeSpan.FromMilliseconds(0));
var k3 = new EasingDoubleKeyFrame(0.3, TimeSpan.FromMilliseconds(AniTime(0.5)));
Storyboard.SetTargetName(dauX, Win.GetName(translation));
Storyboard.SetTargetProperty(dauX, new PropertyPath(ScaleTransform.ScaleXProperty));
dauX.KeyFrames.Add(k2);
dauX.KeyFrames.Add(k3);
Story.Children.Add(dauX);
dauX.FillBehavior = FillBehavior.Stop;
var k4 = new EasingDoubleKeyFrame(1, TimeSpan.FromMilliseconds(0));
var k5 = new EasingDoubleKeyFrame(0.3, TimeSpan.FromMilliseconds(AniTime(0.5)));
Storyboard.SetTargetName(dauY, Win.GetName(translation));
Storyboard.SetTargetProperty(dauY, new PropertyPath(ScaleTransform.ScaleYProperty));
dauY.KeyFrames.Add(k4);
dauY.KeyFrames.Add(k5);
Story.Children.Add(dauY);
dauY.FillBehavior = FillBehavior.Stop;
dauOpacty = new DoubleAnimationUsingKeyFrames();
var k6 = new EasingDoubleKeyFrame(1, TimeSpan.FromMilliseconds(AniTime(0)));
var k6_1 = new EasingDoubleKeyFrame(0, TimeSpan.FromMilliseconds(AniTime(0.5)));
dauOpacty.KeyFrames.Add(k6);
dauOpacty.KeyFrames.Add(k6_1);
Storyboard.SetTarget(dauOpacty, Element);
dauOpacty.FillBehavior = FillBehavior.Stop;
Storyboard.SetTargetProperty(dauOpacty, new PropertyPath(UIElement.OpacityProperty));
Story.Children.Add(dauOpacty);
Story.Completed += Story_Completed;
}
public override void Destroy()
{
Story.Completed -= Story_Completed;
Win.UnRegisterNameAll();
Win.UnRegisterResource(Story);
dauX.KeyFrames.Clear();
dauX = null;
dauY.KeyFrames.Clear();
dauY = null;
dauOpacty.KeyFrames.Clear();
dauOpacty = null;
Story = null;
}
private void Story_Completed(object sndr, EventArgs evtArgs)
{
try
{
Element.Visibility = Visibility.Collapsed;
Element.Opacity = 0;
base.CallClientCompleted();
}
catch
{
}
}
}
}
| 0 | 0.79547 | 1 | 0.79547 | game-dev | MEDIA | 0.335807 | game-dev | 0.975879 | 1 | 0.975879 |
mc-zhonghuang/Urticaria-Public | 4,455 | src/main/java/cn/hackedmc/urticaria/component/impl/hud/dragcomponent/api/SettingsRenderer.java | package cn.hackedmc.urticaria.component.impl.hud.dragcomponent.api;
import cn.hackedmc.urticaria.module.Module;
import cn.hackedmc.urticaria.ui.click.standard.components.value.ValueComponent;
import cn.hackedmc.urticaria.ui.click.standard.components.value.impl.*;
import cn.hackedmc.urticaria.value.impl.*;
import cn.hackedmc.urticaria.util.animation.Animation;
import cn.hackedmc.urticaria.util.animation.Easing;
import cn.hackedmc.urticaria.util.interfaces.InstanceAccess;
import cn.hackedmc.urticaria.util.render.ColorUtil;
import cn.hackedmc.urticaria.util.render.RenderUtil;
import cn.hackedmc.urticaria.util.vector.Vector2d;
import cn.hackedmc.urticaria.value.Value;
import net.minecraft.client.renderer.GlStateManager;
import java.awt.*;
import java.util.ArrayList;
public class SettingsRenderer implements InstanceAccess {
public Module module;
public DragValue positionValue;
public Animation animation = new Animation(Easing.EASE_OUT_ELASTIC, 300);
public boolean close;
public ArrayList<ValueComponent> valueList = new ArrayList<>();
public SettingsRenderer(Module module, DragValue positionValue) {
this.module = module;
this.positionValue = positionValue;
for (final Value<?> value : module.getAllValues()) {
if (value instanceof ModeValue) {
valueList.add(new ModeValueComponent(value));
} else if (value instanceof BooleanValue) {
valueList.add(new BooleanValueComponent(value));
} else if (value instanceof StringValue) {
valueList.add(new StringValueComponent(value));
} else if (value instanceof NumberValue) {
valueList.add(new NumberValueComponent(value));
} else if (value instanceof BoundsNumberValue) {
valueList.add(new BoundsNumberValueComponent(value));
} else if (value instanceof DragValue) {
valueList.add(new PositionValueComponent(value));
} else if (value instanceof ListValue<?>) {
valueList.add(new ListValueComponent(value));
} else if (value instanceof ColorValue) {
valueList.add(new ColorValueComponent(value));
}
}
}
public void render(int mouseX, int mouseY, float partialTicks) {
double width = 100, height = 100;
animation.setDuration(300);
animation.setEasing(close ? Easing.EASE_IN_EXPO : Easing.EASE_OUT_EXPO);
animation.run(close ? 0 : 1);
double scale = animation.getValue();
if (scale <= 0.0001) return;
NORMAL_RENDER_RUNNABLES.add(() -> {
GlStateManager.pushMatrix();
GlStateManager.translate((positionValue.position.x) * (1 - scale), (positionValue.position.y + positionValue.scale.y / 2) * (1 - scale), 0);
GlStateManager.scale(scale, scale, 1);
RenderUtil.roundedRectangle(positionValue.position.x - width - 10, positionValue.position.y + positionValue.scale.y / 2 - height / 2,
width, height, getTheme().getRound(), ColorUtil.withAlpha(getTheme().getBackgroundShade(), (int) (animation.getValue() * getTheme().getBackgroundShade().getAlpha())));
for (final ValueComponent valueComponent : valueList) {
if (valueComponent.getValue() != null && valueComponent.getValue().getHideIf() != null && valueComponent.getValue().getHideIf().getAsBoolean()) {
continue;
}
valueComponent.draw(new Vector2d( (positionValue.position.x +
(valueComponent.getValue().getHideIf() == null ? 0 : 10)),
(float) (positionValue.position.y)), mouseX, mouseY, partialTicks);
}
GlStateManager.popMatrix();
});
NORMAL_BLUR_RUNNABLES.add(() -> {
GlStateManager.pushMatrix();
GlStateManager.translate((positionValue.position.x) * (1 - scale), (positionValue.position.y + positionValue.scale.y / 2) * (1 - scale), 0);
GlStateManager.scale(scale, scale, 1);
RenderUtil.roundedRectangle(positionValue.position.x - width - 10, positionValue.position.y + positionValue.scale.y / 2 - height / 2,
width, height, getTheme().getRound(), Color.BLACK);
GlStateManager.popMatrix();
});
}
public void close() {
close = true;
}
}
| 0 | 0.906466 | 1 | 0.906466 | game-dev | MEDIA | 0.277547 | game-dev | 0.969188 | 1 | 0.969188 |
mkheirkhah/mptcp | 26,329 | src/core/model/timer-impl.h | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#ifndef TIMER_IMPL_H
#define TIMER_IMPL_H
#include "simulator.h"
#include "type-traits.h"
#include "fatal-error.h"
#include "int-to-type.h"
namespace ns3 {
class TimerImpl
{
public:
virtual ~TimerImpl ()
{
}
template <typename T1>
void SetArgs (T1 a1);
template <typename T1, typename T2>
void SetArgs (T1 a1, T2 a2);
template <typename T1, typename T2, typename T3>
void SetArgs (T1 a1, T2 a2, T3 a3);
template <typename T1, typename T2, typename T3,
typename T4>
void SetArgs (T1 a1, T2 a2, T3 a3, T4 a4);
template <typename T1, typename T2, typename T3,
typename T4, typename T5>
void SetArgs (T1 a1, T2 a2, T3 a3, T4 a4, T5 a5);
template <typename T1, typename T2, typename T3,
typename T4, typename T5, typename T6>
void SetArgs (T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6);
virtual EventId Schedule (const Time &delay) = 0;
virtual void Invoke (void) = 0;
};
template <typename T1>
struct TimerImplOne : public TimerImpl
{
virtual void SetArguments (T1 a1) = 0;
};
template <typename T1, typename T2>
struct TimerImplTwo : public TimerImpl
{
virtual void SetArguments (T1 a1,T2 a2) = 0;
};
template <typename T1, typename T2, typename T3>
struct TimerImplThree : public TimerImpl
{
virtual void SetArguments (T1 a1,T2 a2,T3 a3) = 0;
};
template <typename T1, typename T2, typename T3, typename T4>
struct TimerImplFour : public TimerImpl
{
virtual void SetArguments (T1 a1,T2 a2,T3 a3, T4 a4) = 0;
};
template <typename T1, typename T2, typename T3, typename T4, typename T5>
struct TimerImplFive : public TimerImpl
{
virtual void SetArguments (T1 a1,T2 a2,T3 a3, T4 a4, T5 a5) = 0;
};
template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct TimerImplSix : public TimerImpl
{
virtual void SetArguments (T1 a1,T2 a2,T3 a3, T4 a4, T5 a5, T6 a6) = 0;
};
template <typename T>
struct TimerTraits
{
typedef typename TypeTraits<typename TypeTraits<T>::ReferencedType>::NonConstType StoredType;
typedef const StoredType &ParameterType;
};
template <typename FN>
TimerImpl *
MakeTimerImpl (FN fn)
{
NS_ASSERT (TypeTraits<FN>::IsFunctionPointer);
return MakeTimerImpl (IntToType<TypeTraits<FN>::FunctionPointerTraits::nArgs> (), fn);
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<0>, FN fn)
{
struct FnTimerImplZero : public TimerImpl
{
FnTimerImplZero (FN fn)
: m_fn (fn)
{
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn);
}
virtual void Invoke (void)
{
m_fn ();
}
FN m_fn;
} *function = new FnTimerImplZero (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<1>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
struct FnTimerImplOne : public TimerImplOne<T1Parameter>
{
FnTimerImplOne (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1)
{
m_a1 = a1;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1);
}
virtual void Invoke (void)
{
m_fn (m_a1);
}
FN m_fn;
T1Stored m_a1;
} *function = new FnTimerImplOne (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<2>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
struct FnTimerImplTwo : public TimerImplTwo<T1Parameter,T2Parameter>
{
FnTimerImplTwo (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2)
{
m_a1 = a1;
m_a2 = a2;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1, m_a2);
}
virtual void Invoke (void)
{
m_fn (m_a1, m_a2);
}
FN m_fn;
T1Stored m_a1;
T2Stored m_a2;
} *function = new FnTimerImplTwo (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<3>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
struct FnTimerImplThree : public TimerImplThree<T1Parameter,T2Parameter,T3Parameter>
{
FnTimerImplThree (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1, m_a2, m_a3);
}
virtual void Invoke (void)
{
m_fn (m_a1, m_a2, m_a3);
}
FN m_fn;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
} *function = new FnTimerImplThree (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<4>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
struct FnTimerImplFour : public TimerImplFour<T1Parameter,T2Parameter,T3Parameter,T4Parameter>
{
FnTimerImplFour (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1, m_a2, m_a3, m_a4);
}
virtual void Invoke (void)
{
m_fn (m_a1, m_a2, m_a3, m_a4);
}
FN m_fn;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
} *function = new FnTimerImplFour (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<5>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg5Type T5;
typedef typename TimerTraits<T5>::ParameterType T5Parameter;
typedef typename TimerTraits<T5>::StoredType T5Stored;
struct FnTimerImplFive : public TimerImplFive<T1Parameter,T2Parameter,T3Parameter,T4Parameter,T5Parameter>
{
FnTimerImplFive (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4, T5Parameter a5)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
m_a5 = a5;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1, m_a2, m_a3, m_a4, m_a5);
}
virtual void Invoke (void)
{
m_fn (m_a1, m_a2, m_a3, m_a4, m_a5);
}
FN m_fn;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
T5Stored m_a5;
} *function = new FnTimerImplFive (fn);
return function;
}
template <typename FN>
TimerImpl *
MakeTimerImpl (IntToType<6>, FN fn)
{
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg5Type T5;
typedef typename TimerTraits<T5>::ParameterType T5Parameter;
typedef typename TimerTraits<T5>::StoredType T5Stored;
typedef typename TypeTraits<FN>::FunctionPointerTraits::Arg6Type T6;
typedef typename TimerTraits<T6>::ParameterType T6Parameter;
typedef typename TimerTraits<T6>::StoredType T6Stored;
struct FnTimerImplSix : public TimerImplSix<T1Parameter,T2Parameter,T3Parameter,T4Parameter,T5Parameter,T6Parameter>
{
FnTimerImplSix (FN fn)
: m_fn (fn)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4, T5Parameter a5, T6Parameter a6)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
m_a5 = a5;
m_a6 = a6;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_fn, m_a1, m_a2, m_a3, m_a4, m_a5, m_a6);
}
virtual void Invoke (void)
{
m_fn (m_a1, m_a2, m_a3, m_a4, m_a5, m_a6);
}
FN m_fn;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
T5Stored m_a5;
T6Stored m_a6;
} *function = new FnTimerImplSix (fn);
return function;
}
template <typename T>
struct TimerImplMemberTraits;
template <typename T>
struct TimerImplMemberTraits<T *>
{
static T &GetReference (T *p)
{
return *p;
}
};
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (MEM_PTR memPtr, OBJ_PTR objPtr)
{
NS_ASSERT (TypeTraits<MEM_PTR>::IsPointerToMember);
return MakeTimerImpl (IntToType<TypeTraits<MEM_PTR>::PointerToMemberTraits::nArgs> (), memPtr, objPtr);
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<0>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
struct MemFnTimerImplZero : public TimerImpl
{
MemFnTimerImplZero (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)();
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
} *function = new MemFnTimerImplZero (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<1>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
struct MemFnTimerImplOne : public TimerImplOne<T1Parameter>
{
MemFnTimerImplOne (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1)
{
m_a1 = a1;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
} *function = new MemFnTimerImplOne (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<2>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
struct MemFnTimerImplTwo : public TimerImplTwo<T1Parameter,T2Parameter>
{
MemFnTimerImplTwo (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2)
{
m_a1 = a1;
m_a2 = a2;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1, m_a2);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1, m_a2);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
T2Stored m_a2;
} *function = new MemFnTimerImplTwo (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<3>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
struct MemFnTimerImplThree : public TimerImplThree<T1Parameter,T2Parameter,T3Parameter>
{
MemFnTimerImplThree (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1, m_a2, m_a3);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1, m_a2, m_a3);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
} *function = new MemFnTimerImplThree (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<4>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
struct MemFnTimerImplFour : public TimerImplFour<T1Parameter,T2Parameter,T3Parameter,T4Parameter>
{
MemFnTimerImplFour (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1, m_a2, m_a3, m_a4);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1, m_a2, m_a3, m_a4);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
} *function = new MemFnTimerImplFour (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<5>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg5Type T5;
typedef typename TimerTraits<T5>::ParameterType T5Parameter;
typedef typename TimerTraits<T5>::StoredType T5Stored;
struct MemFnTimerImplFive : public TimerImplFive<T1Parameter,T2Parameter,T3Parameter,T4Parameter,T5Parameter>
{
MemFnTimerImplFive (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4,T5Parameter a5)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
m_a5 = a5;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1, m_a2, m_a3, m_a4, m_a5);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1, m_a2, m_a3, m_a4, m_a5);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
T5Stored m_a5;
} *function = new MemFnTimerImplFive (memPtr, objPtr);
return function;
}
template <typename MEM_PTR, typename OBJ_PTR>
TimerImpl *
MakeTimerImpl (IntToType<6>, MEM_PTR memPtr, OBJ_PTR objPtr)
{
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg1Type T1;
typedef typename TimerTraits<T1>::ParameterType T1Parameter;
typedef typename TimerTraits<T1>::StoredType T1Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg2Type T2;
typedef typename TimerTraits<T2>::ParameterType T2Parameter;
typedef typename TimerTraits<T2>::StoredType T2Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg3Type T3;
typedef typename TimerTraits<T3>::ParameterType T3Parameter;
typedef typename TimerTraits<T3>::StoredType T3Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg4Type T4;
typedef typename TimerTraits<T4>::ParameterType T4Parameter;
typedef typename TimerTraits<T4>::StoredType T4Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg5Type T5;
typedef typename TimerTraits<T5>::ParameterType T5Parameter;
typedef typename TimerTraits<T5>::StoredType T5Stored;
typedef typename TypeTraits<MEM_PTR>::PointerToMemberTraits::Arg6Type T6;
typedef typename TimerTraits<T6>::ParameterType T6Parameter;
typedef typename TimerTraits<T6>::StoredType T6Stored;
struct MemFnTimerImplSix : public TimerImplSix<T1Parameter,T2Parameter,T3Parameter,T4Parameter,T5Parameter,T6Parameter>
{
MemFnTimerImplSix (MEM_PTR memPtr, OBJ_PTR objPtr)
: m_memPtr (memPtr),
m_objPtr (objPtr)
{
}
virtual void SetArguments (T1Parameter a1, T2Parameter a2, T3Parameter a3, T4Parameter a4,T5Parameter a5,T6Parameter a6)
{
m_a1 = a1;
m_a2 = a2;
m_a3 = a3;
m_a4 = a4;
m_a5 = a5;
m_a6 = a6;
}
virtual EventId Schedule (const Time &delay)
{
return Simulator::Schedule (delay, m_memPtr, m_objPtr, m_a1, m_a2, m_a3, m_a4, m_a5, m_a6);
}
virtual void Invoke (void)
{
(TimerImplMemberTraits<OBJ_PTR>::GetReference (m_objPtr).*m_memPtr)(m_a1, m_a2, m_a3, m_a4, m_a5, m_a6);
}
MEM_PTR m_memPtr;
OBJ_PTR m_objPtr;
T1Stored m_a1;
T2Stored m_a2;
T3Stored m_a3;
T4Stored m_a4;
T5Stored m_a5;
T6Stored m_a6;
} *function = new MemFnTimerImplSix (memPtr, objPtr);
return function;
}
template <typename T1>
void
TimerImpl::SetArgs (T1 a1)
{
typedef struct TimerImplOne<
typename TimerTraits<T1>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1);
}
template <typename T1, typename T2>
void
TimerImpl::SetArgs (T1 a1, T2 a2)
{
typedef struct TimerImplTwo<
typename TimerTraits<T1>::ParameterType,
typename TimerTraits<T2>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1, a2);
}
template <typename T1, typename T2, typename T3>
void
TimerImpl::SetArgs (T1 a1, T2 a2, T3 a3)
{
typedef struct TimerImplThree<
typename TimerTraits<T1>::ParameterType,
typename TimerTraits<T2>::ParameterType,
typename TimerTraits<T3>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1, a2, a3);
}
template <typename T1, typename T2, typename T3, typename T4>
void
TimerImpl::SetArgs (T1 a1, T2 a2, T3 a3, T4 a4)
{
typedef struct TimerImplFour<
typename TimerTraits<T1>::ParameterType,
typename TimerTraits<T2>::ParameterType,
typename TimerTraits<T3>::ParameterType,
typename TimerTraits<T4>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1, a2, a3, a4);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
void
TimerImpl::SetArgs (T1 a1, T2 a2, T3 a3, T4 a4, T5 a5)
{
typedef struct TimerImplFive<
typename TimerTraits<T1>::ParameterType,
typename TimerTraits<T2>::ParameterType,
typename TimerTraits<T3>::ParameterType,
typename TimerTraits<T4>::ParameterType,
typename TimerTraits<T5>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1, a2, a3, a4, a5);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
void
TimerImpl::SetArgs (T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6)
{
typedef struct TimerImplSix<
typename TimerTraits<T1>::ParameterType,
typename TimerTraits<T2>::ParameterType,
typename TimerTraits<T3>::ParameterType,
typename TimerTraits<T4>::ParameterType,
typename TimerTraits<T5>::ParameterType,
typename TimerTraits<T6>::ParameterType
> TimerImplBase;
TimerImplBase *impl = dynamic_cast<TimerImplBase *> (this);
if (impl == 0)
{
NS_FATAL_ERROR ("You tried to set Timer arguments incompatible with its function.");
return;
}
impl->SetArguments (a1, a2, a3, a4, a5, a6);
}
} // namespace ns3
#endif /* TIMER_IMPL_H */
| 0 | 0.72518 | 1 | 0.72518 | game-dev | MEDIA | 0.192671 | game-dev | 0.742607 | 1 | 0.742607 |
TheFlyingFoool/DuckGameRebuilt | 2,407 | DuckGame/src/DuckGame/Levels/Levelup/VincentProduct.cs | namespace DuckGame
{
public class VincentProduct
{
public VPType type;
public int cost;
public int originalCost;
public int rarity;
public int count;
public Furniture furnitureData;
public Team teamData;
public bool sold;
public Sprite sprite
{
get
{
if (furnitureData != null)
return furnitureData.sprite;
return teamData != null ? teamData.hat : (Sprite)null;
}
}
public Color color => furnitureData != null ? furnitureData.group.color : Color.White;
public string name
{
get
{
if (furnitureData != null)
return furnitureData.name;
return teamData != null ? teamData.name + " HAT" : "Something";
}
}
public string group => furnitureData != null ? furnitureData.group.name : "HATS";
public string description
{
get
{
if (furnitureData != null)
return furnitureData.description;
return teamData != null ? teamData.description : "What a fine piece of furniture.";
}
}
public void Draw(Vec2 pos, float alpha, float deep)
{
if (furnitureData != null)
{
SpriteMap g = furnitureData.sprite;
if (furnitureData.icon != null)
g = furnitureData.icon;
if (furnitureData.font != null && furnitureData.sprite == null)
{
furnitureData.font.scale = new Vec2(1f, 1f);
furnitureData.font.Draw("F", pos + new Vec2(-3.5f, -3f), Color.Black, (Depth)(deep + 0.005f));
}
g.depth = (Depth)deep;
g.frame = 0;
g.alpha = alpha;
Graphics.Draw(g, pos.x, pos.y);
g.alpha = 1f;
}
if (teamData == null)
return;
SpriteMap hat = teamData.hat;
hat.depth = (Depth)deep;
hat.frame = 0;
hat.alpha = alpha;
hat.center = new Vec2(16f, 16f) + teamData.hatOffset;
Graphics.Draw(hat, pos.x, pos.y);
hat.alpha = 1f;
}
}
}
| 0 | 0.641003 | 1 | 0.641003 | game-dev | MEDIA | 0.904493 | game-dev | 0.778244 | 1 | 0.778244 |
OwlGamingCommunity/MTA | 5,134 | mods/deathmatch/resources/mdc/gui/tolls.lua | --[[
-- Copyright (C) Root Gaming - All Rights Reserved
-- Unauthorized copying of this file, via any medium is strictly prohibited
-- Proprietary and confidential
-- Written by Daniel Lett <me@lettuceboi.org>, December 2012
]]--
local SCREEN_X, SCREEN_Y = guiGetScreenSize()
local resourceName = getResourceName( getThisResource( ) )
------------------------------------------
function tolls ( locked )
showCursor( true, true )
local window = { }
local width = 520
local height = 590
local x = SCREEN_X / 2 - width / 2
local y = SCREEN_Y / 2 - height / 2
window.window = guiCreateWindow( x, y, width, height, "MDC Toll System", false )
window.tollImage = guiCreateStaticImage ( 10, 30, 500, 500, ":gps/map.jpg", false, window.window )
window.toll1 = guiCreateStaticImage( 22, 132, 10, 10, ( locked[ 1 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll1,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 1 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll2 = guiCreateStaticImage( 150, 154, 10, 10, ( locked[ 2 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll2,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 2 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll3 = guiCreateStaticImage( 231, 213, 10, 10, ( locked[ 3 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll3,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 3 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll4 = guiCreateStaticImage( 286, 202, 10, 10, ( locked[ 4 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll4,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 4 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll5 = guiCreateStaticImage( 390, 198, 10, 10, ( locked[ 5 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll5,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 5 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll6 = guiCreateStaticImage( 118, 313, 10, 10, ( locked[ 6 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll6,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 6 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll7 = guiCreateStaticImage( 125, 352, 10, 10, ( locked[ 7 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll7,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 7 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll8 = guiCreateStaticImage( 118, 372, 10, 10, ( locked[ 8 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll8,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 8 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll9 = guiCreateStaticImage( 33, 425, 10, 10, ( locked[ 9 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll9,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 9 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.toll10 = guiCreateStaticImage( 250, 375, 10, 10, ( locked[ 10 ] and ":mdc/img/red.png" or ":mdc/img/green.png" ), false, window.tollImage )
addEventHandler( "onClientGUIClick", window.toll10,
function()
triggerServerEvent( resourceName..":toggle_toll", localPlayer, 10 )
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
end
, false )
window.closeButton = guiCreateButton( 10, height - 50, width - 20, 40, "Close", false, window.window )
addEventHandler( "onClientGUIClick", window.closeButton,
function ()
guiSetVisible( window.window, false )
destroyElement( window.window )
window = { }
triggerServerEvent( "mdc:main", localPlayer )
end
, false )
end
------------------------------------------
addEvent( resourceName..":tolls", true )
addEventHandler( resourceName..":tolls", root, tolls ) | 0 | 0.753246 | 1 | 0.753246 | game-dev | MEDIA | 0.540615 | game-dev | 0.59717 | 1 | 0.59717 |
MATTYOneInc/AionEncomBase_Java8 | 2,760 | AL-Game/data/scripts/system/handlers/admincommands/SpawnNpc.java | /*
* This file is part of Encom.
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package admincommands;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.templates.spawns.SpawnTemplate;
import com.aionemu.gameserver.spawnengine.SpawnEngine;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.chathandlers.AdminCommand;
import java.io.IOException;
/**
* @author Luno
*/
public class SpawnNpc extends AdminCommand {
public SpawnNpc() {
super("spawn");
}
@Override
public void execute(Player admin, String... params) {
if (params.length < 1) {
PacketSendUtility.sendMessage(admin, "syntax //spawn <template_id> <respawn_time> (0 for temp)");
return;
}
int respawnTime = 295;
if (params.length >= 2) {
respawnTime = Integer.valueOf(params[1]);
}
int templateId = Integer.parseInt(params[0]);
float x = admin.getX();
float y = admin.getY();
float z = admin.getZ();
byte heading = admin.getHeading();
int worldId = admin.getWorldId();
SpawnTemplate spawn = SpawnEngine.addNewSpawn(worldId, templateId, x, y, z, heading, respawnTime);
if (spawn == null) {
PacketSendUtility.sendMessage(admin, "There is no template with id " + templateId);
return;
}
VisibleObject visibleObject = SpawnEngine.spawnObject(spawn, admin.getInstanceId());
if (visibleObject == null) {
PacketSendUtility.sendMessage(admin, "Spawn id " + templateId + " was not found!");
}
else if (respawnTime > 0) {
try {
DataManager.SPAWNS_DATA2.saveSpawn(admin, visibleObject, false);
}
catch (IOException e) {
e.printStackTrace();
PacketSendUtility.sendMessage(admin, "Could not save spawn");
}
}
String objectName = visibleObject.getObjectTemplate().getName();
PacketSendUtility.sendMessage(admin, objectName + " spawned");
}
@Override
public void onFail(Player player, String message) {
PacketSendUtility.sendMessage(player, "syntax //spawn <template_id> <respawn_time> (0 for temp)");
}
} | 0 | 0.951446 | 1 | 0.951446 | game-dev | MEDIA | 0.976366 | game-dev | 0.835732 | 1 | 0.835732 |
Horizon-Private-Server/horizon-forge | 8,292 | codegen/rc4/raids/badges.c | /***************************************************
* FILENAME : badges.c
*
* DESCRIPTION :
* Handles logic for the badges.
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
#include <tamtypes.h>
#include <libdl/dl.h>
#include <libdl/player.h>
#include <libdl/pad.h>
#include <libdl/time.h>
#include <libdl/net.h>
#include <libdl/game.h>
#include <libdl/string.h>
#include <libdl/math.h>
#include <libdl/math3d.h>
#include <libdl/stdio.h>
#include <libdl/gamesettings.h>
#include <libdl/dialog.h>
#include <libdl/sound.h>
#include <libdl/patch.h>
#include <libdl/ui.h>
#include <libdl/graphics.h>
#include <libdl/color.h>
#include <libdl/utils.h>
#include <libdl/random.h>
#include "maputils.h"
#include "shared.h"
#include "badges.h"
#include "game.h"
int badgesPlayerCooldown[GAME_MAX_PLAYERS][BANK_BADGE_EFFECT_COUNT] = {0};
int badgesPlayerTimeLastHit[GAME_MAX_PLAYERS] = {0};
int badgesPlayerTimeLastCantShoot[GAME_MAX_PLAYERS] = {0};
int badgesAmmoRegenAmount[WEAPON_SLOT_COUNT] = {
[WEAPON_SLOT_VIPERS] 5,
[WEAPON_SLOT_MAGMA_CANNON] 2,
[WEAPON_SLOT_ARBITER] 1,
[WEAPON_SLOT_FUSION_RIFLE] 1,
[WEAPON_SLOT_MINE_LAUNCHER] 1,
[WEAPON_SLOT_B6] 1,
[WEAPON_SLOT_OMNI_SHIELD] 1,
[WEAPON_SLOT_FLAIL] 2,
};
//--------------------------------------------------------------------------
void badgesOnPlayerGetHit(Player* player, int stateId, int a2, int a3, int t0) {
PlayerVTable* vtable = playerGetVTable(player);
if (!vtable) return;
//
if (stateId == PLAYER_STATE_GET_HIT) {
if (bankGetEquippedBadgeEffectStrength(player->PlayerId, RAIDS_BADGE_TYPE_BERSERKER) > 0) {
if (player->PlayerState == PLAYER_STATE_JUMP_ATTACK && player->PlayerMoby->AnimSeqId == 43) {
return;
}
}
}
vtable->UpdateState(player, stateId, a2, a3, t0);
}
//--------------------------------------------------------------------------
void badgesUpdate_HealthRegen(Player* player, int badgeIdx, float strength)
{
if (playerIsDead(player) || player->Health <= 0) return;
if ((gameGetTime() - badgesPlayerTimeLastCantShoot[player->PlayerId]) < TIME_SECOND) return;
int delayMs = (TIME_SECOND * 5);
int timeSinceLastHitMs = gameGetTime() - (badgesPlayerTimeLastHit[player->PlayerId] + delayMs);
if (timeSinceLastHitMs < 0) return;
timeSinceLastHitMs *= 1 + (0.5 * powf(strength, 2) * 5);
int cooldown = BADGES_HEALTH_REGEN_COOLDOWN_TICKS;
if (timeSinceLastHitMs < (TIME_SECOND * 15))
cooldown *= 5;
else if (timeSinceLastHitMs < (TIME_SECOND * 30))
cooldown *= 3;
else if (timeSinceLastHitMs < (TIME_SECOND * 60))
cooldown *= 2;
float newHealth = clamp(player->Health + BADGES_HEALTH_REGEN_AMOUNT, 0, player->MaxHealth);
if (newHealth != player->Health) {
playerSetHealth(player, newHealth);
//mobyPlaySoundByClass(1, 0, player->PlayerMoby, MOBY_ID_HEALTH_BOX_MULT);
badgesPlayerCooldown[player->PlayerId][badgeIdx] = cooldown;
}
}
//--------------------------------------------------------------------------
void badgesUpdate_AmmoRegen(Player* player, int badgeIdx, float strength)
{
if (playerIsDead(player)) return;
int delayMs = (TIME_SECOND * 1);
int timeSinceLastCantShootMs = gameGetTime() - (badgesPlayerTimeLastCantShoot[player->PlayerId] + delayMs);
if (timeSinceLastCantShootMs < 0) return;
timeSinceLastCantShootMs *= 1 + (0.5 * powf(strength, 2) * 5);
int cooldown = BADGES_AMMO_REGEN_COOLDOWN_TICKS;
if (timeSinceLastCantShootMs < (TIME_SECOND * 1))
cooldown *= 5;
else if (timeSinceLastCantShootMs < (TIME_SECOND * 3))
cooldown *= 3;
else if (timeSinceLastCantShootMs < (TIME_SECOND * 6))
cooldown *= 2;
int equippedGadgetId = player->WeaponHeldId;
int gadgetSlotId = weaponIdToSlot(equippedGadgetId);
if (!gadgetSlotId) return;
if (equippedGadgetId > 0) {
int equippedGadgetMaxAmmo = playerGetWeaponMaxAmmo(player->GadgetBox, equippedGadgetId);
if (equippedGadgetMaxAmmo) {
int equippedGadgetAmmo = player->GadgetBox->Gadgets[equippedGadgetId].Ammo;
float newAmmo = equippedGadgetAmmo + badgesAmmoRegenAmount[gadgetSlotId]*1;
if (newAmmo > equippedGadgetMaxAmmo) newAmmo = equippedGadgetMaxAmmo;
if (newAmmo != equippedGadgetAmmo) {
player->GadgetBox->Gadgets[equippedGadgetId].Ammo = newAmmo;
badgesPlayerCooldown[player->PlayerId][badgeIdx] = cooldown;
}
}
}
}
//--------------------------------------------------------------------------
void badgesUpdate_FlinchResistance(Player* player, int badgeIdx, float strength)
{
if (playerIsDead(player)) return;
if (player->timers.postHitInvinc == 47) {
player->timers.postHitInvinc += 100 * strength;
badgesPlayerCooldown[player->PlayerId][badgeIdx] = player->timers.postHitInvinc - 1;
}
}
//--------------------------------------------------------------------------
void badgesUpdate_Berserker(Player* player, int badgeIdx, float strength)
{
if (playerIsDead(player)) return;
if (player->PlayerState == PLAYER_STATE_JUMP_ATTACK && player->PlayerMoby->AnimSeqId == 43) {
if (player->PlayerMoby->AnimSeqT > 10 && player->PlayerMoby->AnimSeqT < 11 && player->Ground.onGood) {
// spawn explosion
u128 vPos = vector_read(player->PlayerPosition);
float damage = 50;
float radius = 10 + (25 * powf(strength, 2));
mobySpawnExplosion
(vPos, 1, 0x0, 0x0, 0x0, 0x10, 0x10, 0x0, 0, 0, 0, 0,
1, 0, 0x80080840, 0, 0x801040C0, 0x801010C0, 0x801010C0, 0x801010C0, 0x801010C0, 0x801010C0, 0x801010C0, 0x801010C0,
0x801040C0, 1, player->PlayerMoby, 0, vPos, radius/4, 0, damage, radius);
// play explosion sound
mobyPlaySoundByClass(0, 0, player->PlayerMoby, MOBY_ID_ARBITER_ROCKET0);
badgesPlayerCooldown[player->PlayerId][badgeIdx] = 10;
}
}
}
//--------------------------------------------------------------------------
void badgesUpdatePlayer(Player* player, enum RaidsBadgeType badgeType, int badgeIdx, float strength)
{
if (!player) return;
u32 cooldown = decTimerU32(&badgesPlayerCooldown[player->PlayerId][badgeIdx]);
if (cooldown) return;
switch (badgeType)
{
case RAIDS_BADGE_TYPE_HEALTH_REGEN: badgesUpdate_HealthRegen(player, badgeIdx, strength); break;
case RAIDS_BADGE_TYPE_AMMO_REGEN: badgesUpdate_AmmoRegen(player, badgeIdx, strength); break;
case RAIDS_BADGE_TYPE_SHARPSHOOTER: break; // handled by gamemode
case RAIDS_BADGE_TYPE_BERSERKER: badgesUpdate_Berserker(player, badgeIdx, strength); break;
case RAIDS_BADGE_TYPE_FLINCH_RESISTANCE: badgesUpdate_FlinchResistance(player, badgeIdx, strength); break;
case RAIDS_BADGE_TYPE_HEALTH_BUFF: break; // handled by gamemode
case RAIDS_BADGE_TYPE_ALPHA_AMMO_BUFF: break; // handled by gamemode
case RAIDS_BADGE_TYPE_ALPHA_AREA_BUFF: break; // handled by gamemode
case RAIDS_BADGE_TYPE_ALPHA_SPEED_BUFF: break; // handled by gamemode
case RAIDS_BADGE_TYPE_ALPHA_IMPACT_BUFF: break; // handled by gamemode
case RAIDS_BADGE_TYPE_EXPLODING_ENEMIES: break; // handled by gamemode
default: break;
}
}
//--------------------------------------------------------------------------
void badgesStart(void)
{
return;
if (!MapConfig.State) return;
Player** players = playerGetAll();
int i;
for (i = 0; i < GAME_MAX_PLAYERS; ++i) {
Player* player = players[i];
if (!playerIsValid(player))
continue;
// update time last had full health
if (player->PlayerState == PLAYER_STATE_GET_HIT)
badgesPlayerTimeLastHit[player->PlayerId] = gameGetTime();
if (player->timers.gadgetRefire > 0 || player->PlayerState == PLAYER_STATE_FLAIL_ATTACK)
badgesPlayerTimeLastCantShoot[player->PlayerId] = gameGetTime();
RaidsInventoryItem_t* badge = &MapConfig.State->PlayerStates[i].Inventory.Badge;
if (!badge)
continue;
int j;
for (j = 0; j < BANK_BADGE_EFFECT_COUNT; ++j) {
int badgeType = badge->BadgeData.Effects[j];
if (!badgeType) continue;
badgesUpdatePlayer(player, badgeType, j, badge->BadgeData.EffectStrength[j] / 255.0);
}
}
}
//--------------------------------------------------------------------------
void badgesInit(void)
{
return;
// hook blessings
HOOK_JAL(0x005E1DEC, &badgesOnPlayerGetHit);
}
| 0 | 0.90618 | 1 | 0.90618 | game-dev | MEDIA | 0.968947 | game-dev | 0.681124 | 1 | 0.681124 |
ClassiCube/MCGalaxy | 3,651 | MCGalaxy/Commands/World/CmdNewLvl.cs | /*
Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge)
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
https://opensource.org/license/ecl-2-0/
https://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Threading;
using MCGalaxy.Generator;
namespace MCGalaxy.Commands.World {
public sealed class CmdNewLvl : Command2 {
public override string name { get { return "NewLvl"; } }
public override string shortcut { get { return "Gen"; } }
public override string type { get { return CommandTypes.World; } }
public override LevelPermission defaultRank { get { return LevelPermission.Admin; } }
public override CommandPerm[] ExtraPerms {
get { return new[] { new CommandPerm(LevelPermission.Admin, "can generate maps with advanced themes") }; }
}
public override void Use(Player p, string message, CommandData data) {
string[] args = message.SplitSpaces(6);
if (args.Length < 4) { Help(p); return; }
Level lvl = null;
try {
lvl = GenerateMap(p, args, data);
if (lvl == null) return;
lvl.Save(true);
} finally {
if (lvl != null) lvl.Dispose();
Server.DoGC();
}
}
internal Level GenerateMap(Player p, string[] args, CommandData data) {
if (args.Length < 4) return null;
string theme = args.Length > 4 ? args[4] : Server.Config.DefaultMapGenTheme;
string seed = args.Length > 5 ? args[5] : "";
MapGen gen = MapGen.Find(theme);
ushort x = 0, y = 0, z = 0;
if (!MapGen.GetDimensions(p, args, 1, ref x, ref y, ref z)) return null;
if (gen != null && gen.Type == GenType.Advanced && !CheckExtraPerm(p, data, 1)) return null;
return MapGen.Generate(p, gen, args[0], x, y, z, seed);
}
public override void Help(Player p) {
p.Message("&T/NewLvl [name] [width] [height] [length] [theme] <seed>");
p.Message("&HCreates/generates a new level.");
p.Message(" &HSizes must be between 1 and 16384");
p.Message(" &HSeed is optional, and controls how the level is generated");
p.Message("&HUse &T/Help NewLvl themes &Hfor a list of themes.");
p.Message("&HUse &T/Help NewLvl [theme] &Hfor details on how seeds affect levels generated with that theme.");
}
public override void Help(Player p, string message) {
MapGen gen = MapGen.Find(message);
if (message.CaselessEq("theme") || message.CaselessEq("themes")) {
MapGen.PrintThemes(p);
} else if (gen == null) {
p.Message("No theme found with name \"{0}\".", message);
p.Message("&HUse &T/Help NewLvl themes &Hfor a list of themes.");
} else {
p.Message(gen.Desc);
}
}
}
}
| 0 | 0.852503 | 1 | 0.852503 | game-dev | MEDIA | 0.951914 | game-dev | 0.863877 | 1 | 0.863877 |
ProjectTSB/TheSkyBlessing | 4,080 | TheSkyBlessing/data/asset_manager/functions/effect/give/make_effect_data.mcfunction | #> asset_manager:effect/give/make_effect_data
#
# asset:effect の情報からエンティティに追加するエフェクトのストレージデータを作成する。
# 該当エフェクトが付与済みの場合 stack と duration について operation が
# add の場合、既存の値に加算
# replace の場合、既存値と新規値のうち大きい方に置換
# forceReplace の場合、新規値に上書きを行う
#
# @output storage asset:effect EffectData
# @within function asset_manager:effect/give/give
#> Private
# @private
#declare score_holder $OriginDuration
#declare score_holder $OriginStack
#declare score_holder $Duration
#declare score_holder $Stack
#declare score_holder $MaxDuration
#declare score_holder $MaxStack
# 計算用にスコアとして取得する
execute store result score $OriginDuration Temporary run data get storage asset:effect TargetEffectData.Duration
execute store result score $Duration Temporary run data get storage asset:effect Duration
execute store result score $MaxDuration Temporary run data get storage asset:effect MaxDuration
execute store result score $OriginStack Temporary run data get storage asset:effect TargetEffectData.Stack
execute store result score $Stack Temporary run data get storage asset:effect Stack
execute store result score $MaxStack Temporary run data get storage asset:effect MaxStack
# Operationに合わせてDurationとStackを計算する // forceReplaceはそのまま新しい値が使われるので何もしなくて良い
execute if data storage asset:effect {DurationOperation:"replace"} run scoreboard players operation $Duration Temporary > $OriginDuration Temporary
execute if data storage asset:effect {DurationOperation:"add"} run scoreboard players operation $Duration Temporary += $OriginDuration Temporary
execute if data storage asset:effect {StackOperation:"replace"} run scoreboard players operation $Stack Temporary > $OriginStack Temporary
execute if data storage asset:effect {StackOperation:"add"} run scoreboard players operation $Stack Temporary += $OriginStack Temporary
# 最大値を超えてたら最大値にする
scoreboard players operation $Duration Temporary < $MaxDuration Temporary
scoreboard players operation $Stack Temporary < $MaxStack Temporary
# データを作る
data modify storage asset:effect EffectData set value {}
data modify storage asset:effect EffectData.ID set from storage asset:effect ID
data modify storage asset:effect EffectData.Name set from storage asset:effect Name
data modify storage asset:effect EffectData.Description set from storage asset:effect Description
execute store result storage asset:effect EffectData.Duration int 1 run scoreboard players get $Duration Temporary
data modify storage asset:effect EffectData.Visible set from storage asset:effect Visible
execute store result storage asset:effect EffectData.Stack int 1 run scoreboard players get $Stack Temporary
data modify storage asset:effect EffectData.StackVisible set from storage asset:effect StackVisible
data modify storage asset:effect EffectData.IsBadEffect set from storage asset:effect IsBadEffect
data modify storage asset:effect EffectData.ProcessOnDied set from storage asset:effect ProcessOnDied
data modify storage asset:effect EffectData.RequireClearLv set from storage asset:effect RequireClearLv
data modify storage asset:effect EffectData.Field set from storage asset:effect Field
data modify storage asset:effect EffectData.Field merge from storage asset:effect FieldOverride
execute if data storage asset:effect TargetEffectData.Field run data modify storage asset:effect EffectData.PreviousField set from storage asset:effect TargetEffectData.Field
# イベント設定
execute unless data storage asset:effect TargetEffectData run data modify storage asset:effect EffectData.NextEvent set value "given"
execute if data storage asset:effect TargetEffectData run data modify storage asset:effect EffectData.NextEvent set value "re-given"
# リセット
scoreboard players reset $OriginDuration Temporary
scoreboard players reset $OriginStack Temporary
scoreboard players reset $Duration Temporary
scoreboard players reset $Stack Temporary
scoreboard players reset $MaxDuration Temporary
scoreboard players reset $MaxStack Temporary
| 0 | 0.868945 | 1 | 0.868945 | game-dev | MEDIA | 0.945865 | game-dev | 0.926892 | 1 | 0.926892 |
Brackeys/Bullet-Time-Project | 1,115 | Bullet Time/Assets/Standard Assets/ParticleSystems/Scripts/FireLight.cs | using System;
using UnityEngine;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Effects
{
public class FireLight : MonoBehaviour
{
private float m_Rnd;
private bool m_Burning = true;
private Light m_Light;
private void Start()
{
m_Rnd = Random.value*100;
m_Light = GetComponent<Light>();
}
private void Update()
{
if (m_Burning)
{
m_Light.intensity = 2*Mathf.PerlinNoise(m_Rnd + Time.time, m_Rnd + 1 + Time.time*1);
float x = Mathf.PerlinNoise(m_Rnd + 0 + Time.time*2, m_Rnd + 1 + Time.time*2) - 0.5f;
float y = Mathf.PerlinNoise(m_Rnd + 2 + Time.time*2, m_Rnd + 3 + Time.time*2) - 0.5f;
float z = Mathf.PerlinNoise(m_Rnd + 4 + Time.time*2, m_Rnd + 5 + Time.time*2) - 0.5f;
transform.localPosition = Vector3.up + new Vector3(x, y, z)*1;
}
}
public void Extinguish()
{
m_Burning = false;
m_Light.enabled = false;
}
}
}
| 0 | 0.613452 | 1 | 0.613452 | game-dev | MEDIA | 0.697608 | game-dev,graphics-rendering | 0.895367 | 1 | 0.895367 |
The-King-Destroy/YukiBot-MD | 4,258 | plugins/rpg-dungeon.js | let handler = async (m, { conn, command, usedPrefix }) => {
if (!global.db.data.chats[m.chat].economy && m.isGroup) {
return m.reply(`《✦》Los comandos de *Economía* están desactivados en este grupo.\n\nUn *administrador* puede activarlos con el comando:\n» *${usedPrefix}economy on*`)
}
let user = global.db.data.users[m.sender]
if (!user) global.db.data.users[m.sender] = user = { health: 100, coin: 0, exp: 0, lastDungeon: 0 }
if (user.health < 5)
return conn.reply(m.chat, `ꕥ No tienes suficiente salud para volver a la *mazmorra*.\n> Usa *"${usedPrefix}heal"* para curarte.`, m)
const cooldown = 18 * 60 * 1000
const ahora = Date.now()
if (ahora < user.lastDungeon) {
const restante = user.lastDungeon - ahora
const wait = formatTimeMs(restante)
return conn.reply(m.chat, `ꕥ Debes esperar *${wait}* para usar *${usedPrefix + command}* de nuevo.`, m)
}
user.lastDungeon = ahora + cooldown
const evento = pickRandom(eventos)
let monedas, experiencia, salud
if (evento.tipo === 'victoria') {
monedas = Math.floor(Math.random() * 3001) + 12000
experiencia = Math.floor(Math.random() * 71) + 30
salud = Math.floor(Math.random() * 3) + 8
user.coin += monedas
user.exp += experiencia
user.health -= salud
} else if (evento.tipo === 'derrota') {
monedas = Math.floor(Math.random() * 2001) + 6000
experiencia = Math.floor(Math.random() * 31) + 40
salud = Math.floor(Math.random() * 3) + 8
user.coin -= monedas
user.exp -= experiencia
user.health -= salud
if (user.coin < 0) user.coin = 0
if (user.exp < 0) user.exp = 0
} else {
experiencia = Math.floor(Math.random() * 61) + 30
user.exp += experiencia
}
if (user.health < 0) user.health = 0
const resultado = `❀ ${evento.mensaje} ${evento.tipo === 'trampa' ? '' : evento.tipo === 'victoria' ? `ganaste. *${monedas.toLocaleString()} ${currency}*` : `perdiste. *${monedas.toLocaleString()} ${currency}*`}`
await conn.reply(m.chat, resultado.trim(), m)
await global.db.write()
}
handler.tags = ['rpg']
handler.help = ['dungeon', 'mazmorra']
handler.command = ['dungeon', 'mazmorra']
handler.group = true
export default handler
function formatTimeMs(ms) {
const totalSec = Math.ceil(ms / 1000)
const min = Math.floor(totalSec / 60)
const sec = totalSec % 60
const partes = []
if (min) partes.push(`${min} minuto${min !== 1 ? 's' : ''}`)
partes.push(`${sec} segundo${sec !== 1 ? 's' : ''}`)
return partes.join(' ')
}
function pickRandom(list) {
return list[Math.floor(Math.random() * list.length)]
}
const eventos = [
{ tipo: 'victoria', mensaje: 'Derrotaste al guardián de las ruinas y reclamaste el tesoro antiguo,' },
{ tipo: 'victoria', mensaje: 'Descifraste los símbolos rúnicos y obtuviste recompensas ocultas,' },
{ tipo: 'victoria', mensaje: 'Encuentras al sabio de la mazmorra, quien te premia por tu sabiduría,' },
{ tipo: 'victoria', mensaje: 'El espíritu de la reina ancestral te bendice con una gema de poder,' },
{ tipo: 'victoria', mensaje: 'Superas la prueba de los espejos oscuros y recibes un artefacto único,' },
{ tipo: 'victoria', mensaje: 'Derrotas a un gólem de obsidiana y desbloqueas un acceso secreto,' },
{ tipo: 'victoria', mensaje: 'Salvas a un grupo de exploradores perdidos y ellos te recompensan,' },
{ tipo: 'victoria', mensaje: 'Consigues abrir la puerta del juicio y extraes un orbe milenario,' },
{ tipo: 'victoria', mensaje: 'Triunfas sobre un demonio ilusorio que custodiaba el sello perdido,' },
{ tipo: 'victoria', mensaje: 'Purificas el altar corrompido y recibes una bendición ancestral,' },
{ tipo: 'derrota', mensaje: 'Un espectro maldito te drena energía antes de que puedas escapar,' },
{ tipo: 'derrota', mensaje: 'Un basilisco te sorprende en la cámara oculta, huyes herido,' },
{ tipo: 'derrota', mensaje: 'Una criatura informe te roba parte de tu botín en la oscuridad,' },
{ tipo: 'derrota', mensaje: 'Fracasas al invocar un portal y quedas atrapado entre dimensiones,' },
{ tipo: 'derrota', mensaje: 'Pierdes el control de una reliquia y provocas tu propia caída,' },
{ tipo: 'trampa', mensaje: 'Activaste una trampa, pero logras evitar el daño y aprendes algo nuevo.' },
{ tipo: 'trampa', mensaje: 'La sala cambia de forma y pierdes tiempo explorando en círculos.' },
{ tipo: 'trampa', mensaje: 'Caes en una ilusión, fortaleces tu mente sin obtener riquezas.' }
] | 0 | 0.835396 | 1 | 0.835396 | game-dev | MEDIA | 0.726412 | game-dev | 0.805696 | 1 | 0.805696 |
TheAssemblyArmada/Thyme | 1,495 | src/game/logic/object/helper/objectdefectionhelper.h | /**
* @file
*
* @author Jonathan Wilson
*
* @brief Object Defection Helper
*
* @copyright Thyme 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.
* A full copy of the GNU General Public License can be found in
* LICENSE
*/
#pragma once
#include "always.h"
#include "objecthelper.h"
class ObjectDefectionHelperModuleData : public ModuleData
{
public:
ObjectDefectionHelperModuleData() {}
~ObjectDefectionHelperModuleData() override {}
};
class ObjectDefectionHelper : public ObjectHelper
{
IMPLEMENT_NAMED_POOL(ObjectDefectionHelper, ObjectDefectionHelperPool)
public:
ObjectDefectionHelper(Thing *thing, const ModuleData *module_data);
virtual ~ObjectDefectionHelper() override;
virtual NameKeyType Get_Module_Name_Key() const override;
virtual void CRC_Snapshot(Xfer *xfer) override;
virtual void Xfer_Snapshot(Xfer *xfer) override;
virtual void Load_Post_Process() override;
virtual BitFlags<DISABLED_TYPE_COUNT> Get_Disabled_Types_To_Process() const override;
virtual UpdateSleepTime Update() override;
void Start_Defection_Timer(unsigned int timer, bool do_effect);
private:
unsigned int m_startFrame;
unsigned int m_endFrame;
float m_effectTimer;
bool m_doEffect;
};
| 0 | 0.972094 | 1 | 0.972094 | game-dev | MEDIA | 0.353451 | game-dev | 0.758202 | 1 | 0.758202 |
DarkstarProject/darkstar | 1,687 | scripts/commands/delmission.lua | ---------------------------------------------------------------------------------------------------
-- func: delmission <logID> <missionID> <player>
-- desc: Deletes the given mission from the GM or target player.
---------------------------------------------------------------------------------------------------
require("scripts/globals/missions");
cmdprops =
{
permission = 1,
parameters = "sss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!delmission <logID> <missionID> {player}");
end;
function onTrigger(player, logId, missionId, target)
-- validate logId
local logName;
local logInfo = GetMissionLogInfo(logId);
if (logInfo == nil) then
error(player, "Invalid logID.");
return;
end
logName = logInfo.full_name;
logId = logInfo.mission_log;
-- validate missionId
local areaMissionIds = dsp.mission.id[dsp.mission.area[logId]]
if (missionId ~= nil) then
missionId = tonumber(missionId) or areaMissionIds[string.upper(missionId)] or _G[string.upper(missionId)];
end
if (missionId == nil or missionId < 0) then
error(player, "Invalid missionID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- delete mission
targ:delMission(logId, missionId);
player:PrintToPlayer(string.format("Deleted %s mission %i from %s.", logName, missionId, targ:getName()));
end;
| 0 | 0.910453 | 1 | 0.910453 | game-dev | MEDIA | 0.676231 | game-dev | 0.855652 | 1 | 0.855652 |
Gaby-Station/Gaby-Station | 1,675 | Content.Server/_Funkystation/Atmos/Reactions/ZaukerDecompositionReaction.cs | // SPDX-FileCopyrightText: 2025 Steve <marlumpy@gmail.com>
// SPDX-FileCopyrightText: 2025 marc-pelletier <113944176+marc-pelletier@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.Atmos;
using Content.Server.Atmos.EntitySystems;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Reactions;
using JetBrains.Annotations;
namespace Content.Server._Funkystation.Atmos.Reactions;
[UsedImplicitly]
public sealed partial class ZaukerDecompositionReaction : IGasReactionEffect
{
public ReactionResult React(GasMixture mixture, IGasMixtureHolder? holder, AtmosphereSystem atmosphereSystem, float heatScale)
{
if (mixture.Temperature > 20f && mixture.GetMoles(Gas.HyperNoblium) >= 5f)
return ReactionResult.NoReaction;
var initZauker = mixture.GetMoles(Gas.Zauker);
var initN2 = mixture.GetMoles(Gas.Nitrogen);
var burnedFuel = Math.Min(Atmospherics.ZaukerDecompositionMaxRate, Math.Min(initN2, initZauker));
if (burnedFuel <= 0 || initZauker - burnedFuel < 0)
return ReactionResult.NoReaction;
mixture.AdjustMoles(Gas.Zauker, -burnedFuel);
mixture.AdjustMoles(Gas.Oxygen, burnedFuel * 0.3f);
mixture.AdjustMoles(Gas.Nitrogen, burnedFuel * 0.7f);
var energyReleased = burnedFuel * Atmospherics.ZaukerDecompositionEnergy;
var heatCap = atmosphereSystem.GetHeatCapacity(mixture, true);
if (heatCap > Atmospherics.MinimumHeatCapacity)
mixture.Temperature = Math.Max((mixture.Temperature * heatCap + energyReleased) / heatCap, Atmospherics.TCMB);
return ReactionResult.Reacting;
}
} | 0 | 0.744779 | 1 | 0.744779 | game-dev | MEDIA | 0.918687 | game-dev | 0.783402 | 1 | 0.783402 |
thedarkcolour/ForestryCE | 4,529 | src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java | package forestry.factory.recipes.jei.fermenter;
import forestry.api.ForestryConstants;
import forestry.api.fuels.FermenterFuel;
import forestry.api.fuels.FuelManager;
import forestry.api.recipes.IFermenterRecipe;
import forestry.api.recipes.IVariableFermentable;
import forestry.core.config.Constants;
import forestry.core.recipes.jei.ForestryRecipeCategory;
import forestry.core.recipes.jei.ForestryRecipeType;
import forestry.factory.blocks.BlockTypeFactoryTesr;
import forestry.factory.features.FactoryBlocks;
import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.forge.ForgeTypes;
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder;
import mezz.jei.api.gui.builder.IRecipeSlotBuilder;
import mezz.jei.api.gui.drawable.IDrawable;
import mezz.jei.api.gui.drawable.IDrawableAnimated;
import mezz.jei.api.gui.drawable.IDrawableStatic;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.api.recipe.IFocusGroup;
import mezz.jei.api.recipe.RecipeIngredientRole;
import mezz.jei.api.recipe.RecipeType;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class FermenterRecipeCategory extends ForestryRecipeCategory<IFermenterRecipe> {
private static final ResourceLocation TEXTURE = ForestryConstants.forestry(Constants.TEXTURE_PATH_GUI + "/fermenter.png");
private final IDrawableAnimated progressBar0;
private final IDrawableAnimated progressBar1;
private final IDrawable tankOverlay;
private final IDrawable icon;
public FermenterRecipeCategory(IGuiHelper guiHelper) {
super(guiHelper.createDrawable(TEXTURE, 34, 18, 108, 60), "block.forestry.fermenter");
IDrawableStatic progressBarDrawable0 = guiHelper.createDrawable(TEXTURE, 176, 60, 4, 18);
this.progressBar0 = guiHelper.createAnimatedDrawable(progressBarDrawable0, 40, IDrawableAnimated.StartDirection.BOTTOM, false);
IDrawableStatic progressBarDrawable1 = guiHelper.createDrawable(TEXTURE, 176, 78, 4, 18);
this.progressBar1 = guiHelper.createAnimatedDrawable(progressBarDrawable1, 80, IDrawableAnimated.StartDirection.BOTTOM, false);
this.tankOverlay = guiHelper.createDrawable(TEXTURE, 192, 0, 16, 58);
ItemStack fermenter = new ItemStack(FactoryBlocks.TESR.get(BlockTypeFactoryTesr.FERMENTER).block());
this.icon = guiHelper.createDrawableIngredient(VanillaTypes.ITEM_STACK, fermenter);
}
@Override
public RecipeType<IFermenterRecipe> getRecipeType() {
return ForestryRecipeType.FERMENTER;
}
@Override
public IDrawable getIcon() {
return this.icon;
}
@Override
public void setRecipe(IRecipeLayoutBuilder builder, IFermenterRecipe recipe, IFocusGroup focuses) {
IRecipeSlotBuilder ingredientInputSlot = builder.addSlot(RecipeIngredientRole.INPUT, 51, 5)
.addIngredients(recipe.getInputItem());
Collection<FermenterFuel> fuels = FuelManager.fermenterFuel.values();
List<ItemStack> fuelInputs = fuels.stream().map(FermenterFuel::item).toList();
builder.addSlot(RecipeIngredientRole.INPUT, 41, 39)
.addItemStacks(fuelInputs);
FluidStack fluidInput = recipe.getInputFluid().copy();
fluidInput.setAmount(recipe.getFermentationValue());
builder.addSlot(RecipeIngredientRole.INPUT, 1, 1)
.setFluidRenderer(3000, false, 16, 58)
.setOverlay(this.tankOverlay, 0, 0)
.addIngredient(ForgeTypes.FLUID_STACK, fluidInput);
final int baseAmount = Math.round(recipe.getFermentationValue() * recipe.getModifier());
List<FluidStack> outputs =
Arrays.stream(recipe.getInputItem().getItems())
.map(fermentable -> {
int amount = baseAmount;
if (fermentable.getItem() instanceof IVariableFermentable variableFermentable) {
amount *= variableFermentable.getFermentationModifier(fermentable);
}
return new FluidStack(recipe.getOutput(), amount);
})
.toList();
IRecipeSlotBuilder fluidOutputSlot = builder.addSlot(RecipeIngredientRole.OUTPUT, 91, 1)
.setFluidRenderer(3000, false, 16, 58)
.setOverlay(this.tankOverlay, 0, 0)
.addIngredients(ForgeTypes.FLUID_STACK, outputs);
builder.createFocusLink(ingredientInputSlot, fluidOutputSlot);
}
@Override
public void draw(IFermenterRecipe recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) {
this.progressBar0.draw(graphics, 40, 14);
this.progressBar1.draw(graphics, 64, 28);
}
}
| 0 | 0.904895 | 1 | 0.904895 | game-dev | MEDIA | 0.984644 | game-dev | 0.944766 | 1 | 0.944766 |
Unity-Technologies/ai-planner-samples | 8,768 | Match3/Packages/generated.ai.planner.plans/Generated.AI.Planner.Plans/Match3Plan/Match3PlanExecutor.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Unity.AI.Planner;
using Unity.AI.Planner.Traits;
using UnityEngine;
using Generated.AI.Planner.StateRepresentation;
using Generated.AI.Planner.StateRepresentation.Match3Plan;
namespace Generated.AI.Planner.Plans.Match3Plan
{
public struct DefaultCumulativeRewardEstimator : ICumulativeRewardEstimator<StateData>
{
public BoundedValue Evaluate(StateData state)
{
return new BoundedValue(-5, 0, 5);
}
}
public struct TerminationEvaluator : ITerminationEvaluator<StateData>
{
public bool IsTerminal(StateData state, out float terminalReward)
{
terminalReward = 0f;
var terminal = false;
var SearchEndInstance = new SearchEnd();
if (SearchEndInstance.IsTerminal(state))
{
terminal = true;
terminalReward += SearchEndInstance.TerminalReward(state);
}
var SearchPrunedInstance = new SearchPruned();
if (SearchPrunedInstance.IsTerminal(state))
{
terminal = true;
terminalReward += SearchPrunedInstance.TerminalReward(state);
}
return terminal;
}
}
class Match3PlanExecutor : BaseTraitBasedPlanExecutor<TraitBasedObject, StateEntityKey, StateData, StateDataContext, StateManager, ActionKey>
{
static Dictionary<Guid, string> s_ActionGuidToNameLookup = new Dictionary<Guid,string>()
{
{ ActionScheduler.SwapRightGuid, nameof(SwapRight) },
{ ActionScheduler.SwapUpGuid, nameof(SwapUp) },
};
PlannerStateConverter<TraitBasedObject, StateEntityKey, StateData, StateDataContext, StateManager> m_StateConverter;
public Match3PlanExecutor(StateManager stateManager, PlannerStateConverter<TraitBasedObject, StateEntityKey, StateData, StateDataContext, StateManager> stateConverter)
{
m_StateManager = stateManager;
m_StateConverter = stateConverter;
}
public override string GetActionName(IActionKey actionKey)
{
s_ActionGuidToNameLookup.TryGetValue(((IActionKeyWithGuid)actionKey).ActionGuid, out var name);
return name;
}
protected override void Act(ActionKey actionKey)
{
var stateData = m_StateManager.GetStateData(CurrentPlanState, false);
var actionName = string.Empty;
switch (actionKey.ActionGuid)
{
case var actionGuid when actionGuid == ActionScheduler.SwapRightGuid:
actionName = nameof(SwapRight);
break;
case var actionGuid when actionGuid == ActionScheduler.SwapUpGuid:
actionName = nameof(SwapUp);
break;
}
var executeInfos = GetExecutionInfo(actionName);
if (executeInfos == null)
return;
var argumentMapping = executeInfos.GetArgumentValues();
var arguments = new object[argumentMapping.Count()];
var i = 0;
foreach (var argument in argumentMapping)
{
var split = argument.Split('.');
int parameterIndex = -1;
var traitBasedObjectName = split[0];
if (string.IsNullOrEmpty(traitBasedObjectName))
throw new ArgumentException($"An argument to the '{actionName}' callback on '{m_Actor?.name}' DecisionController is invalid");
switch (actionName)
{
case nameof(SwapRight):
parameterIndex = SwapRight.GetIndexForParameterName(traitBasedObjectName);
break;
case nameof(SwapUp):
parameterIndex = SwapUp.GetIndexForParameterName(traitBasedObjectName);
break;
}
if (parameterIndex == -1)
throw new ArgumentException($"Argument '{traitBasedObjectName}' to the '{actionName}' callback on '{m_Actor?.name}' DecisionController is invalid");
var traitBasedObjectIndex = actionKey[parameterIndex];
if (split.Length > 1) // argument is a trait
{
switch (split[1])
{
case nameof(Game):
var traitGame = stateData.GetTraitOnObjectAtIndex<Game>(traitBasedObjectIndex);
arguments[i] = split.Length == 3 ? traitGame.GetField(split[2]) : traitGame;
break;
case nameof(Cell):
var traitCell = stateData.GetTraitOnObjectAtIndex<Cell>(traitBasedObjectIndex);
arguments[i] = split.Length == 3 ? traitCell.GetField(split[2]) : traitCell;
break;
case nameof(Coordinate):
var traitCoordinate = stateData.GetTraitOnObjectAtIndex<Coordinate>(traitBasedObjectIndex);
arguments[i] = split.Length == 3 ? traitCoordinate.GetField(split[2]) : traitCoordinate;
break;
case nameof(Blocker):
var traitBlocker = stateData.GetTraitOnObjectAtIndex<Blocker>(traitBasedObjectIndex);
arguments[i] = split.Length == 3 ? traitBlocker.GetField(split[2]) : traitBlocker;
break;
}
}
else // argument is an object
{
var planStateId = stateData.GetTraitBasedObjectId(traitBasedObjectIndex);
GameObject dataSource;
if (m_PlanStateToGameStateIdLookup.TryGetValue(planStateId.Id, out var gameStateId))
dataSource = m_StateConverter.GetDataSource(new TraitBasedObjectId { Id = gameStateId });
else
dataSource = m_StateConverter.GetDataSource(planStateId);
Type expectedType = executeInfos.GetParameterType(i);
// FIXME - if this is still needed
// if (typeof(ITraitBasedObjectData).IsAssignableFrom(expectedType))
// {
// arguments[i] = dataSource;
// }
// else
{
arguments[i] = null;
var obj = dataSource;
if (obj != null && obj is GameObject gameObject)
{
if (expectedType == typeof(GameObject))
arguments[i] = gameObject;
if (typeof(Component).IsAssignableFrom(expectedType))
arguments[i] = gameObject == null ? null : gameObject.GetComponent(expectedType);
}
}
}
i++;
}
CurrentActionKey = actionKey;
StartAction(executeInfos, arguments);
}
public override ActionParameterInfo[] GetActionParametersInfo(IStateKey stateKey, IActionKey actionKey)
{
string[] parameterNames = {};
var stateData = m_StateManager.GetStateData((StateEntityKey)stateKey, false);
switch (((IActionKeyWithGuid)actionKey).ActionGuid)
{
case var actionGuid when actionGuid == ActionScheduler.SwapRightGuid:
parameterNames = SwapRight.parameterNames;
break;
case var actionGuid when actionGuid == ActionScheduler.SwapUpGuid:
parameterNames = SwapUp.parameterNames;
break;
}
var parameterInfo = new ActionParameterInfo[parameterNames.Length];
for (var i = 0; i < parameterNames.Length; i++)
{
var traitBasedObjectId = stateData.GetTraitBasedObjectId(((ActionKey)actionKey)[i]);
#if DEBUG
parameterInfo[i] = new ActionParameterInfo { ParameterName = parameterNames[i], TraitObjectName = traitBasedObjectId.Name.ToString(), TraitObjectId = traitBasedObjectId.Id };
#else
parameterInfo[i] = new ActionParameterInfo { ParameterName = parameterNames[i], TraitObjectName = traitBasedObjectId.ToString(), TraitObjectId = traitBasedObjectId.Id };
#endif
}
return parameterInfo;
}
}
}
| 0 | 0.890844 | 1 | 0.890844 | game-dev | MEDIA | 0.895902 | game-dev | 0.941395 | 1 | 0.941395 |
ryantpayton/MapleStory-Client | 9,418 | Character/Inventory/Inventory.cpp | //////////////////////////////////////////////////////////////////////////////////
// This file is part of the continued Journey MMORPG client //
// Copyright (C) 2015-2019 Daniel Allendorf, Ryan Payton //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the GNU Affero General Public License as published by //
// the Free Software Foundation, either version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU Affero General Public License for more details. //
// //
// You should have received a copy of the GNU Affero General Public License //
// along with this program. If not, see <https://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////////
#include "Inventory.h"
#include "../../Data/BulletData.h"
#include "../../Data/EquipData.h"
#include <iostream>
namespace ms
{
Inventory::Inventory()
{
bulletslot = 0;
meso = 0;
running_uid = 0;
slotmaxima[InventoryType::Id::EQUIPPED] = EquipSlot::Id::LENGTH;
}
void Inventory::recalc_stats(Weapon::Type type)
{
totalstats.clear();
for (auto& iter : inventories[InventoryType::Id::EQUIPPED])
{
auto equip_iter = equips.find(iter.second.unique_id);
if (equip_iter != equips.end())
{
const Equip& equip = equip_iter->second;
for (auto stat_iter : totalstats)
stat_iter.second += equip.get_stat(stat_iter.first);
}
}
int32_t prefix;
switch (type)
{
case Weapon::Type::BOW:
prefix = 2060;
break;
case Weapon::Type::CROSSBOW:
prefix = 2061;
break;
case Weapon::Type::CLAW:
prefix = 2070;
break;
case Weapon::Type::GUN:
prefix = 2330;
break;
default:
prefix = 0;
break;
}
bulletslot = 0;
if (prefix)
{
for (auto& iter : inventories[InventoryType::Id::USE])
{
const Slot& slot = iter.second;
if (slot.count && slot.item_id / 1000 == prefix)
{
bulletslot = iter.first;
break;
}
}
}
if (int32_t bulletid = get_bulletid())
totalstats[EquipStat::Id::WATK] += BulletData::get(bulletid).get_watk();
}
void Inventory::set_meso(int64_t m)
{
meso = m;
}
void Inventory::set_slotmax(InventoryType::Id type, uint8_t slotmax)
{
slotmaxima[type] = slotmax;
}
void Inventory::add_item(InventoryType::Id invtype, int16_t slot, int32_t item_id, bool cash, int64_t expire, uint16_t count, const std::string& owner, int16_t flags)
{
items.emplace(
std::piecewise_construct,
std::forward_as_tuple(add_slot(invtype, slot, item_id, count, cash)),
std::forward_as_tuple(item_id, expire, owner, flags)
);
}
void Inventory::add_pet(InventoryType::Id invtype, int16_t slot, int32_t item_id, bool cash, int64_t expire, const std::string& name, int8_t level, int16_t closeness, int8_t fullness)
{
pets.emplace(
std::piecewise_construct,
std::forward_as_tuple(add_slot(invtype, slot, item_id, 1, cash)),
std::forward_as_tuple(item_id, expire, name, level, closeness, fullness)
);
}
void Inventory::add_equip(InventoryType::Id invtype, int16_t slot, int32_t item_id, bool cash, int64_t expire, uint8_t slots, uint8_t level, const EnumMap<EquipStat::Id, uint16_t>& stats, const std::string& owner, int16_t flag, uint8_t ilevel, uint16_t iexp, int32_t vicious)
{
equips.emplace(
std::piecewise_construct,
std::forward_as_tuple(add_slot(invtype, slot, item_id, 1, cash)),
std::forward_as_tuple(item_id, expire, owner, flag, slots, level, stats, ilevel, iexp, vicious)
);
}
void Inventory::remove(InventoryType::Id type, int16_t slot)
{
auto iter = inventories[type].find(slot);
if (iter == inventories[type].end())
return;
int32_t unique_id = iter->second.unique_id;
inventories[type].erase(iter);
switch (type)
{
case InventoryType::Id::EQUIPPED:
case InventoryType::Id::EQUIP:
equips.erase(unique_id);
break;
case InventoryType::Id::CASH:
items.erase(unique_id);
pets.erase(unique_id);
break;
default:
items.erase(unique_id);
break;
}
}
void Inventory::swap(InventoryType::Id firsttype, int16_t firstslot, InventoryType::Id secondtype, int16_t secondslot)
{
Slot first = std::move(inventories[firsttype][firstslot]);
inventories[firsttype][firstslot] = std::move(inventories[secondtype][secondslot]);
inventories[secondtype][secondslot] = std::move(first);
if (!inventories[firsttype][firstslot].item_id)
remove(firsttype, firstslot);
if (!inventories[secondtype][secondslot].item_id)
remove(secondtype, secondslot);
}
int32_t Inventory::add_slot(InventoryType::Id type, int16_t slot, int32_t item_id, int16_t count, bool cash)
{
running_uid++;
inventories[type][slot] = { running_uid, item_id, count, cash };
return running_uid;
}
void Inventory::change_count(InventoryType::Id type, int16_t slot, int16_t count)
{
auto iter = inventories[type].find(slot);
if (iter != inventories[type].end())
iter->second.count = count;
}
void Inventory::modify(InventoryType::Id type, int16_t slot, int8_t mode, int16_t arg, Movement move)
{
if (slot < 0)
{
slot = -slot;
type = InventoryType::Id::EQUIPPED;
}
arg = (arg < 0) ? -arg : arg;
switch (mode)
{
case Modification::CHANGECOUNT:
change_count(type, slot, arg);
break;
case Modification::SWAP:
switch (move)
{
case Movement::MOVE_INTERNAL:
swap(type, slot, type, arg);
break;
case Movement::MOVE_UNEQUIP:
swap(InventoryType::Id::EQUIPPED, slot, InventoryType::Id::EQUIP, arg);
break;
case Movement::MOVE_EQUIP:
swap(InventoryType::Id::EQUIP, slot, InventoryType::Id::EQUIPPED, arg);
break;
}
break;
case Modification::REMOVE:
remove(type, slot);
break;
}
}
uint8_t Inventory::get_slotmax(InventoryType::Id type) const
{
if (type == InventoryType::Id::DEC)
return slotmaxima[InventoryType::Id::CASH];
return slotmaxima[type];
}
uint16_t Inventory::get_stat(EquipStat::Id type) const
{
return totalstats[type];
}
int64_t Inventory::get_meso() const
{
return meso;
}
bool Inventory::has_projectile() const
{
return bulletslot > 0;
}
bool Inventory::has_equipped(EquipSlot::Id slot) const
{
return inventories[InventoryType::Id::EQUIPPED].count(slot) > 0;
}
int16_t Inventory::get_bulletslot() const
{
return bulletslot;
}
uint16_t Inventory::get_bulletcount() const
{
return get_item_count(InventoryType::Id::USE, bulletslot);
}
int32_t Inventory::get_bulletid() const
{
return get_item_id(InventoryType::Id::USE, bulletslot);
}
EquipSlot::Id Inventory::find_equipslot(int32_t itemid) const
{
const EquipData& cloth = EquipData::get(itemid);
if (!cloth.is_valid())
return EquipSlot::Id::NONE;
EquipSlot::Id eqslot = cloth.get_eqslot();
if (eqslot == EquipSlot::Id::RING1)
{
if (!has_equipped(EquipSlot::Id::RING2))
return EquipSlot::Id::RING2;
if (!has_equipped(EquipSlot::Id::RING3))
return EquipSlot::Id::RING3;
if (!has_equipped(EquipSlot::Id::RING4))
return EquipSlot::Id::RING4;
return EquipSlot::Id::RING1;
}
else
{
return eqslot;
}
}
int16_t Inventory::find_free_slot(InventoryType::Id type) const
{
int16_t counter = 1;
for (auto& iter : inventories[type])
{
if (iter.first != counter)
return counter;
counter++;
}
return counter <= slotmaxima[type] ? counter : 0;
}
int16_t Inventory::find_item(InventoryType::Id type, int32_t itemid) const
{
for (auto& iter : inventories[type])
if (iter.second.item_id == itemid)
return iter.first;
return 0;
}
int16_t Inventory::get_item_count(InventoryType::Id type, int16_t slot) const
{
auto iter = inventories[type].find(slot);
if (iter != inventories[type].end())
return iter->second.count;
else
return 0;
}
int16_t Inventory::get_total_item_count(int32_t itemid) const
{
InventoryType::Id type = InventoryType::by_item_id(itemid);
int16_t total_count = 0;
for (auto& iter : inventories[type])
if (iter.second.item_id == itemid)
total_count += iter.second.count;
return total_count;
}
int32_t Inventory::get_item_id(InventoryType::Id type, int16_t slot) const
{
auto iter = inventories[type].find(slot);
if (iter != inventories[type].end())
return iter->second.item_id;
else
return 0;
}
Optional<const Equip> Inventory::get_equip(InventoryType::Id type, int16_t slot) const
{
if (type != InventoryType::Id::EQUIPPED && type != InventoryType::Id::EQUIP)
return {};
auto slot_iter = inventories[type].find(slot);
if (slot_iter == inventories[type].end())
return {};
auto equip_iter = equips.find(slot_iter->second.unique_id);
if (equip_iter == equips.end())
return {};
return equip_iter->second;
}
Inventory::Movement Inventory::movementbyvalue(int8_t value)
{
if (value >= Inventory::Movement::MOVE_INTERNAL && value <= Inventory::Movement::MOVE_EQUIP)
return static_cast<Movement>(value);
LOG(LOG_DEBUG, "Unknown Inventory::Movement value: [" << value << "]");
return Inventory::Movement::MOVE_NONE;
}
} | 0 | 0.946123 | 1 | 0.946123 | game-dev | MEDIA | 0.939631 | game-dev | 0.963775 | 1 | 0.963775 |
DigiWorm0/LevelImposter | 1,153 | LevelImposter/Trigger/TriggerHandles/RandomTriggerHandle.cs | using LevelImposter.Core;
using UnityEngine;
namespace LevelImposter.Trigger;
public class RandomTriggerHandle : ITriggerHandle
{
private int _randomOffset;
public void OnTrigger(TriggerSignal signal)
{
if (signal.TriggerID != "random")
return;
// Get source element
var objectData = signal.TargetObject.GetLIData();
// Get a random value
// Seed is synced across all clients, so the same value is generated on all clients
var randVal = RandomizerSync.GetRandom(objectData.ID, _randomOffset++);
// Get the random chance (0 - 1)
var randomChance = 1.0f / (objectData.Properties.triggerCount ?? 2);
// Get the trigger index based on the random value (0 - triggerCount)
var triggerIndex = Mathf.FloorToInt(randVal / randomChance);
// Get the trigger ID
var targetID = "onRandom " + (triggerIndex + 1);
// Create & Fire Trigger
TriggerSignal newSignal = new(
signal.TargetObject,
targetID,
signal
);
TriggerSystem.GetInstance().FireTrigger(newSignal);
}
} | 0 | 0.756629 | 1 | 0.756629 | game-dev | MEDIA | 0.901765 | game-dev | 0.590022 | 1 | 0.590022 |
sciner/webcraft | 18,296 | www/src/pickat.ts | import { Vector } from "./helpers.js";
import {BLEND_MODES} from 'vauxcel';
import { TerrainGeometry15 } from "./geom/terrain_geometry_15.js";
import {Resources} from "./resources.js";
import {BLOCK} from "./blocks.js";
import {Raycaster, RaycasterResult} from "./Raycaster.js";
import { MOUSE } from "./constant.js";
import {LineGeometry} from "./geom/line_geometry.js";
import {AABB} from "./core/AABB.js";
import glMatrix from "@vendors/gl-matrix-3.3.min.js"
import type { Player } from "./player.js";
import type { World } from "./world.js";
import type { Renderer } from "./render.js";
import type { ChunkGrid } from "./core/ChunkGrid.js";
import type { ChunkManager } from "./chunk_manager.js";
import {TerrainBaseTexture} from "./renders/TerrainBaseTexture.js";
const {mat4} = glMatrix;
const half = new Vector(0.5, 0.5, 0.5);
export interface ICmdPickatData extends IPickatEvent {
actions ? : any // POJO of WorldAction
eye_pos ? : IVector
snapshotId ? : int // id of the blocks history snapshot on the client that should be restored if this action afails on server
changeExtraData ? : boolean
extra_data ? : any
/**
* Если это поле задано, то это id события, по которому синхронизируестя управление, см. {@link ClientPlayerControlManager.controlEventId}.
* Если это поле задано, то и клиент, и сервер _обязаны_ вызвать один из методов синхронизации с этим id.
* Но: вызывать нужно не сразу, а тогда, когда применяются изменения, связанные с этим событием (например, после
* обраотки созданного {@link WorldAction} который меняет положение игрока).
*/
controlEventId?: int
}
type PickAtOnTarget = (e: IPickatEvent, times: float, number: int) => Promise<boolean>
type PickAtOnInteractEntity = (IPickatEvent) => void
type PickAtOnInteractFluid = (IPickatEventPos) => boolean
export class PickAt {
raycaster: Raycaster
chunk_addr: Vector
_temp_pos : Vector = new Vector(0, 0, 0)
world: World
render: Renderer
chunk_manager: ChunkManager
grid: ChunkGrid
targetDescription: any = null
visibleBlockHUD: any = null
onTarget: PickAtOnTarget
onInteractEntity: PickAtOnInteractEntity
onInteractFluid: PickAtOnInteractFluid
modelMatrix: any
empty_matrix: any
material_target: any
chunk: any
material_damage: any
target_block: {
pos: IPickatEventPos | Vector
visible: boolean
geom: LineGeometry
}
damage_block: {
pos: IPickatEventPos | Vector
mesh: any
event?: IPickatEvent
frame: number
number: number
times: number // количество миллисекунд, в течение которого на блок было воздействие
prev_time: any // точное время, когда в последний раз было воздействие на блок
start: any
}
private nextId = 0 // id of the next pickAt event, and the associated WorldAction
constructor(world : World, render : Renderer, onTarget : PickAtOnTarget, onInteractEntity : PickAtOnInteractEntity, onInteractFluid : PickAtOnInteractFluid) {
this.world = world
this.render = render
this.chunk_manager = world.chunkManager
this.grid = world.chunkManager.grid
this.onTarget = onTarget // (block, target_event, elapsed_time) => {...};
this.onInteractEntity = onInteractEntity
this.onInteractFluid = onInteractFluid
//
this.target_block = {
pos: null,
visible: false,
geom: new LineGeometry()
}
//
this.damage_block = {
pos: null,
mesh: null,
event: null,
frame: 0,
number: 0,
times: 0, // количество миллисекунд, в течение которого на блок было воздействие
prev_time: null, // точное время, когда в последний раз было воздействие на блок
start: null
}
//
const modelMatrix = this.modelMatrix = mat4.create();
mat4.scale(modelMatrix, modelMatrix, [1.002, 1.002, 1.002]);
//
this.empty_matrix = mat4.create()
this.raycaster = new Raycaster(this.world)
this.target_block.geom.defColor = 0xFF000000
}
get(pos : IVector, callback : ((res: RaycasterResult | null) => void) | null = null,
pickat_distance : number, view_vector?: IVector, ignore_transparent? : boolean, return_fluid? : boolean
): RaycasterResult | null {
const render = this.render;
pos = this._temp_pos.copyFrom(pos);
// view_vector = null;
const myPlayerModel = this.world.players.getMyself()
if(view_vector) {
return this.raycaster.get(pos, view_vector, pickat_distance, callback, ignore_transparent, return_fluid, myPlayerModel);
}
const m = mat4.invert(this.empty_matrix, render.viewMatrix);
return this.raycaster.getFromView(pos, m, pickat_distance, callback, ignore_transparent, return_fluid, myPlayerModel);
}
// Used by other classes
getTargetBlock(player : Player) {
if (!player.game_mode.canBlockAction()) {
return null;
}
// Get actual pick-at block
const pos = this.get(player.getEyePos(), null, player.game_mode.getPickatDistance(), player.forward, true);
return pos ? this.world.getBlock(new Vector(pos as any)) : null;
}
/**
* Возвращает следующий по порядку id, который может быть использован:
* - для {@link IPickatEvent}
* - для других действий и команд, не связанных с pickat, но требующих синхронизации
* управления игрока с сервером, см. {@link ClientPlayerControlManager.syncWithEventId}
*/
getNextId(): int { return ++this.nextId }
// setEvent...
setEvent(player: Player, e_: {button_id: int, shiftKey: boolean}): void {
const e = e_ as IPickatEvent
e.id = this.getNextId()
e.start_time = performance.now();
e.destroyBlock = e.button_id == MOUSE.BUTTON_LEFT;
e.cloneBlock = e.button_id == MOUSE.BUTTON_WHEEL;
e.createBlock = e.button_id == MOUSE.BUTTON_RIGHT;
e.interactMobID = null;
e.interactPlayerID = null;
e.number = 0;
const damage_block = this.damage_block;
damage_block.event = Object.assign(e, {number: 0});
damage_block.start = performance.now();
this.updateDamageBlock();
// Picking target
/*if (player.pickAt && Qubatch.hud.active && player.game_mode.canBlockAction()) {
player.pickAt.update(player.pos, player.game_mode.getPickatDistance());
}*/
}
// setDamagePercent...
setDamagePercent(pos, percent) {
let damage_block = this.damage_block;
let new_frame = Math.round(percent * 9);
if(damage_block.frame != new_frame) {
damage_block.frame = new_frame;
if(damage_block.mesh) {
damage_block.mesh.destroy();
damage_block.mesh = this.createDamageBuffer(pos, BLOCK.calcTexture([14 + new_frame, 31]));
}
}
}
// updateDamageBlock...
updateDamageBlock() {
let target_block = this.target_block;
if(target_block.visible) {
let damage_block = this.damage_block;
if(damage_block.mesh) {
damage_block.mesh.destroy();
}
damage_block.pos = target_block.pos;
damage_block.number = 0;
damage_block.frame = 0;
damage_block.times = 0;
damage_block.prev_time = null;
damage_block.mesh = this.createDamageBuffer(damage_block.pos, BLOCK.calcTexture([damage_block.frame, 15]));
}
}
// update...
update(pos: IVector, pickat_distance: number, view_vector: IVector): void {
// Get actual pick-at block
let bPos = this.get(pos, null, pickat_distance, view_vector, false);
let target_block = this.target_block;
let damage_block = this.damage_block;
target_block.visible = !!bPos?.point && !bPos.mob && !bPos.player;
this.updateTargetDescription(target_block.visible ? bPos : null);
// Detect interact with fluid
if (bPos?.fluidLeftTop && !(bPos.player || bPos.mob) && this.onInteractFluid(bPos.fluidLeftTop)) {
return
}
if(bPos && bPos.point) {
if(bPos.player || bPos.mob) {
if(this.onInteractEntity instanceof Function) {
if(this.damage_block.event) {
this.damage_block.event.interactPlayerID = bPos?.player?.id;
this.damage_block.event.interactMobID = bPos?.mob?.id;
this.onInteractEntity(this.damage_block.event);
this.damage_block.event = null;
}
}
return;
}
damage_block.pos = bPos;
// Check if pick-at block changed, or HUD info visibility changed
let tbp = target_block.pos;
const newVisibleBlockHUD = Qubatch.hud.isDrawingBlockInfo();
if(!tbp || (tbp.x != bPos.x || tbp.y != bPos.y || tbp.z != bPos.z) ||
this.visibleBlockHUD !== newVisibleBlockHUD
) {
this.visibleBlockHUD = newVisibleBlockHUD;
// 1. Target block
target_block.pos = bPos;
this.createTargetLines(bPos, target_block.geom);
// 2. Damage block
if(damage_block.event) {
damage_block.pos = bPos;
this.updateDamageBlock();
}
}
} else {
damage_block.prev_time = null;
}
this.checkTargets();
}
// checkTargets...
async checkTargets() {
let target_block = this.target_block;
let damage_block = this.damage_block;
if(!target_block.visible) {
return false;
}
if(!damage_block.event) {
return false;
}
damage_block.number++;
damage_block.event.number++;
let pn = performance.now();
if(damage_block.prev_time) {
damage_block.times += pn - damage_block.prev_time;
}
damage_block.prev_time = pn;
if(this.onTarget instanceof Function) {
// полное копирование, во избежания модификации
let event = {...damage_block.event};
event.pos = {...damage_block.pos} as IPickatEventPos;
event.pos.n = (event.pos.n as Vector).clone();
event.pos.point = (event.pos.point as Vector).clone();
if(await this.onTarget(event, damage_block.times / 1000, damage_block.number)) {
this.updateDamageBlock();
if(damage_block.mesh) {
damage_block.mesh.destroy();
damage_block.mesh = null;
}
}
}
return false;
}
// Draw meshes
draw() {
if(!Qubatch.hud.active) {
return;
}
if(!this.material_target) {
this.initMaterials();
}
let render = this.render;
let target_block = this.target_block;
let damage_block = this.damage_block;
// 1. Target block
if(target_block.geom && target_block.visible) {
target_block.geom.draw(render.renderBackend);
}
// 2. Damage block
if(damage_block.mesh && damage_block.event && damage_block.event.destroyBlock && damage_block.frame > 0) {
const matrix = mat4.create();
let a_pos = half.add(this.damage_block.pos);
// Light
this.chunk_addr = this.grid.toChunkAddr(this.damage_block.pos);
this.chunk = this.chunk_manager.getChunk(this.chunk_addr);
if(this.chunk) {
mat4.translate(matrix, matrix,
[
(a_pos.x - this.chunk.coord.x),
(a_pos.y - this.chunk.coord.y),
(a_pos.z - this.chunk.coord.z),
]
);
a_pos = this.chunk.coord;
}
render.renderBackend.drawMesh(damage_block.mesh, this.material_damage, a_pos, matrix || this.modelMatrix);
}
}
createTargetLines(pos, geom) {
const lineWidth = 100 / Qubatch.render.HUD.height * 1.5 // .25
const aabbConfig = {isLocal: true, lineWidth, colorABGR: 0xFF000000};
// const aabbConfig = {isLocal: true, lineWidth: lineWidth * 10, colorABGR: 0xFFFF00FF};
let vertices = [];
geom.clear();
geom.pos.copyFrom(pos);
// let pp = 0;
// let flags = 0, sideFlags = 0, upFlags = 0;
let block = this.world.chunkManager.getBlock(pos.x, pos.y, pos.z);
let shapes = BLOCK.getShapes(block, this.world, false, false);
let aabb = new AABB();
for (let i = 0; i < shapes.length; i++) {
aabb.set(...shapes[i]);
geom.addAABB(aabb, aabbConfig);
}
return new TerrainGeometry15(vertices);
}
// createTargetBuffer...
createTargetBuffer(pos, c) {
let vertices = [];
let pp = 0;
let flags = 0, sideFlags = 0, upFlags = 0;
let block = this.world.chunkManager.getBlock(pos.x, pos.y, pos.z);
let shapes = BLOCK.getShapes(block, this.world, false, false);
for (let i = 0; i < shapes.length; i++) {
const shape = shapes[i];
let x1 = shape[0];
let x2 = shape[3];
let y1 = shape[1];
let y2 = shape[4];
let z1 = shape[2];
let z2 = shape[5];
let xw = x2 - x1; // ширина по оси X
let yw = y2 - y1; // ширина по оси Y
let zw = z2 - z1; // ширина по оси Z
let x = -.5 + x1 + xw/2;
let y_top = -.5 + y2;
let y_bottom = -.5 + y1;
let z = -.5 + z1 + zw/2;
// Up; X,Z,Y
vertices.push(x, z, y_top,
xw, 0, 0,
0, zw, 0,
c[0], c[1], c[2], c[3],
pp, flags | upFlags);
// Bottom
vertices.push(x, z, y_bottom,
xw, 0, 0,
0, -zw, 0,
c[0], c[1], c[2], c[3],
pp, flags);
// South | Forward | z++ (XZY)
vertices.push(x, z - zw/2, y_bottom + yw/2,
xw, 0, 0,
0, 0, yw,
c[0], c[1], c[2], -c[3],
pp, flags | sideFlags);
// North | Back | z--
vertices.push(x, z + zw/2, y_bottom + yw/2,
xw, 0, 0,
0, 0, -yw,
c[0], c[1], -c[2], c[3],
pp, flags | sideFlags);
// West | Left | x--
vertices.push(x - xw/2, z, y_bottom + yw/2,
0, zw, 0,
0, 0, -yw,
c[0], c[1], -c[2], c[3],
pp, flags | sideFlags);
// East | Right | x++
vertices.push(x + xw/2, z, y_bottom + yw/2,
0, zw, 0,
0, 0, yw,
c[0], c[1], -c[2], c[3],
pp, flags | sideFlags);
}
return new TerrainGeometry15(vertices);
}
// for HUD
updateTargetDescription(pos_: IVector | null) {
if (!Qubatch.hud.isDrawingBlockInfo() || !pos_) {
this.targetDescription =null;
return;
}
const pos = Vector.vectorify(pos_);
const block = this.world.chunkManager.getBlock(pos.x, pos.y, pos.z);
if (block.id === BLOCK.DUMMY.id || block.id === BLOCK.AIR.id) {
this.targetDescription = null;
return;
}
const lightValue = block.lightValue;
this.targetDescription = {
worldPos: pos,
posInChunk: pos.clone().subSelf(block.tb.dataChunk.pos),
chunkAddr: this.grid.toChunkAddr(pos),
block: block.clonePOJO(),
material: block.material,
fluid: (pos_ as any).fluidVal,
}
let normal = ((pos_ as any).n);
if (normal) {
const neibBlock = this.world.chunkManager.getBlock(pos.add(normal));
const lightValue = neibBlock.lightValue || 0;
this.targetDescription.caveLight = ((lightValue & 255) / 17);
this.targetDescription.dayLight = (15 - ((lightValue >> 8) & 255) / 17);
}
}
// createDamageBuffer...
createDamageBuffer(pos, c) {
return this.createTargetBuffer(pos, c);
}
// initMaterials
initMaterials() {
// Material (damage)
this.material_damage = this.render.renderBackend.createMaterial({
blendMode: BLEND_MODES.MULTIPLY,
shader: this.render.defaultShader,
group: {
cullFace: true,
opaque: false,
decalOffset: 6,
}
});
// Material (target)
this.material_target = this.material_damage.getSubMat(new TerrainBaseTexture({
source: Resources.pickat.target,
minFilter: 'nearest',
magFilter: 'nearest'
}));
}
// Сбросить текущий прогресс разрушения/установки
resetProgress() {
const damage_block = this.damage_block;
this.target_block.pos = new Vector(0, -Number.MAX_SAFE_INTEGER, 0);
if(damage_block) {
damage_block.times = 0;
damage_block.event = null;
if(damage_block.mesh) {
damage_block.mesh.destroy();
damage_block.mesh = null;
}
}
}
}
| 0 | 0.962179 | 1 | 0.962179 | game-dev | MEDIA | 0.875984 | game-dev | 0.861507 | 1 | 0.861507 |
The-Final-Nights/The-Final-Nights | 3,319 | code/modules/clothing/masks/_masks.dm | /obj/item/clothing/mask
name = "mask"
icon = 'icons/obj/clothing/masks.dmi'
body_parts_covered = HEAD
slot_flags = ITEM_SLOT_MASK
strip_delay = 40
equip_delay_other = 40
var/modifies_speech = FALSE
var/mask_adjusted = FALSE
var/adjusted_flags = null
var/conceals_voice = TRUE
/obj/item/clothing/mask/attack_self(mob/user)
if((clothing_flags & VOICEBOX_TOGGLABLE))
clothing_flags ^= (VOICEBOX_DISABLED)
var/status = !(clothing_flags & VOICEBOX_DISABLED)
to_chat(user, "<span class='notice'>You turn the voice box in [src] [status ? "on" : "off"].</span>")
/obj/item/clothing/mask/equipped(mob/M, slot)
. = ..()
if (slot == ITEM_SLOT_MASK && modifies_speech)
RegisterSignal(M, COMSIG_MOB_SAY, PROC_REF(handle_speech))
else
UnregisterSignal(M, COMSIG_MOB_SAY)
/obj/item/clothing/mask/dropped(mob/M)
. = ..()
UnregisterSignal(M, COMSIG_MOB_SAY)
/obj/item/clothing/mask/vv_edit_var(vname, vval)
if(vname == NAMEOF(src, modifies_speech) && ismob(loc))
var/mob/M = loc
if(M.get_item_by_slot(ITEM_SLOT_MASK) == src)
if(vval)
if(!modifies_speech)
RegisterSignal(M, COMSIG_MOB_SAY, PROC_REF(handle_speech))
else if(modifies_speech)
UnregisterSignal(M, COMSIG_MOB_SAY)
return ..()
/obj/item/clothing/mask/proc/handle_speech()
SIGNAL_HANDLER
/obj/item/clothing/mask/worn_overlays(isinhands = FALSE)
. = list()
if(!isinhands)
if(body_parts_covered & HEAD)
if(damaged_clothes)
. += mutable_appearance('icons/effects/item_damage.dmi', "damagedmask")
if(HAS_BLOOD_DNA(src))
. += mutable_appearance('icons/effects/blood.dmi', "maskblood")
/obj/item/clothing/mask/update_clothes_damaged_state(damaged_state = CLOTHING_DAMAGED)
..()
if(ismob(loc))
var/mob/M = loc
M.update_inv_wear_mask()
//Proc that moves gas/breath masks out of the way, disabling them and allowing pill/food consumption
/obj/item/clothing/mask/proc/adjustmask(mob/living/user)
if(user?.incapacitated())
return
mask_adjusted = !mask_adjusted
if(!mask_adjusted)
src.icon_state = initial(icon_state)
gas_transfer_coefficient = initial(gas_transfer_coefficient)
permeability_coefficient = initial(permeability_coefficient)
clothing_flags |= visor_flags
flags_inv |= visor_flags_inv
flags_cover |= visor_flags_cover
to_chat(user, "<span class='notice'>You push \the [src] back into place.</span>")
slot_flags = initial(slot_flags)
else
icon_state += "_up"
to_chat(user, "<span class='notice'>You push \the [src] out of the way.</span>")
gas_transfer_coefficient = null
permeability_coefficient = null
clothing_flags &= ~visor_flags
flags_inv &= ~visor_flags_inv
flags_cover &= ~visor_flags_cover
if(adjusted_flags)
slot_flags = adjusted_flags
if(user)
user.wear_mask_update(src, toggle_off = mask_adjusted)
user.update_action_buttons_icon() //when mask is adjusted out, we update all buttons icon so the user's potential internal tank correctly shows as off.
//Toggles voice hiding.
/obj/item/clothing/mask/CtrlClick(mob/user)
. = ..()
conceals_voice = !conceals_voice
to_chat(user, span_notice("You are [conceals_voice ? "now" : "no longer"] concealing your voice!"))
/obj/item/clothing/mask/examine(mob/user)
. = ..()
if(conceals_voice && (flags_inv & HIDEFACE))
. += span_notice("Ctrl-click the mask to toggle voice concealment.")
| 0 | 0.956018 | 1 | 0.956018 | game-dev | MEDIA | 0.924541 | game-dev | 0.936308 | 1 | 0.936308 |
Kirby64Ret/kirby64 | 5,325 | asm/non_matchings/ovl1/ovl1_2/func_800A78D0.s | glabel func_800A78D0
/* 04FB20 800A78D0 27BDFFC8 */ addiu $sp, $sp, -0x38
/* 04FB24 800A78D4 AFBF0024 */ sw $ra, 0x24($sp)
/* 04FB28 800A78D8 AFA40038 */ sw $a0, 0x38($sp)
/* 04FB2C 800A78DC AFB00020 */ sw $s0, 0x20($sp)
/* 04FB30 800A78E0 0C026E67 */ jal func_8009B99C
/* 04FB34 800A78E4 24040100 */ li $a0, 256
/* 04FB38 800A78E8 3C01800D */ lui $at, %hi(D_800D6FB4) # $at, 0x800d
/* 04FB3C 800A78EC AC226FB4 */ sw $v0, %lo(D_800D6FB4)($at)
/* 04FB40 800A78F0 0C02812E */ jal func_800A04B8
/* 04FB44 800A78F4 24040040 */ li $a0, 64
/* 04FB48 800A78F8 3C10800D */ lui $s0, %hi(D_800D6FB8) # $s0, 0x800d
/* 04FB4C 800A78FC 26106FB8 */ addiu $s0, %lo(D_800D6FB8) # addiu $s0, $s0, 0x6fb8
/* 04FB50 800A7900 AE020000 */ sw $v0, ($s0)
/* 04FB54 800A7904 3C04800D */ lui $a0, %hi(D_800D6FB4) # $a0, 0x800d
/* 04FB58 800A7908 0C0028A7 */ jal func_8000A29C_ovl1
/* 04FB5C 800A790C 8C846FB4 */ lw $a0, %lo(D_800D6FB4)($a0)
/* 04FB60 800A7910 0C0028A7 */ jal func_8000A29C_ovl1
/* 04FB64 800A7914 8E040000 */ lw $a0, ($s0)
/* 04FB68 800A7918 2404FFF9 */ li $a0, -7
/* 04FB6C 800A791C 00002825 */ move $a1, $zero
/* 04FB70 800A7920 24060018 */ li $a2, 24
/* 04FB74 800A7924 0C002860 */ jal func_8000A180
/* 04FB78 800A7928 00003825 */ move $a3, $zero
/* 04FB7C 800A792C 3C05800A */ lui $a1, %hi(D_8009E834) # $a1, 0x800a
/* 04FB80 800A7930 AE020000 */ sw $v0, ($s0)
/* 04FB84 800A7934 3C01800D */ lui $at, %hi(D_800D6FB4) # $at, 0x800d
/* 04FB88 800A7938 24A5E834 */ addiu $a1, %lo(D_8009E834) # addiu $a1, $a1, -0x17cc
/* 04FB8C 800A793C AC226FB4 */ sw $v0, %lo(D_800D6FB4)($at)
/* 04FB90 800A7940 00402025 */ move $a0, $v0
/* 04FB94 800A7944 AFA5002C */ sw $a1, 0x2c($sp)
/* 04FB98 800A7948 24060001 */ li $a2, 1
/* 04FB9C 800A794C 0C002286 */ jal func_80008A18
/* 04FBA0 800A7950 00003825 */ move $a3, $zero
/* 04FBA4 800A7954 3C05800A */ lui $a1, %hi(D_800A09AC) # $a1, 0x800a
/* 04FBA8 800A7958 24A509AC */ addiu $a1, %lo(D_800A09AC) # addiu $a1, $a1, 0x9ac
/* 04FBAC 800A795C AFA50028 */ sw $a1, 0x28($sp)
/* 04FBB0 800A7960 8E040000 */ lw $a0, ($s0)
/* 04FBB4 800A7964 24060001 */ li $a2, 1
/* 04FBB8 800A7968 0C002286 */ jal func_80008A18
/* 04FBBC 800A796C 00003825 */ move $a3, $zero
/* 04FBC0 800A7970 8E040000 */ lw $a0, ($s0)
/* 04FBC4 800A7974 8FA5002C */ lw $a1, 0x2c($sp)
/* 04FBC8 800A7978 24060001 */ li $a2, 1
/* 04FBCC 800A797C 0C002286 */ jal func_80008A18
/* 04FBD0 800A7980 00003825 */ move $a3, $zero
/* 04FBD4 800A7984 8E040000 */ lw $a0, ($s0)
/* 04FBD8 800A7988 8FA50028 */ lw $a1, 0x28($sp)
/* 04FBDC 800A798C 24060001 */ li $a2, 1
/* 04FBE0 800A7990 0C002286 */ jal func_80008A18
/* 04FBE4 800A7994 00003825 */ move $a3, $zero
/* 04FBE8 800A7998 00002025 */ move $a0, $zero
/* 04FBEC 800A799C 00002825 */ move $a1, $zero
/* 04FBF0 800A79A0 24060018 */ li $a2, 24
/* 04FBF4 800A79A4 0C002860 */ jal func_8000A180
/* 04FBF8 800A79A8 3C078000 */ lui $a3, 0x8000
/* 04FBFC 800A79AC 3C05800A */ lui $a1, %hi(D_800A7ABC) # $a1, 0x800a
/* 04FC00 800A79B0 240EFFFF */ li $t6, -1
/* 04FC04 800A79B4 00408025 */ move $s0, $v0
/* 04FC08 800A79B8 AFAE0010 */ sw $t6, 0x10($sp)
/* 04FC0C 800A79BC 24A57ABC */ addiu $a1, %lo(D_800A7ABC) # addiu $a1, $a1, 0x7abc
/* 04FC10 800A79C0 00402025 */ move $a0, $v0
/* 04FC14 800A79C4 24060010 */ li $a2, 16
/* 04FC18 800A79C8 0C00297F */ jal func_8000A5FC
/* 04FC1C 800A79CC 2407000C */ li $a3, 12
/* 04FC20 800A79D0 240F000F */ li $t7, 15
/* 04FC24 800A79D4 AE0F0030 */ sw $t7, 0x30($s0)
/* 04FC28 800A79D8 24040010 */ li $a0, 16
/* 04FC2C 800A79DC 0C026D54 */ jal func_8009B550
/* 04FC30 800A79E0 240500BC */ li $a1, 188
/* 04FC34 800A79E4 3C03800D */ lui $v1, %hi(D_800D6AB8) # $v1, 0x800d
/* 04FC38 800A79E8 3C02800D */ lui $v0, %hi(D_800D6AD8) # $v0, 0x800d
/* 04FC3C 800A79EC 24426AD8 */ addiu $v0, %lo(D_800D6AD8) # addiu $v0, $v0, 0x6ad8
/* 04FC40 800A79F0 24636AB8 */ addiu $v1, %lo(D_800D6AB8) # addiu $v1, $v1, 0x6ab8
.L800A79F4_ovl1:
/* 04FC44 800A79F4 24630004 */ addiu $v1, $v1, 4
/* 04FC48 800A79F8 0062082B */ sltu $at, $v1, $v0
/* 04FC4C 800A79FC 1420FFFD */ bnez $at, .L800A79F4_ovl1
/* 04FC50 800A7A00 AC60FFFC */ sw $zero, -4($v1)
/* 04FC54 800A7A04 3C02800D */ lui $v0, %hi(D_800D6A38) # $v0, 0x800d
/* 04FC58 800A7A08 3C03800D */ lui $v1, %hi(D_800D6A58) # $v1, 0x800d
/* 04FC5C 800A7A0C 24636A58 */ addiu $v1, %lo(D_800D6A58) # addiu $v1, $v1, 0x6a58
/* 04FC60 800A7A10 24426A38 */ addiu $v0, %lo(D_800D6A38) # addiu $v0, $v0, 0x6a38
.L800A7A14_ovl1:
/* 04FC64 800A7A14 24420010 */ addiu $v0, $v0, 0x10
/* 04FC68 800A7A18 AC40FFF4 */ sw $zero, -0xc($v0)
/* 04FC6C 800A7A1C AC40FFF8 */ sw $zero, -8($v0)
/* 04FC70 800A7A20 AC40FFFC */ sw $zero, -4($v0)
/* 04FC74 800A7A24 1443FFFB */ bne $v0, $v1, .L800A7A14_ovl1
/* 04FC78 800A7A28 AC40FFF0 */ sw $zero, -0x10($v0)
/* 04FC7C 800A7A2C 8FBF0024 */ lw $ra, 0x24($sp)
/* 04FC80 800A7A30 8FB00020 */ lw $s0, 0x20($sp)
/* 04FC84 800A7A34 27BD0038 */ addiu $sp, $sp, 0x38
/* 04FC88 800A7A38 03E00008 */ jr $ra
/* 04FC8C 800A7A3C 00000000 */ nop
.type func_800A78D0, @function
.size func_800A78D0, . - func_800A78D0
| 0 | 0.68832 | 1 | 0.68832 | game-dev | MEDIA | 0.859035 | game-dev | 0.545543 | 1 | 0.545543 |
GJKen/L4d2_plugins | 19,007 | 可选-特殊击杀提示(Tabun)/left4dead2/addons/sourcemod/scripting/l4d2_stats.sp | #pragma semicolon 1
#pragma newdecls required
#include <sourcemod>
#define L4D2UTIL_STOCKS_ONLY 1
#include <l4d2util>
#include <colors>
#define TEAM_SPECTATOR 1
#define TEAM_SURVIVOR 2
#define TEAM_INFECTED 3
#define BOOMER_STAGGER_TIME 4.0 // Amount of time after a boomer has been meleed that we consider the meleer the person who
// shut down the boomer, this is just a guess value..
// Player temp stats
int
g_iDamageDealt[MAXPLAYERS + 1][MAXPLAYERS + 1], // Victim - Attacker
g_iShotsDealt[MAXPLAYERS + 1][MAXPLAYERS + 1]; // Victim - Attacker, count # of shots (not pellets)
//
int
g_iBoomerClient = 0, // Last player to be boomer (or current boomer)
g_iBoomerKiller = 0, // Client who shot the boomer
g_iBoomerShover = 0, // Client who shoved the boomer
g_iLastHealth[MAXPLAYERS + 1] = {0, ...};
float
BoomerKillTime = 0.0;
bool
g_bHasRoundEnded = false,
g_bHasBoomLanded = false,
g_bIsPouncing[MAXPLAYERS + 1] = {false, ...},
g_bShotCounted[MAXPLAYERS + 1][MAXPLAYERS + 1]; // Victim - Attacker, used by playerhurt and weaponfired
Handle
g_hBoomerShoveTimer = null,
g_hBoomerKillTimer = null;
char
Boomer[32]; // Name of Boomer
public Plugin myinfo =
{
name = "L4D2 Realtime Stats",
author = "Griffin, Philogl, Sir, A1m`",
description = "Display Skeets/Etc to Chat to clients",
version = "1.2.2",
url = "https://github.com/SirPlease/L4D2-Competitive-Rework"
}
public void OnPluginStart()
{
HookEvent("round_start", Event_RoundStart);
HookEvent("round_end", Event_RoundEnd);
HookEvent("player_hurt", Event_PlayerHurt);
HookEvent("player_death", Event_PlayerDeath);
HookEvent("player_spawn", Event_PlayerSpawn);
HookEvent("ability_use", Event_AbilityUse);
HookEvent("lunge_pounce", Event_LungePounce);
HookEvent("weapon_fire", Event_WeaponFire);
HookEvent("player_shoved", Event_PlayerShoved);
HookEvent("player_now_it", Event_PlayerBoomed);
HookEvent("triggered_car_alarm", Event_AlarmCar);
}
public void Event_PlayerSpawn(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
int client = GetClientOfUserId(hEvent.GetInt("userid"));
if (client == 0 || !IsClientInGame(client)) {
return;
}
if (GetClientTeam(client) == TEAM_INFECTED) {
int zombieclass = GetInfectedClass(client);
if (zombieclass == L4D2Infected_Tank) {
return;
}
if (zombieclass == L4D2Infected_Boomer) {
// Fresh boomer spawning (if g_iBoomerClient is set and an AI boomer spawns, it's a boomer going AI)
if (!IsFakeClient(client) || !g_iBoomerClient) {
g_bHasBoomLanded = false;
g_iBoomerClient = client;
g_iBoomerShover = 0;
g_iBoomerKiller = 0;
}
DestroyTimer(g_hBoomerShoveTimer);
BoomerKillTime = 0.0;
g_hBoomerKillTimer = CreateTimer(0.1, Timer_KillBoomer, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE);
}
g_iLastHealth[client] = GetClientHealth(client);
}
}
public void Event_WeaponFire(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
int client = GetClientOfUserId(hEvent.GetInt("userid"));
for (int i = 1; i <= MaxClients; i++) {
// [Victim][Attacker]
g_bShotCounted[i][client] = false;
}
}
public void OnMapStart()
{
g_bHasRoundEnded = false;
ClearMapStats();
}
public void OnMapEnd()
{
/*
* Sometimes the event 'round_start' is called before OnMapStart()
* and the timer handle is not reset, so it's better to do it here.
*/
g_hBoomerShoveTimer = null; // TIMER_FLAG_NO_MAPCHANGE
g_hBoomerKillTimer = null; // TIMER_FLAG_NO_MAPCHANGE
g_bHasRoundEnded = true;
}
public void Event_RoundStart(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
g_bHasRoundEnded = false;
DestroyTimer(g_hBoomerKillTimer);
BoomerKillTime = 0.0;
}
public void Event_RoundEnd(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasRoundEnded) {
return;
}
g_bHasRoundEnded = true;
for (int i = 1; i <= MaxClients; i++) {
ClearDamage(i);
}
}
// Pounce tracking, from skeet announce
public void Event_AbilityUse(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasRoundEnded) {
return;
}
int userid = hEvent.GetInt("userid");
int client = GetClientOfUserId(userid);
if (!IsClientInGame(client) || GetClientTeam(client) != TEAM_INFECTED) {
return;
}
int zombieclass = GetInfectedClass(client);
if (zombieclass == L4D2Infected_Hunter) {
g_bIsPouncing[client] = true;
CreateTimer(0.5, Timer_GroundedCheck, userid, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE);
}
}
public void Event_LungePounce(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
int attacker = GetClientOfUserId(hEvent.GetInt("userid"));
int zombieclass = GetInfectedClass(attacker);
if (zombieclass == L4D2Infected_Hunter) {
g_bIsPouncing[attacker] = false;
}
}
public Action Timer_GroundedCheck(Handle hTimer, any userid)
{
int client = GetClientOfUserId(userid);
if (client > 0 && !(GetEntityFlags(client) & FL_ONGROUND)) {
return Plugin_Continue;
}
g_bIsPouncing[client] = false;
return Plugin_Stop;
}
public Action Timer_KillBoomer(Handle hTimer)
{
BoomerKillTime += 0.1;
return Plugin_Continue;
}
public void Event_PlayerHurt(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasRoundEnded) {
return;
}
int victim = GetClientOfUserId(hEvent.GetInt("userid"));
if (victim == 0 || !IsClientInGame(victim)) {
return;
}
int attacker = GetClientOfUserId(hEvent.GetInt("attacker"));
if (!attacker || !IsClientInGame(attacker)) {
return;
}
if (GetClientTeam(attacker) == TEAM_SURVIVOR && GetClientTeam(victim) == TEAM_INFECTED) {
int zombieclass = GetInfectedClass(victim);
if (zombieclass == L4D2Infected_Tank) {
return; // We don't care about tank damage
}
if (!g_bShotCounted[victim][attacker]) {
g_iShotsDealt[victim][attacker]++;
g_bShotCounted[victim][attacker] = true;
}
int remaining_health = hEvent.GetInt("health");
// Let player_death handle remainder damage (avoid overkill damage)
if (remaining_health <= 0) {
return;
}
// remainder health will be awarded as damage on kill
g_iLastHealth[victim] = remaining_health;
int damage = hEvent.GetInt("dmg_health");
g_iDamageDealt[victim][attacker] += damage;
/*switch(zombieclass) {
case L4D2Infected_Boomer: {
// Boomer Code Here
}
case L4D2Infected_Hunter: {
// Hunter Code Here
}
case L4D2Infected_Smoker: {
// Smoker Code Here
}
case L4D2Infected_Jockey: {
// Jockey Code Here
}
case L4D2Infected_Charger: {
// Charger Code Here
}
case L4D2Infected_Spitter: {
// Spitter Code Here
}
}*/
}
}
public void Event_PlayerDeath(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasRoundEnded) {
return;
}
int victim = GetClientOfUserId(hEvent.GetInt("userid"));
int attacker = GetClientOfUserId(hEvent.GetInt("attacker"));
if (victim == 0 || !IsClientInGame(victim) || attacker == 0) {
return;
}
if (!IsClientInGame(attacker)) {
if (GetClientTeam(victim) == TEAM_INFECTED) {
ClearDamage(victim);
}
return;
}
if (GetClientTeam(attacker) == TEAM_SURVIVOR && GetClientTeam(victim) == TEAM_INFECTED) {
int zombieclass = GetInfectedClass(victim);
if (zombieclass == L4D2Infected_Tank) {
return; // We don't care about tank damage
}
int lasthealth = g_iLastHealth[victim];
g_iDamageDealt[victim][attacker] += lasthealth;
if (zombieclass == L4D2Infected_Boomer) {
// Only happens on mid map plugin load when a boomer is up
if (!g_iBoomerClient) {
g_iBoomerClient = victim;
}
//// Oringial code ////
/*if (!IsFakeClient(g_iBoomerClient)) {
GetClientName(g_iBoomerClient, Boomer, sizeof(Boomer));
} else {
Boomer = "AI";
}*/
//// Code from decompiler ////
if (IsClientConnected(g_iBoomerClient)) {
if (!IsFakeClient(g_iBoomerClient)) {
GetClientName(g_iBoomerClient, Boomer, sizeof(Boomer));
} else {
Format(Boomer, sizeof(Boomer), "AI");
}
} else {
if (!IsFakeClient(victim)) {
GetClientName(victim, Boomer, sizeof(Boomer));
} else {
Format(Boomer, sizeof(Boomer), "AI");
}
}
////////
CreateTimer(0.2, Timer_BoomerKilledCheck, victim, TIMER_FLAG_NO_MAPCHANGE);
g_iBoomerKiller = attacker;
DestroyTimer(g_hBoomerKillTimer);
} else if (zombieclass == L4D2Infected_Hunter && g_bIsPouncing[victim]) { // Skeet!
int[][] assisters = new int[MaxClients][2];
int assister_count, i;
int damage = g_iDamageDealt[victim][attacker];
int shots = g_iShotsDealt[victim][attacker];
//char plural = (shots == 1) ? 0 : 's';
for (i = 1; i <= MaxClients; i++) {
if (i == attacker) {
continue;
}
if (g_iDamageDealt[victim][i] > 0 && IsClientInGame(i)) {
assisters[assister_count][0] = i;
assisters[assister_count][1] = g_iDamageDealt[victim][i];
assister_count++;
}
}
// Used GetClientWeapon because Melee Damage is known to be broken
// Use l4d2_melee_fix.smx in order to make this work properly. :)
// Rlly?!
char weapon[64];
GetClientWeapon(attacker, weapon, sizeof(weapon));
if (strcmp(weapon, "weapon_melee") == 0) {
/*CPrintToChat(victim, "{green}★ {default}You were {blue}melee skeeted {default}by {olive}%N", attacker);
CPrintToChat(attacker, "{green}★ {default}You {blue}melee{default}-{blue}skeeted {olive}%N", victim);
for (int b = 1; b <= MaxClients; b++) {
//Print to Specs!
if (IsClientInGame(b) && (victim != b) && (attacker != b)) {
CPrintToChat(b, "{green}★ {olive}%N {default}was {blue}melee{default}-{blue}skeeted {default}by {olive}%N", victim, attacker)
}
}*/
CPrintToChatAll("{green}★ {blue}%N {default}被 {blue}%N {default}用{blue}近战空爆", victim, attacker);
} else if (hEvent.GetBool("headshot") && strcmp(weapon, "weapon_sniper_scout") == 0) { // Scout Headshot
/*CPrintToChat(victim, "{green}★ {default}You were {blue}Headshotted {default}by {blue}Scout-Player{default}: {olive}%N", attacker);
CPrintToChat(attacker, "{green}★ {default}You {blue}Headshotted {olive}%N {default}with the {blue}Scout", victim);
for (int b = 1; b <= MaxClients; b++) {
//Print to Specs!
if (IsClientInGame(b) && (victim != b) && (attacker != b)) {
CPrintToChat(b, "{green}★ {olive}%N {default}was {blue}Headshotted {default}by {blue}Scout-Player{default}: {olive}%N", \
victim, attacker);
}
}*/
CPrintToChatAll("{green}★ {blue}%N {default}被 {blue}%N {blue}爆头", victim, attacker);
} else if (assister_count) {
// Sort by damage, descending
SortCustom2D(assisters, assister_count, ClientValue2DSortDesc);
char assister_string[128];
char buf[MAX_NAME_LENGTH + 8];
int assist_shots = g_iShotsDealt[victim][assisters[0][0]];
// Construct assisters string
Format(assister_string, sizeof(assister_string), "%N (%d/%d 枪)", \
assisters[0][0], assisters[0][1], g_iShotsDealt[victim][assisters[0][0]]);
for (i = 1; i < assister_count; i++) {
assist_shots = g_iShotsDealt[victim][assisters[i][0]];
Format(buf, sizeof(buf), ", %N (%d/%d 枪)", assisters[i][0], assisters[i][1], assist_shots);
StrCat(assister_string, sizeof(assister_string), buf);
}
/*
// Print to assisters
for (i = 0; i < assister_count; i++) {
CPrintToChat(assisters[i][0], "{green}★ {olive}%N {default}teamskeeted {olive}%N {default}for {blue}%d damage {default}in {blue}%d shot%c{default}. Assisted by: {olive}%s", \
attacker, victim, damage, shots, plural, assister_string);
}
// Print to victim
CPrintToChat(victim, "{green}★ {default}You were teamskeeted by {olive}%N {default}for {blue}%d damage {default}in {blue}%d shot%c{default}. Assisted by: {olive}%s", \
attacker, damage, shots, plural, assister_string);
// Finally print to attacker
CPrintToChat(attacker, "{green}★ {default}You teamskeeted {olive}%N {default}for {blue}%d damage {default}in {blue}%d shot%c{default}. Assisted by: {olive}%s", \
victim, damage, shots, plural, assister_string);
//Print to Specs!
for (int b = 1; b <= MaxClients; b++) {
if (IsClientInGame(b) && GetClientTeam(b) == TEAM_SPECTATOR) {
CPrintToChat(b, "{green}★ {olive}%N {default}teamskeeted {olive}%N {default}for {blue}%d damage {default}in {blue}%d shot%c{default}. Assisted by: {olive}%s", \
attacker, victim, damage, shots, plural, assister_string);
}
}*/
CPrintToChatAll("{green}★ {blue}%N {default} 和团队空爆了 {blue}%N {default}({blue}%d {default}枪 {blue}%d {default}伤害 ). 助攻: {olive}%s", \
attacker, victim, shots, damage, assister_string);
} else {
/*CPrintToChat(victim, "{green}★ {default}You were skeeted by {olive}%N {default}in {blue}%d shot%c", attacker, shots, plural);
CPrintToChat(attacker, "{green}★ {default}You skeeted {olive}%N {default}in {blue}%d shot%c", victim, shots, plural);
for (int b = 1; b <= MaxClients; b++) {
//Print to Everyone Else!
if (IsClientInGame(b) && (victim != b) && attacker != b) {
CPrintToChat(b, "{green}★ {olive}%N {default}skeeted {olive}%N {default}in {blue}%d shot%c", attacker, victim, shots, plural);
}
}*/
CPrintToChatAll("{green}★ {blue}%N {olive}%d枪 {default}空爆了 {blue}%N", \
attacker, shots, victim);
}
}
}
if (GetClientTeam(victim) == TEAM_INFECTED) {
ClearDamage(victim);
}
}
public Action Timer_BoomerKilledCheck(Handle hTimer)
{
BoomerKillTime = BoomerKillTime - 0.2;
if (g_bHasBoomLanded || BoomerKillTime > 2.0) {
g_iBoomerClient = 0;
BoomerKillTime = 0.0;
return Plugin_Stop;
}
//Oringial Code
/*if (IsClientInGame(g_iBoomerKiller)) {
if (IsClientInGame(g_iBoomerClient)) {
//Boomer was Shoved before he was Killed!
if (g_iBoomerShover != 0 && IsClientInGame(g_iBoomerShover)) {
// Shover is Killer
if (g_iBoomerShover == g_iBoomerKiller) {
//CPrintToChatAll("{green}★ {olive}%N {default}shoved and popped {olive}%s{default}'s Boomer in {blue}%0.1fs", g_iBoomerKiller, Boomer, BoomerKillTime);
} else { // Someone Shoved and Someone Killed
//CPrintToChatAll("{green}★ {olive}%N {default}shoved and {olive}%N {default}popped {olive}%s{default}'s Boomer in {blue}%0.1fs", g_iBoomerShover, g_iBoomerKiller, Boomer, BoomerKillTime);
}
} else { //Boomer got Popped without Shove
//CPrintToChatAll("{green}★ {olive}%N {default}has shutdown {olive}%s{default}'s Boomer in {blue}%0.1fs", g_iBoomerKiller, Boomer, BoomerKillTime);
}
}
}*/
// Code from decompiler and modified code:)
if (BoomerKillTime < 0.1) {
BoomerKillTime = 0.1;
}
if (IsValidClient(g_iBoomerKiller)) {
if (IsValidClient(g_iBoomerClient)) {
char sRank[16];
if (BoomerKillTime <= 0.5) {
Format(sRank, sizeof(sRank), "★★★");
} else if (BoomerKillTime > 0.5 && BoomerKillTime <= 1.4) {
Format(sRank, sizeof(sRank), "★★");
} else {
Format(sRank, sizeof(sRank), "★");
}
CPrintToChatAll("{green}%s {blue}%N {default}瞬杀了在 {blue}%0.1f {default}秒前生成的{blue}Boomer[%s]", sRank, g_iBoomerKiller, BoomerKillTime, Boomer);
}
}
////
g_iBoomerClient = 0;
BoomerKillTime = 0.0;
return Plugin_Stop;
}
public void Event_PlayerShoved(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasRoundEnded) {
return;
}
int victim = GetClientOfUserId(hEvent.GetInt("userid"));
if (victim == 0 || !IsClientInGame(victim) || GetClientTeam(victim) != TEAM_INFECTED) {
return;
}
int attacker = GetClientOfUserId(hEvent.GetInt("attacker"));
if (attacker == 0 || !IsClientInGame(attacker) || GetClientTeam(attacker) != TEAM_SURVIVOR) {
return;
}
int zombieclass = GetInfectedClass(victim);
if (zombieclass == L4D2Infected_Boomer) {
if (g_hBoomerShoveTimer != null) {
DestroyTimer(g_hBoomerShoveTimer);
if (!g_iBoomerShover || !IsClientInGame(g_iBoomerShover)) {
g_iBoomerShover = attacker;
}
} else {
g_iBoomerShover = attacker;
}
g_hBoomerShoveTimer = CreateTimer(BOOMER_STAGGER_TIME, Timer_BoomerShove, _, TIMER_FLAG_NO_MAPCHANGE);
}
}
public Action Timer_BoomerShove(Handle hTimer)
{
// PrintToChatAll("[DEBUG] BoomerShove timer expired, credit for boomer shutdown is available to anyone at this point!");
g_hBoomerShoveTimer = null;
g_iBoomerShover = 0;
return Plugin_Stop;
}
public void Event_PlayerBoomed(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bHasBoomLanded) {
return;
}
g_bHasBoomLanded = true;
// Doesn't matter if we log stats to an out of play client, won't affect anything
/*if (!IsClientInGame(g_iBoomerClient) || IsFakeClient(g_iBoomerClient)) {
return;
}*/
// We credit the person who spawned the boomer with booms even if it went AI
//if (hEvent.GetBool("exploded")) {
// Proxy Boom!
//if (g_iBoomerShover != 0) {
/*if (g_iBoomerKiller == g_iBoomerShover) {
int iTeam = 0;
for (int i = 1; i <= MaxClients; i++) {
if (IsClientInGame(i)) {
iTeam = GetClientTeam(i);
if (iTeam == TEAM_SURVIVOR || iTeam == TEAM_SURVIVOR) {
CPrintToChat(i, "{green}★ {olive}%N {default}shoved {olive}%s{default}'s Boomer, but popped it too early", g_iBoomerShover, Boomer);
}
}
}
} else {
int iTeam = 0;
for (int i = 1; i <= MaxClients; i++) {
if (IsClientInGame(i)) {
iTeam = GetClientTeam(i);
if (iTeam == TEAM_SURVIVOR || iTeam == TEAM_SURVIVOR) {
CPrintToChat(i, "{green}★ {olive}%N {default}shoved {olive}%s{default}'s Boomer, but {olive}%N {default}popped it too early", g_iBoomerShover, Boomer, g_iBoomerKiller);
}
}
}
}
*/
//}
//} else {
// Boomer > Survivor Skills.
//}
}
/*
* "triggered_car_alarm"
* {
* "userid" "short" // person who triggered the car alarm
* }
*/
public void Event_AlarmCar(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
int iClient = GetClientOfUserId(hEvent.GetInt("userid"));
if (iClient > 0 && GetClientTeam(iClient) == TEAM_SURVIVOR) {
CPrintToChatAll("{green}★ {olive}%N {default}触发了 {olive}警报车", iClient);
}
}
void ClearMapStats()
{
for (int i = 1; i <= MaxClients; i++) {
ClearDamage(i);
}
}
void ClearDamage(int client)
{
g_iLastHealth[client] = 0;
for (int i = 1; i <= MaxClients; i++) {
g_iDamageDealt[client][i] = 0;
g_iShotsDealt[client][i] = 0;
}
}
public int ClientValue2DSortDesc(int[] x, int[] y, const int[][] array, Handle hndl)
{
if (x[1] > y[1]) {
return -1;
} else if (x[1] < y[1]) {
return 1;
} else {
return 0;
}
}
void DestroyTimer(Handle &hRefTimer)
{
if (hRefTimer != null) {
KillTimer(hRefTimer);
hRefTimer = null;
}
}
//// Code from decompiler ////
bool IsValidClient(int client)
{
return (client > 0 && client <= MaxClients && IsClientInGame(client));
}
////
| 0 | 0.965919 | 1 | 0.965919 | game-dev | MEDIA | 0.848916 | game-dev | 0.905644 | 1 | 0.905644 |
JoshParnell/ltheory | 5,860 | script/App/FMODTest.lua | local Bindings = ApplicationBindings
local FMODTest = Application()
local SFX = {
Gun = 'blaster',
Hero = 'chewy',
}
local kMoveSpeed = 100.0
function FMODTest:getTitle ()
return 'FMOD Test'
end
function FMODTest:onInit ()
Audio.Init()
Audio.Set3DSettings(1, 10, 2);
self.emitters = {
{ file = 'cantina', image = 'image/cantinaband', x = 128, y = 100 },
{ file = 'Imperial_March', image = 'image/vader', x = 256, y = 600 },
}
self.ambiances = {
'900years',
'breath',
'chewy',
'chosenone',
'comeback',
'dont',
'jabbalaugh',
'jedi',
'nerfherder',
'thybidding',
'traintheboy',
'yesmaster',
'yodalaugh',
}
self.rng = RNG.FromTime()
do -- Start async preload of effects
for k, v in pairs(SFX) do
Sound.LoadAsync(v, false, true)
end
end
Sound.Load('cantina', true, true)
for i = 1, #self.emitters do
local e = self.emitters[i]
e.tex = Tex2D.Load(e.image)
e.tex:genMipmap()
e.tex:setMagFilter(TexFilter.Linear)
e.tex:setMinFilter(TexFilter.LinearMipLinear)
e.sound = Sound.Load(e.file, true, true)
e.sound:set3DPos(Vec3f(e.x, 0, e.y), Vec3f(0, 0, 0))
--e.sound:setPlayPos(e.sound:getDuration() - 10*i)
e.sound:play()
end
self.lastFireTime = 0
self.pos = Vec3f(256, 0, 256)
self.vel = Vec3f(0, 0, 0)
self.ambianceTimer = 1.0 + self.rng:getExp()
self.particles = {}
self.onKeyDown = {
[Key.S] = function () self.vel.z = self.vel.z + kMoveSpeed * self.dt end,
[Key.W] = function () self.vel.z = self.vel.z - kMoveSpeed * self.dt end,
[Key.D] = function () self.vel.x = self.vel.x + kMoveSpeed * self.dt end,
[Key.A] = function () self.vel.x = self.vel.x - kMoveSpeed * self.dt end,
}
self.onKeyPress = {
[Key.N1] = function () Audio.Prepare(Audio.Load(SFX.Gun, true), true, false):play() end,
[Key.N2] = function () Audio.Prepare(Audio.Load(SFX.Hero, true), false, false):play() end,
[Key.Left] = function () self.pos = Vec3f( 10, 0, 0) end,
[Key.Right] = function () self.pos = Vec3f(-10, 0, 0) end,
[Key.Up] = function () self.pos = Vec3f( 0, 0, -10) end,
[Key.Down] = function () self.pos = Vec3f( 0, 0, 10) end,
[Key.Space] = function () self.pos = Vec3f( 0, 2, 0) end,
}
end
function FMODTest:onInput ()
if Input.GetPressed(Bindings.Exit) then
self:quit()
end
if Input.GetDown(Button.Mouse.Left) then
if TimeStamp.GetElapsed(self.lastFireTime) > 0.12 then
self.lastFireTime = self.lastUpdate
local sound = Sound.Load(SFX.Gun, false, true)
sound:setFreeOnFinish(true)
sound:set3DPos(Vec3f(0, 0, 0), Vec3f(0, 0, 0))
sound:setVolume(Math.Lerp(0.2, 0.6, self.rng:getUniform() ^ 2.0))
sound:play()
end
end
if Input.GetDown(Button.Mouse.Right) then
local is = Input.GetState()
self.pos.x = is.mousePosition.x
self.pos.z = is.mousePosition.y
end
for k, v in pairs(self.onKeyDown) do
if Input.GetDown(k) then v() end
end
for k, v in pairs(self.onKeyPress) do
if Input.GetPressed(k) then v() end
end
end
function FMODTest:onDraw ()
BlendMode.PushAlpha()
Draw.Clear(0.1, 0.1, 0.1, 1.0)
for i = 1, #self.emitters do
Draw.Color(1, 1, 1, 1)
local e = self.emitters[i]
local sz = e.tex:getSize()
e.tex:draw(e.x - 96, e.y - 96, 192, 192)
local d = Vec3f(e.x, 0, e.y):distance(self.pos)
local c = Vec3f():lerp(Vec3f(1.0, 0.0, 0.2), exp(-max(0, d / 128 - 1.0)))
Draw.Color(c.x, c.y, c.z, 1)
Draw.Border(8, e.x - 96, e.y - 96, 192, 192)
end
Draw.PointSize(2.0)
Draw.SmoothPoints(true)
for i = 1, #self.particles do
local p = self.particles[i]
local alpha = p.life / 5
Draw.Color(0.25, 1.0, 0.25, alpha * 0.8)
Draw.Point(p.x, p.y)
end
Draw.Color(0.1, 0.6, 1.0, 1.0)
Draw.Rect(self.pos.x - 4, self.pos.z - 4, 8, 8)
BlendMode.Pop()
end
function FMODTest:onUpdate (dt)
self.pos = self.pos + self.vel:scale(dt)
self.vel:iscale(exp(-dt))
do -- Play 'ambient' sound effects in a cloud around the listener
-- WARNING : May cause extreme annoyance, nightmares, and/or euphoria.
-- Josh hereby absolves himself of all responsibility.
self.ambianceTimer = self.ambianceTimer - dt
if self.ambianceTimer <= 0 then
self.ambianceTimer = self.ambianceTimer + 0.25 * self.rng:getExp()
local sound = Sound.Load(self.rng:choose(self.ambiances), false, true)
local dp = self.rng:getDir2():scale(100.0 * (1.0 + self.rng:getExp()))
sound:setFreeOnFinish(true)
sound:setPitch(Math.Clamp(1.0 + 0.1 * self.rng:getGaussian(), 0.6, 1.0 / 0.6))
sound:set3DPos(self.pos + Vec3f(dp.x, 0, dp.y), Vec3f(0, 0, 0))
sound:setVolume(0.5 + 0.5 * self.rng:getExp())
sound:play()
self.particles[#self.particles + 1] = { life = 5, x = self.pos.x + dp.x, y = self.pos.z + dp.y }
end
end
do -- Particle update
local i = 1
while i <= #self.particles do
local p = self.particles[i]
p.life = p.life - dt
if p.life < 0 then
self.particles[i] = self.particles[#self.particles]
self.particles[#self.particles] = nil
else i = i + 1 end
end
end
Audio.SetListenerPos(self.pos, self.vel, Vec3f(0, 0, -1), Vec3f(0, 1, 0))
Audio.Update()
--[[
for i = 1, #self.emitters do
local s = self.emitters[i].sound
--printf("%20s\t%.2f\t%s\t%s", tostring(s:getName()), s:getDuration(), s:isPlaying(), s:isFinished())
printf("%20s\t%.2f\t%s", tostring(s:getName()), s:getDuration(), s:isFinished())
end
--]]
end
function FMODTest:onExit ()
Audio.Free()
end
return FMODTest
-- TODO : Push Audio handling from LTheory up into Appliction?
-- TODO : Where is CoInitialize being called? I don't see a warning from FMOD
-- TODO : Pool of sounds with pitch variation
| 0 | 0.740863 | 1 | 0.740863 | game-dev | MEDIA | 0.948543 | game-dev | 0.894986 | 1 | 0.894986 |
blendogames/thirtyflightsofloving | 24,758 | game/m_boss32.c | /*
===========================================================================
Copyright (C) 1997-2001 Id Software, Inc.
Copyright (C) 2000-2002 Mr. Hyde and Mad Dog
This file is part of Lazarus Quake 2 Mod source code.
Lazarus Quake 2 Mod source code 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.
Lazarus Quake 2 Mod source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Lazarus Quake 2 Mod source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*
==============================================================================
Makron -- Final Boss
==============================================================================
*/
#include "g_local.h"
#include "m_boss32.h"
qboolean visible (edict_t *self, edict_t *other);
void MakronRailgun (edict_t *self);
void MakronSaveloc (edict_t *self);
void MakronHyperblaster (edict_t *self);
void makron_step_left (edict_t *self);
void makron_step_right (edict_t *self);
void makronBFG (edict_t *self);
void makron_dead (edict_t *self);
void SP_monster_makron_put (edict_t *self);
static int sound_pain4;
static int sound_pain5;
static int sound_pain6;
static int sound_death;
static int sound_step_left;
static int sound_step_right;
static int sound_attack_bfg;
static int sound_brainsplorch;
static int sound_prerailgun;
static int sound_popup;
static int sound_taunt1;
static int sound_taunt2;
static int sound_taunt3;
static int sound_hit;
void makron_taunt (edict_t *self)
{
float r;
r=random();
if (r <= 0.3)
gi.sound (self, CHAN_AUTO, sound_taunt1, 1, ATTN_NONE, 0);
else if (r <= 0.6)
gi.sound (self, CHAN_AUTO, sound_taunt2, 1, ATTN_NONE, 0);
else
gi.sound (self, CHAN_AUTO, sound_taunt3, 1, ATTN_NONE, 0);
}
//
// stand
//
mframe_t makron_frames_stand []=
{
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL, // 10
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL, // 20
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL, // 30
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL, // 40
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL, // 50
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL // 60
};
mmove_t makron_move_stand = {FRAME_stand201, FRAME_stand260, makron_frames_stand, NULL};
void makron_stand (edict_t *self)
{
self->monsterinfo.currentmove = &makron_move_stand;
}
mframe_t makron_frames_run [] =
{
ai_run, 3, makron_step_left,
ai_run, 12, NULL,
ai_run, 8, NULL,
ai_run, 8, NULL,
ai_run, 8, makron_step_right,
ai_run, 6, NULL,
ai_run, 12, NULL,
ai_run, 9, NULL,
ai_run, 6, NULL,
ai_run, 12, NULL
};
mmove_t makron_move_run = {FRAME_walk204, FRAME_walk213, makron_frames_run, NULL};
void makron_hit (edict_t *self)
{
gi.sound (self, CHAN_AUTO, sound_hit, 1, ATTN_NONE,0);
}
void makron_popup (edict_t *self)
{
gi.sound (self, CHAN_BODY, sound_popup, 1, ATTN_NONE,0);
}
void makron_step_left (edict_t *self)
{
gi.sound (self, CHAN_BODY, sound_step_left, 1, ATTN_NORM,0);
}
void makron_step_right (edict_t *self)
{
gi.sound (self, CHAN_BODY, sound_step_right, 1, ATTN_NORM,0);
}
void makron_brainsplorch (edict_t *self)
{
gi.sound (self, CHAN_VOICE, sound_brainsplorch, 1, ATTN_NORM,0);
}
void makron_prerailgun (edict_t *self)
{
gi.sound (self, CHAN_WEAPON, sound_prerailgun, 1, ATTN_NORM,0);
}
mframe_t makron_frames_walk [] =
{
ai_walk, 3, makron_step_left,
ai_walk, 12, NULL,
ai_walk, 8, NULL,
ai_walk, 8, NULL,
ai_walk, 8, makron_step_right,
ai_walk, 6, NULL,
ai_walk, 12, NULL,
ai_walk, 9, NULL,
ai_walk, 6, NULL,
ai_walk, 12, NULL
};
mmove_t makron_move_walk = {FRAME_walk204, FRAME_walk213, makron_frames_run, NULL};
void makron_walk (edict_t *self)
{
self->monsterinfo.currentmove = &makron_move_walk;
}
void makron_run (edict_t *self)
{
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
self->monsterinfo.currentmove = &makron_move_stand;
else
self->monsterinfo.currentmove = &makron_move_run;
}
mframe_t makron_frames_pain6 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 10
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, makron_popup,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 20
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, makron_taunt,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_pain6 = {FRAME_pain601, FRAME_pain627, makron_frames_pain6, makron_run};
mframe_t makron_frames_pain5 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_pain5 = {FRAME_pain501, FRAME_pain504, makron_frames_pain5, makron_run};
mframe_t makron_frames_pain4 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_pain4 = {FRAME_pain401, FRAME_pain404, makron_frames_pain4, makron_run};
mframe_t makron_frames_death2 [] =
{
ai_move, -15, NULL,
ai_move, 3, NULL,
ai_move, -12, NULL,
ai_move, 0, makron_step_left,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 10
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 11, NULL,
ai_move, 12, NULL,
ai_move, 11, makron_step_right,
ai_move, 0, NULL,
ai_move, 0, NULL, // 20
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 30
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 5, NULL,
ai_move, 7, NULL,
ai_move, 6, makron_step_left,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -1, NULL,
ai_move, 2, NULL, // 40
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 50
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -6, NULL,
ai_move, -4, NULL,
ai_move, -6, makron_step_right,
ai_move, -4, NULL,
ai_move, -4, makron_step_left,
ai_move, 0, NULL,
ai_move, 0, NULL, // 60
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -2, NULL,
ai_move, -5, NULL,
ai_move, -3, makron_step_right,
ai_move, -8, NULL,
ai_move, -3, makron_step_left,
ai_move, -7, NULL,
ai_move, -4, NULL,
ai_move, -4, makron_step_right, // 70
ai_move, -6, NULL,
ai_move, -7, NULL,
ai_move, 0, makron_step_left,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL, // 80
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -2, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 2, NULL,
ai_move, 0, NULL, // 90
ai_move, 27, makron_hit,
ai_move, 26, NULL,
ai_move, 0, makron_brainsplorch,
ai_move, 0, NULL,
ai_move, 0, NULL // 95
};
mmove_t makron_move_death2 = {FRAME_death201, FRAME_death295, makron_frames_death2, makron_dead};
mframe_t makron_frames_death3 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_death3 = {FRAME_death301, FRAME_death320, makron_frames_death3, NULL};
mframe_t makron_frames_sight [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_sight= {FRAME_active01, FRAME_active13, makron_frames_sight, makron_run};
void makronBFG (edict_t *self)
{
vec3_t forward, right;
vec3_t start;
vec3_t dir;
vec3_t vec;
AngleVectors (self->s.angles, forward, right, NULL);
G_ProjectSource (self->s.origin, monster_flash_offset[MZ2_MAKRON_BFG], forward, right, start);
VectorCopy (self->enemy->s.origin, vec);
vec[2] += self->enemy->viewheight;
VectorSubtract (vec, start, dir);
VectorNormalize (dir);
gi.sound (self, CHAN_VOICE, sound_attack_bfg, 1, ATTN_NORM, 0);
monster_fire_bfg (self, start, dir, 50, 300, 100, 300, MZ2_MAKRON_BFG);
}
mframe_t makron_frames_attack3 []=
{
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, makronBFG, // FIXME: BFG Attack here
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_attack3 = {FRAME_attak301, FRAME_attak308, makron_frames_attack3, makron_run};
mframe_t makron_frames_attack4[]=
{
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, MakronHyperblaster, // fire
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_attack4 = {FRAME_attak401, FRAME_attak426, makron_frames_attack4, makron_run};
mframe_t makron_frames_attack5[]=
{
ai_charge, 0, makron_prerailgun,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, MakronSaveloc,
ai_move, 0, MakronRailgun, // Fire railgun
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t makron_move_attack5 = {FRAME_attak501, FRAME_attak516, makron_frames_attack5, makron_run};
void MakronSaveloc (edict_t *self)
{
VectorCopy (self->enemy->s.origin, self->pos1); //save for aiming the shot
self->pos1[2] += self->enemy->viewheight;
};
// FIXME: He's not firing from the proper Z
void MakronRailgun (edict_t *self)
{
vec3_t start;
vec3_t dir;
vec3_t forward, right;
AngleVectors (self->s.angles, forward, right, NULL);
G_ProjectSource (self->s.origin, monster_flash_offset[MZ2_MAKRON_RAILGUN_1], forward, right, start);
// calc direction to where we targted
VectorSubtract (self->pos1, start, dir);
VectorNormalize (dir);
monster_fire_railgun (self, start, dir, 50, 100, MZ2_MAKRON_RAILGUN_1);
}
// FIXME: This is all wrong. He's not firing at the proper angles.
void MakronHyperblaster (edict_t *self)
{
vec3_t dir;
vec3_t vec;
vec3_t start;
vec3_t forward, right;
int flash_number;
flash_number = MZ2_MAKRON_BLASTER_1 + (self->s.frame - FRAME_attak405);
AngleVectors (self->s.angles, forward, right, NULL);
G_ProjectSource (self->s.origin, monster_flash_offset[flash_number], forward, right, start);
if (self->enemy)
{
VectorCopy (self->enemy->s.origin, vec);
vec[2] += self->enemy->viewheight;
VectorSubtract (vec, start, vec);
vectoangles (vec, vec);
dir[0] = vec[0];
}
else
{
dir[0] = 0;
}
if (self->s.frame <= FRAME_attak413)
dir[1] = self->s.angles[1] - 10 * (self->s.frame - FRAME_attak413);
else
dir[1] = self->s.angles[1] + 10 * (self->s.frame - FRAME_attak421);
dir[2] = 0;
AngleVectors (dir, forward, NULL, NULL);
monster_fire_blaster (self, start, forward, 15, 1000, MZ2_MAKRON_BLASTER_1, EF_BLASTER, BLASTER_ORANGE);
}
void makron_pain (edict_t *self, edict_t *other, float kick, int damage)
{
if (self->health < (self->max_health / 2))
{
self->s.skinnum |= 1;
if (!(self->fogclip & 2)) //custom bloodtype flag check
self->blood_type = 3; //sparks and blood
}
if (level.time < self->pain_debounce_time)
return;
// Lessen the chance of him going into his pain frames
if (damage <=25)
if (random()<0.2)
return;
self->pain_debounce_time = level.time + 3;
if (skill->value == 3)
return; // no pain anims in nightmare
if (damage <= 40)
{
gi.sound (self, CHAN_VOICE, sound_pain4, 1, ATTN_NONE,0);
self->monsterinfo.currentmove = &makron_move_pain4;
}
else if (damage <= 110)
{
gi.sound (self, CHAN_VOICE, sound_pain5, 1, ATTN_NONE,0);
self->monsterinfo.currentmove = &makron_move_pain5;
}
else if (damage <= 150)
{
if (random() <= 0.45)
{
gi.sound (self, CHAN_VOICE, sound_pain6, 1, ATTN_NONE,0);
self->monsterinfo.currentmove = &makron_move_pain6;
}
}
else
{
if (random() <= 0.35)
{
gi.sound (self, CHAN_VOICE, sound_pain6, 1, ATTN_NONE,0);
self->monsterinfo.currentmove = &makron_move_pain6;
}
}
};
void makron_sight(edict_t *self, edict_t *other)
{
self->monsterinfo.currentmove = &makron_move_sight;
};
void makron_attack(edict_t *self)
{
vec3_t vec;
float range;
float r;
r = random();
VectorSubtract (self->enemy->s.origin, self->s.origin, vec);
range = VectorLength (vec);
if (r <= 0.3)
self->monsterinfo.currentmove = &makron_move_attack3;
else if (r <= 0.6)
self->monsterinfo.currentmove = &makron_move_attack4;
else
self->monsterinfo.currentmove = &makron_move_attack5;
}
/*
---
Makron Torso. This needs to be spawned in
---
*/
void makron_torso_think (edict_t *self)
{
if (++self->s.frame < 365)
self->nextthink = level.time + FRAMETIME;
else
{
self->s.frame = 346;
self->nextthink = level.time + FRAMETIME;
}
}
void makron_torso_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
int n;
self->monsterinfo.power_armor_type = POWER_ARMOR_NONE;
// check for gib
if (self->health <= self->gib_health && !(self->spawnflags & SF_MONSTER_NOGIB))
{
for (n = 0; n < 1 /*4*/; n++)
ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", 0, 0, damage, GIB_ORGANIC);
for (n = 0; n < 4; n++)
ThrowGib (self, "models/objects/gibs/sm_metal/tris.md2", 0, 0, damage, GIB_METALLIC);
G_FreeEdict(self);
return;
}
}
void makron_torso (edict_t *ent)
{
// ent->movetype = MOVETYPE_NONE;
// ent->solid = SOLID_NOT;
// VectorSet (ent->mins, -8, -8, 0);
// VectorSet (ent->maxs, 8, 8, 8);
// Lazarus changes to make makron torso gibbable
ent->movetype = MOVETYPE_NONE;
ent->solid = SOLID_BBOX;
ent->svflags = SVF_DEADMONSTER;
VectorSet (ent->mins, -32, -32, 0);
VectorSet (ent->maxs, 32, 32, 32);
ent->health = -1;
ent->gib_health = -900;
ent->die = makron_torso_die;
ent->takedamage = DAMAGE_YES;
ent->deadflag = DEAD_DEAD;
ent->s.frame = 346;
ent->s.modelindex = gi.modelindex ("models/monsters/boss3/rider/tris.md2");
ent->think = makron_torso_think;
ent->nextthink = level.time + 2 * FRAMETIME;
ent->s.sound = gi.soundindex ("makron/spine.wav");
gi.linkentity (ent);
}
//
// death
//
void makron_dead (edict_t *self)
{
// Lazarus - this is way too big
// VectorSet (self->mins, -60, -60, 0);
// VectorSet (self->maxs, 60, 60, 72);
VectorSet (self->mins, -48, -48, 0);
VectorSet (self->maxs, 48, 48, 32);
self->movetype = MOVETYPE_TOSS;
self->svflags |= SVF_DEADMONSTER;
self->nextthink = 0;
gi.linkentity (self);
M_FlyCheck (self);
}
void makron_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
edict_t *tempent;
int n;
if (!(self->fogclip & 2)) //custom bloodtype flag check
self->blood_type = 3; //sparks and blood
self->monsterinfo.power_armor_type = POWER_ARMOR_NONE;
self->s.sound = 0;
// check for gib
if (self->health <= self->gib_health&& !(self->spawnflags & SF_MONSTER_NOGIB))
{
gi.sound (self, CHAN_VOICE, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0);
for (n = 0; n < 1 /*4*/; n++)
ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", 0, 0, damage, GIB_ORGANIC);
for (n = 0; n < 4; n++)
ThrowGib (self, "models/objects/gibs/sm_metal/tris.md2", 0, 0, damage, GIB_METALLIC);
ThrowHead (self, "models/objects/gibs/gear/tris.md2", 0, 0, damage, GIB_METALLIC);
self->deadflag = DEAD_DEAD;
return;
}
if (self->deadflag == DEAD_DEAD)
return;
// regular death
gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NONE, 0);
self->s.skinnum |= 1;
self->deadflag = DEAD_DEAD;
self->takedamage = DAMAGE_YES;
tempent = G_Spawn();
VectorCopy (self->s.origin, tempent->s.origin);
VectorCopy (self->s.angles, tempent->s.angles);
tempent->s.origin[1] -= 84;
makron_torso (tempent);
self->monsterinfo.currentmove = &makron_move_death2;
}
qboolean Makron_CheckAttack (edict_t *self)
{
vec3_t spot1, spot2;
vec3_t temp;
float chance;
trace_t tr;
qboolean enemy_infront;
int enemy_range;
float enemy_yaw;
if (self->enemy->health > 0)
{
// see if any entities are in the way of the shot
VectorCopy (self->s.origin, spot1);
spot1[2] += self->viewheight;
VectorCopy (self->enemy->s.origin, spot2);
spot2[2] += self->enemy->viewheight;
tr = gi.trace (spot1, NULL, NULL, spot2, self, CONTENTS_SOLID|CONTENTS_MONSTER|CONTENTS_SLIME|CONTENTS_LAVA);
// do we have a clear shot?
if (tr.ent != self->enemy)
return false;
}
enemy_infront = infront(self, self->enemy);
enemy_range = range(self, self->enemy);
VectorSubtract (self->enemy->s.origin, self->s.origin, temp);
enemy_yaw = vectoyaw(temp);
self->ideal_yaw = enemy_yaw;
// melee attack
if (enemy_range == RANGE_MELEE)
{
if (self->monsterinfo.melee)
self->monsterinfo.attack_state = AS_MELEE;
else
self->monsterinfo.attack_state = AS_MISSILE;
return true;
}
// missile attack
if (!self->monsterinfo.attack)
return false;
if (level.time < self->monsterinfo.attack_finished)
return false;
if (enemy_range == RANGE_FAR)
return false;
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
chance = 0.4;
}
else if (enemy_range == RANGE_MELEE)
{
chance = 0.8;
}
else if (enemy_range == RANGE_NEAR)
{
chance = 0.4;
}
else if (enemy_range == RANGE_MID)
{
chance = 0.2;
}
else
{
return false;
}
if (random () < chance)
{
self->monsterinfo.attack_state = AS_MISSILE;
self->monsterinfo.attack_finished = level.time + 2*random();
return true;
}
if (self->flags & FL_FLY)
{
if (random() < 0.3)
self->monsterinfo.attack_state = AS_SLIDING;
else
self->monsterinfo.attack_state = AS_STRAIGHT;
}
return false;
}
//
// monster_makron
//
void MakronPrecache (void)
{
sound_pain4 = gi.soundindex ("makron/pain3.wav");
sound_pain5 = gi.soundindex ("makron/pain2.wav");
sound_pain6 = gi.soundindex ("makron/pain1.wav");
sound_death = gi.soundindex ("makron/death.wav");
sound_step_left = gi.soundindex ("makron/step1.wav");
sound_step_right = gi.soundindex ("makron/step2.wav");
sound_attack_bfg = gi.soundindex ("makron/bfg_fire.wav");
sound_brainsplorch = gi.soundindex ("makron/brain1.wav");
sound_prerailgun = gi.soundindex ("makron/rail_up.wav");
sound_popup = gi.soundindex ("makron/popup.wav");
sound_taunt1 = gi.soundindex ("makron/voice4.wav");
sound_taunt2 = gi.soundindex ("makron/voice3.wav");
sound_taunt3 = gi.soundindex ("makron/voice.wav");
sound_hit = gi.soundindex ("makron/bhit.wav");
gi.modelindex ("models/monsters/boss3/rider/tris.md2");
}
/*QUAKED monster_makron (1 .5 0) (-30 -30 0) (30 30 90) Ambush Trigger_Spawn Sight
*/
// Knightmare- direct spawn function, sets nojump flag
void SP_monster_makron (edict_t *self)
{
self->fogclip |= 1;
SP_monster_makron_put (self);
}
void SP_monster_makron_put (edict_t *self)
{
if (deathmatch->value)
{
G_FreeEdict (self);
return;
}
MakronPrecache ();
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
self->s.modelindex = gi.modelindex ("models/monsters/boss3/rider/tris.md2");
VectorSet (self->mins, -30, -30, 0);
VectorSet (self->maxs, 30, 30, 90);
// Lazarus: mapper-configurable health
if (!self->health)
self->health = 3000;
// Lazarus: get around Killed's prevention of health dropping below -999
// if (!self->gib_health)
// self->gib_health = -2000;
if (!self->gib_health)
self->gib_health = -800;
if (!self->mass)
self->mass = 500;
self->pain = makron_pain;
self->die = makron_die;
self->monsterinfo.stand = makron_stand;
self->monsterinfo.walk = makron_walk;
self->monsterinfo.run = makron_run;
self->monsterinfo.dodge = NULL;
self->monsterinfo.attack = makron_attack;
self->monsterinfo.melee = NULL;
self->monsterinfo.sight = makron_sight;
self->monsterinfo.checkattack = Makron_CheckAttack;
// Knightmare- added sparks and blood type
if (!self->blood_type)
self->blood_type = 2; // sparks
else
self->fogclip |= 2; // custom bloodtype flag
// Lazarus
if (self->powerarmor)
{
if (self->powerarmortype == 1)
self->monsterinfo.power_armor_type = POWER_ARMOR_SCREEN;
else
self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD;
self->monsterinfo.power_armor_power = self->powerarmor;
}
self->common_name = "Makron";
self->class_id = ENTITY_MONSTER_MAKRON;
gi.linkentity (self);
// Knightmare- nojump flag
if (self->fogclip & 1)
self->monsterinfo.currentmove = &makron_move_stand;
else
self->monsterinfo.currentmove = &makron_move_sight;
if (self->health < 0)
{
mmove_t *deathmoves[] = {&makron_move_death2,
&makron_move_death3,
NULL};
M_SetDeath(self, (mmove_t **)&deathmoves);
}
self->monsterinfo.scale = MODEL_SCALE;
walkmonster_start(self);
}
/*
=================
MakronSpawn
=================
*/
void MakronSpawn (edict_t *self)
{
vec3_t vec;
edict_t *player;
self->classname = "monster_makron"; // Knightmare- set the right classname
SP_monster_makron_put (self);
// Knightmare- gross hack for map6 of COS3- don't jump
if (Q_stricmp(level.mapname, "grinsp3f") == 0)
return;
// jump at player
player = level.sight_client;
if (!player)
return;
VectorSubtract (player->s.origin, self->s.origin, vec);
self->s.angles[YAW] = vectoyaw(vec);
VectorNormalize (vec);
VectorMA (vec3_origin, 400, vec, self->velocity);
self->velocity[2] = 200;
self->groundentity = NULL;
}
/*
=================
MakronToss
Jorg is just about dead, so set up to launch Makron out
=================
*/
void MakronToss (edict_t *self)
{
edict_t *ent;
ent = G_Spawn ();
ent->nextthink = level.time + 0.8;
ent->think = MakronSpawn;
ent->target = self->target;
// Knightmare- if Jorg was killed by a trigger_hurt, set nojump flag
if (self->fogclip & 4)
ent->fogclip |= 1;
ent->health = self->health2;
ent->mass = self->mass2;
// ent->common_name = "Makron";
// self->class_id = ENTITY_MONSTER_MAKRON;
#ifdef KMQUAKE2_ENGINE_MOD
// If the Jorg was transparent, make Makron transparent, too.
if (self->s.alpha)
ent->s.alpha = self->s.alpha;
#endif
VectorCopy (self->s.origin, ent->s.origin);
self->s.modelindex2 = 0; // Knightmare- remove Makron model from dead Jorg
}
| 0 | 0.912678 | 1 | 0.912678 | game-dev | MEDIA | 0.792116 | game-dev | 0.872436 | 1 | 0.872436 |
SkriptLang/Skript | 1,314 | src/main/java/org/skriptlang/skript/bukkit/breeding/BreedingModule.java | package org.skriptlang.skript.bukkit.breeding;
import ch.njol.skript.Skript;
import ch.njol.skript.lang.util.SimpleEvent;
import ch.njol.skript.registrations.EventValues;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.entity.EntityBreedEvent;
import org.bukkit.event.entity.EntityEnterLoveModeEvent;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
public class BreedingModule {
public static void load() throws IOException {
Skript.getAddonInstance().loadClasses("org.skriptlang.skript.bukkit.breeding", "elements");
Skript.registerEvent("Love Mode Enter", SimpleEvent.class, EntityEnterLoveModeEvent.class,
"[entity] enter[s] love mode", "[entity] love mode [enter]")
.description("Called whenever an entity enters a state of being in love.")
.examples(
"on love mode enter:",
"\tcancel event # No one is allowed love here"
)
.since("2.10");
EventValues.registerEventValue(EntityBreedEvent.class, ItemStack.class, EntityBreedEvent::getBredWith);
EventValues.registerEventValue(EntityEnterLoveModeEvent.class, LivingEntity.class, EntityEnterLoveModeEvent::getEntity);
EventValues.registerEventValue(EntityEnterLoveModeEvent.class, HumanEntity.class, EntityEnterLoveModeEvent::getHumanEntity);
}
}
| 0 | 0.791259 | 1 | 0.791259 | game-dev | MEDIA | 0.870903 | game-dev | 0.716193 | 1 | 0.716193 |
PacktPublishing/Mastering-Cpp-Game-Development | 2,846 | Chapter07/Include/bullet/LinearMath/btStackAlloc.h | /*
Copyright (c) 2003-2006 Gino van den Bergen / 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.
*/
/*
StackAlloc extracted from GJK-EPA collision solver by Nathanael Presson
Nov.2006
*/
#ifndef BT_STACK_ALLOC
#define BT_STACK_ALLOC
#include "btScalar.h" //for btAssert
#include "btAlignedAllocator.h"
///The btBlock class is an internal structure for the btStackAlloc memory allocator.
struct btBlock
{
btBlock* previous;
unsigned char* address;
};
///The StackAlloc class provides some fast stack-based memory allocator (LIFO last-in first-out)
class btStackAlloc
{
public:
btStackAlloc(unsigned int size) { ctor();create(size); }
~btStackAlloc() { destroy(); }
inline void create(unsigned int size)
{
destroy();
data = (unsigned char*) btAlignedAlloc(size,16);
totalsize = size;
}
inline void destroy()
{
btAssert(usedsize==0);
//Raise(L"StackAlloc is still in use");
if(usedsize==0)
{
if(!ischild && data)
btAlignedFree(data);
data = 0;
usedsize = 0;
}
}
int getAvailableMemory() const
{
return static_cast<int>(totalsize - usedsize);
}
unsigned char* allocate(unsigned int size)
{
const unsigned int nus(usedsize+size);
if(nus<totalsize)
{
usedsize=nus;
return(data+(usedsize-size));
}
btAssert(0);
//&& (L"Not enough memory"));
return(0);
}
SIMD_FORCE_INLINE btBlock* beginBlock()
{
btBlock* pb = (btBlock*)allocate(sizeof(btBlock));
pb->previous = current;
pb->address = data+usedsize;
current = pb;
return(pb);
}
SIMD_FORCE_INLINE void endBlock(btBlock* block)
{
btAssert(block==current);
//Raise(L"Unmatched blocks");
if(block==current)
{
current = block->previous;
usedsize = (unsigned int)((block->address-data)-sizeof(btBlock));
}
}
private:
void ctor()
{
data = 0;
totalsize = 0;
usedsize = 0;
current = 0;
ischild = false;
}
unsigned char* data;
unsigned int totalsize;
unsigned int usedsize;
btBlock* current;
bool ischild;
};
#endif //BT_STACK_ALLOC
| 0 | 0.710836 | 1 | 0.710836 | game-dev | MEDIA | 0.259286 | game-dev | 0.934858 | 1 | 0.934858 |
JetBrains/resharper-unity | 4,971 | resharper/resharper-unity/src/Unity/CSharp/Feature/Services/LiveTemplates/Scope/InUnityCSharpProject.cs | using System;
using JetBrains.ProjectModel.Properties;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope;
using JetBrains.ReSharper.Plugins.Unity.Resources;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
// DefaultUID is convention, but inconsistent
// ReSharper disable InconsistentNaming
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.LiveTemplates.Scope
{
// Defines a scope point, but has no inherent behaviour, other than to compare against
// other scope points. A template can declare that it requires this scope point, and
// the template will only be made available if a ScopeProvider "publishes" this scope
// point based on the current context (e.g. the project is a Unity project)
public class InUnityCSharpProject : InLanguageSpecificProject
{
private static readonly Guid DefaultUID = new Guid("B37325A3-4F0A-405B-8A5C-00ECA4ED3B30");
private static readonly Guid QuickUID = new Guid("D32F297F-E422-4612-839A-FE76D9914B34");
public InUnityCSharpProject()
: base(ProjectLanguage.CSHARP)
{
AdditionalSuperTypes.Add(typeof(InLanguageSpecificProject));
}
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityProjects_Text;
public override PsiLanguageType RelatedLanguage => CSharpLanguage.Instance;
// Define the name and UID of the QuickList we'll use for Unity projects. Any
// scope points that are subsets will appear in this QuickList (I think)
public override string QuickListTitle => "Unity projects";
public override Guid QuickListUID => QuickUID;
}
// TODO: Add scope for inside the Packages folder (with or without PSI project?)
// TODO: Add scope for inside an assembly definition folder
// Scope is anywhere inside the Assets folder. Note that this does not include packages. It will include assembly
// definitions if they are inside Assets, but not elsewhere.
// TODO: Should it have a base of C# project? What about folders outside of the PSI project structure?
public class InUnityCSharpAssetsFolder : InUnityCSharpProject
{
private static readonly Guid DefaultUID = new Guid("400D0960-419A-4D68-B6BD-024A7C9E4DDB");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityAssetsFolder_Text;
}
// Scope is Assets/**/Editor/**
public class InUnityCSharpEditorFolder : InUnityCSharpAssetsFolder
{
private static readonly Guid DefaultUID = new Guid("725DF216-7E35-4AAF-8C8E-3FEF06B172AA");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityEditorFolder_Text;
}
// Scope is anywhere under non-editor folder under Assets: Assets/**/!Editor/**
public class InUnityCSharpRuntimeFolder : InUnityCSharpAssetsFolder
{
private static readonly Guid DefaultUID = new Guid("AD3BD55C-0026-4C29-B6AD-6B82170CD657");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityRuntimeFolder_Text;
}
// Scope is anywhere under a firstpass folder in Assets:
// Assets/Standard Assets/**
// Assets/Pro Standard Assets/**
// Assets/Plugins/**
// (For clarity, this includes Editor folders)
public class InUnityCSharpFirstpassFolder : InUnityCSharpAssetsFolder
{
private static readonly Guid DefaultUID = new Guid("9B4C634E-812C-4699-BED0-7FC0A34533DB");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityFirstpassFolder_Text;
}
// Scope is anywhere under an Editor folder in a firstpass folder of Assets:
// Assets/Standard Assets/**/Editor/**
// Assets/Pro Standard Assets/**/Editor/**
// Assets/Plugins/**/Editor/**
public class InUnityCSharpFirstpassEditorFolder : InUnityCSharpFirstpassFolder
{
private static readonly Guid DefaultUID = new Guid("375D8555-CCD0-4D17-B6F6-2DCC1E01FCAB");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityFirstpassEditorFolder_Text;
}
// Scope is anywhere under a firstpass folder in Assets that is NOT an editor folder:
// Assets/Standard Assets/**/!Editor/**
// Assets/Pro Standard Assets/**/!Editor/**
// Assets/Plugins/**/!Editor/**
public class InUnityCSharpFirstpassRuntimeFolder : InUnityCSharpFirstpassFolder
{
private static readonly Guid DefaultUID = new Guid("101DB5F5-CE2E-4CD3-954F-34CE9AB3ECEA");
public override Guid GetDefaultUID() => DefaultUID;
public override string PresentableShortName => Strings.UnityFirstpassRuntimeFolder_Text;
}
} | 0 | 0.718016 | 1 | 0.718016 | game-dev | MEDIA | 0.803698 | game-dev | 0.64521 | 1 | 0.64521 |
Fabricators-of-Create/Porting-Lib | 1,657 | modules/entity/src/testmod/java/io/github/fabricators_of_create/porting_lib/entity/testmod/CustomSlimeRenderer.java | package io.github.fabricators_of_create.porting_lib.entity.testmod;
import org.jetbrains.annotations.NotNull;
import com.mojang.blaze3d.vertex.PoseStack;
import io.github.fabricators_of_create.porting_lib.entity.testmod.CustomSlime.OrbitingItem;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.renderer.entity.SlimeRenderer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.world.entity.monster.Slime;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.phys.Vec3;
public class CustomSlimeRenderer extends SlimeRenderer {
private final ItemRenderer itemRenderer;
public CustomSlimeRenderer(Context context) {
super(context);
this.itemRenderer = context.getItemRenderer();
}
@Override
public void render(@NotNull Slime slime, float yaw, float tickDelta, @NotNull PoseStack poseStack, @NotNull MultiBufferSource buffers, int light) {
super.render(slime, yaw, tickDelta, poseStack, buffers, light);
if (!(slime instanceof CustomSlime custom))
return;
OrbitingItem item = custom.item;
BakedModel model = itemRenderer.getModel(item.stack, slime.level(), slime, 0);
poseStack.pushPose();
Vec3 offset = item.getOffset(tickDelta);
poseStack.translate(offset.x, offset.y, offset.z);
itemRenderer.render(
item.stack, ItemDisplayContext.FIXED, false, poseStack, buffers, light, OverlayTexture.NO_OVERLAY, model
);
poseStack.popPose();
}
}
| 0 | 0.633718 | 1 | 0.633718 | game-dev | MEDIA | 0.895161 | game-dev,graphics-rendering | 0.815591 | 1 | 0.815591 |
It-Life/Deer_GameFramework_Wolong | 2,704 | Assets/Standard Assets/DeerExample/Lean/Common+/Extras/LeanChaseRigidbody2D.cs | using UnityEngine;
namespace Lean.Common
{
/// <summary>This script allows you to drag this Rigidbody2D in a way that causes it to chase the specified position.</summary>
[RequireComponent(typeof(Rigidbody2D))]
[HelpURL(LeanHelper.PlusHelpUrlPrefix + "LeanChaseRigidbody2D")]
[AddComponentMenu(LeanHelper.ComponentPathPrefix + "Chase Rigidbody2D")]
public class LeanChaseRigidbody2D : LeanChase
{
public enum AxisType
{
HorizontalAndVertical,
Horizontal,
Vertical
}
/// <summary>This allows you to control which axes the velocity can apply to.</summary>
public AxisType Axis { set { axis = value; } get { return axis; } } [SerializeField] private AxisType axis;
[System.NonSerialized]
private Rigidbody2D cachedRigidbody;
[System.NonSerialized]
protected bool fixedUpdateCalled;
/// <summary>This method will override the Position value based on the specified value.</summary>
public override void SetPosition(Vector3 newPosition)
{
base.SetPosition(newPosition);
fixedUpdateCalled = false;
}
protected virtual void OnEnable()
{
cachedRigidbody = GetComponent<Rigidbody2D>();
}
protected override void UpdatePosition(float damping, float linear)
{
if (positionSet == true || continuous == true)
{
if (destination != null)
{
position = destination.TransformPoint(destinationOffset);
}
var currentPosition = (Vector2)(transform.position);
var targetPosition = (Vector2)(position + offset);
var direction = targetPosition - currentPosition;
var velocity = direction / Time.fixedDeltaTime;
// Apply the velocity
velocity *= LeanHelper.GetDampenFactor(damping, Time.fixedDeltaTime);
velocity = Vector3.MoveTowards(velocity, Vector3.zero, linear * Time.fixedDeltaTime);
if (axis == AxisType.Horizontal)
{
velocity.y = cachedRigidbody.velocity.y;
}
else if (axis == AxisType.Vertical)
{
velocity.x = cachedRigidbody.velocity.x;
}
cachedRigidbody.velocity = velocity;
fixedUpdateCalled = true;
}
}
protected virtual void LateUpdate()
{
if (fixedUpdateCalled == true)
{
positionSet = false;
fixedUpdateCalled = false;
}
}
}
}
#if UNITY_EDITOR
namespace Lean.Common.Editor
{
using TARGET = LeanChaseRigidbody2D;
[UnityEditor.CanEditMultipleObjects]
[UnityEditor.CustomEditor(typeof(TARGET))]
public class LeanChaseRigidbody2D_Editor : LeanChase_Editor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
base.OnInspector();
Separator();
Draw("axis", "This allows you to control which axes the velocity can apply to.");
}
}
}
#endif | 0 | 0.934607 | 1 | 0.934607 | game-dev | MEDIA | 0.967354 | game-dev | 0.972578 | 1 | 0.972578 |
shiptest-ss13/Shiptest | 3,551 | code/datums/components/slippery.dm | /datum/component/slippery
dupe_mode = COMPONENT_DUPE_UNIQUE_PASSARGS
var/force_drop_items = FALSE
var/knockdown_time = 0
var/paralyze_time = 0
var/lube_flags
var/datum/callback/callback
var/mob/living/holder
var/list/slot_whitelist = list(ITEM_SLOT_OCLOTHING, ITEM_SLOT_ICLOTHING, ITEM_SLOT_GLOVES, ITEM_SLOT_FEET, ITEM_SLOT_HEAD, ITEM_SLOT_MASK, ITEM_SLOT_BELT, ITEM_SLOT_NECK)
///what we give to connect_loc by default, makes slippable mobs moving over us slip
var/static/list/default_connections = list(
COMSIG_ATOM_ENTERED = PROC_REF(Slip),
)
///what we give to connect_loc if we're an item and get equipped by a mob. makes slippable mobs moving over our holder slip
var/static/list/holder_connections = list(
COMSIG_ATOM_ENTERED = PROC_REF(Slip_on_wearer),
)
/// The connect_loc_behalf component for the holder_connections list.
var/datum/weakref/holder_connect_loc_behalf
/datum/component/slippery/Initialize(_knockdown, _lube_flags = NONE, datum/callback/_callback, _paralyze, _force_drop = FALSE)
knockdown_time = max(_knockdown, 0)
paralyze_time = max(_paralyze, 0)
force_drop_items = _force_drop
lube_flags = _lube_flags
callback = _callback
add_connect_loc_behalf_to_parent()
if(ismovable(parent))
if(isitem(parent))
RegisterSignal(parent, COMSIG_ITEM_EQUIPPED, PROC_REF(on_equip))
RegisterSignal(parent, COMSIG_ITEM_DROPPED, PROC_REF(on_drop))
else
RegisterSignal(parent, COMSIG_ATOM_ENTERED, PROC_REF(Slip))
/datum/component/slippery/proc/add_connect_loc_behalf_to_parent()
if(ismovable(parent))
AddComponent(/datum/component/connect_loc_behalf, parent, default_connections)
/datum/component/slippery/InheritComponent(datum/component/slippery/component, i_am_original, knockdown, lube_flags = NONE, datum/callback/callback, paralyze, force_drop = FALSE, slot_whitelist)
if(component)
knockdown = component.knockdown_time
lube_flags = component.lube_flags
callback = component.callback
paralyze = component.paralyze_time
force_drop = component.force_drop_items
slot_whitelist = component.slot_whitelist
src.knockdown_time = max(knockdown, 0)
src.paralyze_time = max(paralyze, 0)
src.force_drop_items = force_drop
src.lube_flags = lube_flags
src.callback = callback
if(slot_whitelist)
src.slot_whitelist = slot_whitelist
/datum/component/slippery/proc/Slip(datum/source, atom/movable/arrived, atom/old_loc, list/atom/old_locs)
SIGNAL_HANDLER
if(!isliving(arrived))
return
var/mob/living/victim = arrived
if(!(victim.movement_type & FLYING) && victim.slip(knockdown_time, parent, lube_flags, paralyze_time, force_drop_items) && callback)
callback.Invoke(victim)
/datum/component/slippery/proc/on_equip(datum/source, mob/equipper, slot)
SIGNAL_HANDLER
if((!LAZYLEN(slot_whitelist) || (slot in slot_whitelist)) && isliving(equipper))
holder = equipper
qdel(GetComponent(/datum/component/connect_loc_behalf))
AddComponent(/datum/component/connect_loc_behalf, holder, holder_connections)
RegisterSignal(holder, COMSIG_PARENT_PREQDELETED, PROC_REF(holder_deleted))
/datum/component/slippery/proc/holder_deleted(datum/source, datum/possible_holder)
SIGNAL_HANDLER
if(possible_holder == holder)
holder = null
/datum/component/slippery/proc/on_drop(datum/source, mob/user)
SIGNAL_HANDLER
UnregisterSignal(user, COMSIG_PARENT_PREQDELETED)
qdel(GetComponent(/datum/component/connect_loc_behalf))
add_connect_loc_behalf_to_parent()
holder = null
/datum/component/slippery/proc/Slip_on_wearer(datum/source, atom/movable/arrived)
SIGNAL_HANDLER
| 0 | 0.969308 | 1 | 0.969308 | game-dev | MEDIA | 0.755392 | game-dev | 0.983339 | 1 | 0.983339 |
neperfepx/neper | 22,513 | src/neut/neut_tesr/neut_tesr_geom/neut_tesr_geom1.c | /* This file is part of the Neper software package. */
/* Copyright (C) 2003-2024, Romain Quey. */
/* See the COPYING file in the tgeom-level directory. */
#include "neut_tesr_geom_.h"
int
neut_tesr_vox_pos (struct TESR Tesr, int vox, int *pos)
{
int qty, unitqty;
qty = vox;
unitqty = Tesr.size[0] * Tesr.size[1];
pos[2] = 1 + (qty - 1) / unitqty;
qty -= (pos[2] - 1) * unitqty;
unitqty = Tesr.size[0];
pos[1] = 1 + (qty - 1) / unitqty;
qty -= (pos[1] - 1) * unitqty;
pos[0] = qty;
return 0;
}
int
neut_tesr_pos3_vox (struct TESR Tesr, int x, int y, int z, int *pvox)
{
(*pvox) =
(z - 1) * Tesr.size[1] * Tesr.size[0] + (y - 1) * Tesr.size[0] + x;
return 0;
}
int
neut_tesr_pos_vox (struct TESR Tesr, int *pos, int *pvox)
{
return neut_tesr_pos3_vox (Tesr, pos[0], pos[1], pos[2], pvox);
}
int
neut_tesr_vox_coo (struct TESR Tesr, int vox, double *coo)
{
int pos[3];
neut_tesr_vox_pos (Tesr, vox, pos);
neut_tesr_pos_coo (Tesr, pos, coo);
return 0;
}
int
neut_tesr_vox_oridef (struct TESR Tesr, int vox, int *poridef)
{
int pos[3];
*poridef = 0;
neut_tesr_vox_pos (Tesr, vox, pos);
if (Tesr.VoxOri)
{
if (!Tesr.VoxOriDef)
*poridef = 1;
else
*poridef = Tesr.VoxOriDef[pos[0]][pos[1]][pos[2]];
}
else
*poridef = 0;
return 0;
}
int
neut_tesr_vox_ori (struct TESR Tesr, int vox, double *ori)
{
int pos[3];
neut_tesr_vox_pos (Tesr, vox, pos);
if (Tesr.VoxCell[pos[0]][pos[1]][pos[2]])
{
if (Tesr.VoxOri)
ut_array_1d_memcpy (Tesr.VoxOri[pos[0]][pos[1]][pos[2]], 4, ori);
else
ut_array_1d_memcpy (Tesr.CellOri[Tesr.VoxCell[pos[0]][pos[1]][pos[2]]], 4, ori);
return 0;
}
else
{
ut_array_1d_zero (ori, 4);
return -1;
}
}
int
neut_tesr_vox_cell (struct TESR Tesr, int vox, int *pcell)
{
int voxpos[3];
neut_tesr_vox_pos (Tesr, vox, voxpos);
(*pcell) = Tesr.VoxCell[voxpos[0]][voxpos[1]][voxpos[2]];
return 0;
}
int
neut_tesr_vox_cellid (struct TESR Tesr, int vox, int *pcell)
{
neut_tesr_vox_cell (Tesr, vox, pcell);
if (Tesr.CellId)
(*pcell) = Tesr.CellId[(*pcell)];
return 0;
}
int
neut_tesr_coo_pos (struct TESR Tesr, double *coo, int mode, int *voxpos)
{
int i;
for (i = 0; i < Tesr.Dim; i++)
{
voxpos[i] =
ceil ((coo[i] - Tesr.Origin[i]) / Tesr.vsize[i] +
ut_num_sgn_int (mode) * 1e-6);
// voxpos[i] = ut_num_min_int (voxpos[i], Tesr.size[i]);
}
for (i = Tesr.Dim; i < 3; i++)
voxpos[i] = 1;
return 0;
}
int
neut_tesr_pos_coo (struct TESR Tesr, int *voxpos, double *coo)
{
int i;
for (i = 0; i < Tesr.Dim; i++)
coo[i] = Tesr.Origin[i] + (voxpos[i] - 0.5) * Tesr.vsize[i];
return 0;
}
int
neut_tesr_cell_voxqty (struct TESR Tesr, int cell)
{
int i, j, k, vqty;
vqty = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
vqty++;
return vqty;
}
void
neut_tesr_cell_voxs (struct TESR Tesr, int cell, int ***pvoxs, int *pvoxqty)
{
int i, j, k, vqty;
*pvoxqty = neut_tesr_cell_voxqty (Tesr, cell);
(*pvoxs) = ut_alloc_2d_int (*pvoxqty, 3);
vqty = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
ut_array_1d_int_set_3 ((*pvoxs)[vqty++], i, j, k);
return;
}
int
neut_tesr_voxqty (struct TESR Tesr)
{
int i, j, k, vqty;
vqty = 0;
for (k = 1; k <= Tesr.size[2]; k++)
for (j = 1; j <= Tesr.size[1]; j++)
for (i = 1; i <= Tesr.size[0]; i++)
if (Tesr.VoxCell[i][j][k] != 0)
vqty++;
return vqty;
}
int
neut_tesr_totvoxqty (struct TESR Tesr)
{
if (Tesr.Dim == 2)
return Tesr.size[0] * Tesr.size[1];
else if (Tesr.Dim == 3)
return Tesr.size[0] * Tesr.size[1] * Tesr.size[2];
else
return 0;
}
double
neut_tesr_avcellvoxqty (struct TESR Tesr)
{
return (double) neut_tesr_voxqty (Tesr) / Tesr.CellQty;
}
int
neut_tesr_cell_volume (struct TESR Tesr, int cell, double *pvol)
{
int vqty;
double voxvol;
vqty = neut_tesr_cell_voxqty (Tesr, cell);
neut_tesr_voxsize (Tesr, &voxvol);
(*pvol) = voxvol * vqty;
return (*pvol > 0) ? 0 : -1;
}
int
neut_tesr_cell_area (struct TESR Tesr, int cell, double *parea)
{
int i, j;
if (Tesr.Dim != 2)
abort ();
(*parea) = 0;
for (j = 1; j <= Tesr.size[1]; j++)
for (i = 1; i <= Tesr.size[0]; i++)
if (Tesr.VoxCell[i][j][1] == cell)
(*parea)++;
(*parea) *= (Tesr.vsize[0] * Tesr.vsize[1]);
return 0;
}
int
neut_tesr_cell_size (struct TESR Tesr, int cell, double *psize)
{
if (Tesr.Dim == 2)
neut_tesr_cell_area (Tesr, cell, psize);
else if (Tesr.Dim == 3)
neut_tesr_cell_volume (Tesr, cell, psize);
else
abort ();
return 0;
}
int
neut_tesr_cell_centre (struct TESR Tesr, int cell, double *coo)
{
int i, j, k, qty;
int *voxpos = NULL;
double *voxcoo = NULL;
voxpos = ut_alloc_1d_int (3);
voxcoo = ut_alloc_1d (3);
qty = 0;
ut_array_1d_zero (coo, 3);
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
{
ut_array_1d_int_set_3 (voxpos, i, j, k);
neut_tesr_pos_coo (Tesr, voxpos, voxcoo);
ut_array_1d_add (coo, voxcoo, 3, coo);
qty++;
}
if (qty > 0)
ut_array_1d_scale (coo, 3, 1. / qty);
ut_free_1d_int (&voxpos);
ut_free_1d (&voxcoo);
return (qty > 0) ? 0 : -1;
}
void
neut_tesr_cells_centre (struct TESR Tesr, int *cells, int cellqty, double *coo)
{
int i, cell;
double size, totsize, *tmp = ut_alloc_1d (3);
ut_array_1d_zero (coo, 3);
totsize = 0;
for (i = 0; i < cellqty; i++)
{
cell = cells[i];
neut_tesr_cell_centre (Tesr, cell, tmp);
neut_tesr_cell_size (Tesr, cell, &size);
totsize += size;
ut_array_1d_scale (tmp, 3, size);
ut_array_1d_add (coo, tmp, 3, coo);
}
ut_array_1d_scale (coo, 3, 1. / totsize);
ut_free_1d (&tmp);
return;
}
void
neut_tesr_rastercentre (struct TESR Tesr, double *coo)
{
int i;
for (i = 0; i < 3; i++)
coo[i] = Tesr.Origin[i] + 0.5 * Tesr.vsize[i] * Tesr.size[i];
return;
}
void
neut_tesr_centre (struct TESR Tesr, double *coo)
{
int i, j;
double *vol = NULL, **cellcoo = NULL;
if (Tesr.hasvoid == -1 || Tesr.hasvoid == 0)
{
neut_tesr_rastercentre (Tesr, coo);
return;
}
vol = ut_alloc_1d (Tesr.CellQty);
cellcoo = ut_alloc_2d (Tesr.CellQty, 3);
for (i = 0; i < Tesr.CellQty; i++)
{
neut_tesr_cell_volume (Tesr, i + 1, vol + i);
neut_tesr_cell_centre (Tesr, i + 1, cellcoo[i]);
}
ut_array_1d_zero (coo, 3);
for (i = 0; i < Tesr.CellQty; i++)
for (j = 0; j < 3; j++)
coo[j] += vol[i] * cellcoo[i][j];
ut_array_1d_scale (coo, 3, 1. / ut_array_1d_sum (vol, Tesr.CellQty));
ut_free_1d (&vol);
ut_free_2d (&cellcoo, Tesr.CellQty);
return;
}
void
neut_tesr_centre_x (struct TESR Tesr, double *px)
{
double *c = ut_alloc_1d (3);
neut_tesr_centre (Tesr, c);
(*px) = c[0];
ut_free_1d (&c);
return;
}
void
neut_tesr_centre_y (struct TESR Tesr, double *py)
{
double *c = ut_alloc_1d (3);
neut_tesr_centre (Tesr, c);
(*py) = c[1];
ut_free_1d (&c);
return;
}
void
neut_tesr_centre_z (struct TESR Tesr, double *pz)
{
double *c = ut_alloc_1d (3);
neut_tesr_centre (Tesr, c);
(*pz) = c[2];
ut_free_1d (&c);
return;
}
void
neut_tesr_cell_diameq (struct TESR Tesr, int cell, double *pval)
{
if (Tesr.Dim == 3)
{
neut_tesr_cell_volume (Tesr, cell, pval);
(*pval) = pow ((6 / M_PI) * (*pval), 0.3333333333333333333333333);
}
else if (Tesr.Dim == 2)
{
neut_tesr_cell_area (Tesr, cell, pval);
(*pval) = sqrt ((4 / M_PI) * (*pval));
}
else
abort ();
return;
}
void
neut_tesr_cell_radeq (struct TESR Tesr, int cell, double *pval)
{
neut_tesr_cell_diameq (Tesr, cell, pval);
(*pval) *= 0.5;
return;
}
void
neut_tesr_cell_points (struct TESR Tesr, int cell, int ***ppts, int *pptqty)
{
int i, j, k;
if (!Tesr.CellBBox)
ut_print_neperbug ();
(*pptqty) = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
{
(*pptqty)++;
(*ppts) = ut_realloc_2d_int_addline (*ppts, *pptqty, 3);
ut_array_1d_int_set_3 ((*ppts)[(*pptqty) - 1], i, j, k);
}
return;
}
void
neut_tesr_cell_coos (struct TESR Tesr, int cell, double ***pcoos,
int *pcooqty)
{
int i, **pts = NULL;
neut_tesr_cell_points (Tesr, cell, &pts, pcooqty);
// ut_array_2d_int_fprintf (stdout, pts, *pcooqty, 3, "%d");
(*pcoos) = ut_alloc_2d (*pcooqty, Tesr.Dim);
for (i = 0; i < *pcooqty; i++)
neut_tesr_pos_coo (Tesr, pts[i], (*pcoos)[i]);
ut_free_2d_int (&pts, *pcooqty);
return;
}
void
neut_tesr_cell_boundpoints (struct TESR Tesr, int cell, int ***ppts,
int *pptqty, int connec, char* interior)
{
int i, j, k;
if (!Tesr.CellBBox)
ut_print_neperbug ();
(*pptqty) = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
if (neut_tesr_cell_boundpoints_test
(Tesr, cell, i, j, k, connec, interior))
{
(*pptqty)++;
(*ppts) = ut_realloc_2d_int_addline (*ppts, *pptqty, 3);
ut_array_1d_int_set_3 ((*ppts)[(*pptqty) - 1], i, j, k);
}
return;
}
void
neut_tesr_cell_boundcoos (struct TESR Tesr, int cell, double ***pcoos,
int *pcooqty, int connec, char* interior)
{
int i, **pts = NULL;
neut_tesr_cell_boundpoints (Tesr, cell, &pts, pcooqty, connec, interior);
(*pcoos) = ut_alloc_2d (*pcooqty, 3);
for (i = 0; i < *pcooqty; i++)
neut_tesr_pos_coo (Tesr, pts[i], (*pcoos)[i]);
ut_free_2d_int (&pts, *pcooqty);
return;
}
void
neut_tesr_cell_cornerpoints (struct TESR Tesr, int cell, int ***ppts,
int *pptqty)
{
int i, j, k;
if (!Tesr.CellBBox)
ut_print_neperbug ();
(*pptqty) = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
if (Tesr.VoxCell[i][j][k] == cell)
{
// neighbors along x
if (Tesr.VoxCell[i - 1][j][k] == cell
&& Tesr.VoxCell[i + 1][j][k] == cell)
continue;
// neighbors along y
if (Tesr.VoxCell[i][j - 1][k] == cell
&& Tesr.VoxCell[i][j + 1][k] == cell)
continue;
// neighbors along z
if (Tesr.VoxCell[i][j][k - 1] == cell
&& Tesr.VoxCell[i][j][k + 1] == cell)
continue;
// neighbors along x y
if (Tesr.VoxCell[i - 1][j - 1][k] == cell
&& Tesr.VoxCell[i + 1][j + 1][k] == cell)
continue;
// neighbors along x -y
if (Tesr.VoxCell[i - 1][j + 1][k] == cell
&& Tesr.VoxCell[i + 1][j - 1][k] == cell)
continue;
// neighbors along y z
if (Tesr.VoxCell[i][j - 1][k - 1] == cell
&& Tesr.VoxCell[i][j + 1][k + 1] == cell)
continue;
// neighbors along y -z
if (Tesr.VoxCell[i][j - 1][k + 1] == cell
&& Tesr.VoxCell[i][j + 1][k - 1] == cell)
continue;
// neighbors along z x
if (Tesr.VoxCell[i - 1][j][k - 1] == cell
&& Tesr.VoxCell[i + 1][j][k + 1] == cell)
continue;
// neighbors along z -x
if (Tesr.VoxCell[i + 1][j][k - 1] == cell
&& Tesr.VoxCell[i - 1][j][k + 1] == cell)
continue;
(*pptqty)++;
(*ppts) = ut_realloc_2d_int_addline (*ppts, *pptqty, 3);
ut_array_1d_int_set_3 ((*ppts)[(*pptqty) - 1], i, j, k);
}
return;
}
void
neut_tesr_cell_convexity (struct TESR Tesr, int cell, double *pval)
{
int i, j, k, qty, **pts = NULL;
double voxvol, dist, vol, vol2, **coos = NULL;
struct NODES N;
struct MESH M;
int *pt = NULL;
double *coo = NULL;
double eps = 1e-4 * ut_array_1d_min (Tesr.vsize, Tesr.Dim);
double eps3 = 1e-2 * ut_array_1d_gmean (Tesr.vsize, Tesr.Dim);
srand48 (1);
pt = ut_alloc_1d_int (3);
coo = ut_alloc_1d (3);
neut_nodes_set_zero (&N);
neut_mesh_set_zero (&M);
neut_tesr_cell_cornerpoints (Tesr, cell, &pts, &qty);
coos = ut_alloc_2d (qty, 3);
for (i = 0; i < qty; i++)
{
neut_tesr_pos_coo (Tesr, pts[i], coos[i]);
for (j = 0; j < Tesr.Dim; j++)
coos[i][j] += eps * drand48 ();
}
net_pts_convexhull (coos, qty, 3, &N, &M);
vol = 0;
for (k = Tesr.CellBBox[cell][2][0]; k <= Tesr.CellBBox[cell][2][1]; k++)
for (j = Tesr.CellBBox[cell][1][0]; j <= Tesr.CellBBox[cell][1][1]; j++)
for (i = Tesr.CellBBox[cell][0][0]; i <= Tesr.CellBBox[cell][0][1]; i++)
{
if (Tesr.VoxCell[i][j][k] == cell)
vol++;
else
{
ut_array_1d_int_set_3 (pt, i, j, k);
neut_tesr_pos_coo (Tesr, pt, coo);
ut_space_polypts_point_dist (coos, qty, coo, &dist);
if (dist < eps3)
vol++;
}
}
neut_tesr_voxsize (Tesr, &voxvol);
vol *= voxvol;
neut_tesr_cell_volume (Tesr, cell, &vol2);
(*pval) = vol2 / vol;
if (*pval > 1 + 1e-9 || *pval < 0)
ut_print_neperbug ();
ut_free_2d_int (&pts, qty);
ut_free_2d (&coos, qty);
ut_free_1d (&coo);
ut_free_1d_int (&pt);
neut_nodes_free (&N);
neut_mesh_free (&M);
return;
}
void
neut_tesr_cell_aniso (struct TESR Tesr, int cell, double **evect,
double *eval)
{
int i, cooqty = 0;
double **coos = NULL;
double *centre = ut_alloc_1d (Tesr.Dim);
double **S = ut_alloc_2d (Tesr.Dim, Tesr.Dim);
neut_tesr_cell_centre (Tesr, cell, centre);
neut_tesr_cell_coos (Tesr, cell, &coos, &cooqty);
for (i = 0; i < cooqty; i++)
ut_array_1d_sub (coos[i], centre, Tesr.Dim, coos[i]);
ut_vector_set_covar (coos, NULL, cooqty, Tesr.Dim, S);
ut_mat_eigen (S, Tesr.Dim, eval, evect);
ut_free_1d (¢re);
ut_free_2d (&coos, cooqty);
ut_free_2d (&S, Tesr.Dim);
return;
}
void
neut_tesr_cell_anisoxyz (struct TESR Tesr, int cell, double *fact)
{
int i, j, cooqty = 0;
double **coos = NULL;
double *centre = ut_alloc_1d (Tesr.Dim);
double **S = ut_alloc_2d (Tesr.Dim, Tesr.Dim);
neut_tesr_cell_coos (Tesr, cell, &coos, &cooqty);
neut_tesr_cell_centre (Tesr, cell, centre);
for (i = 0; i < cooqty; i++)
ut_array_1d_sub (coos[i], centre, Tesr.Dim, coos[i]);
for (i = 0; i < Tesr.Dim; i++)
{
fact[i] = 0;
for (j = 0; j < cooqty; j++)
fact[i] += pow (coos[j][i], 2);
fact[i] = sqrt (fact[i]);
}
ut_array_1d_scale (fact, Tesr.Dim,
1. / pow (ut_array_1d_prod (fact, Tesr.Dim),
1. / Tesr.Dim));
ut_free_1d (¢re);
ut_free_2d (&coos, cooqty);
ut_free_2d (&S, Tesr.Dim);
return;
}
void
neut_tesr_cells_anisoxyz (struct TESR Tesr, double *fact)
{
int i;
double vol;
double **facts = ut_alloc_2d (Tesr.CellQty + 1, Tesr.Dim);
double *vols = ut_alloc_1d (Tesr.CellQty + 1);
vol = 0;
ut_array_1d_zero (fact, 3);
for (i = 1; i <= Tesr.CellQty; i++)
{
neut_tesr_cell_anisoxyz (Tesr, i, facts[i]);
neut_tesr_cell_volume (Tesr, i, vols + i);
ut_array_1d_scale (facts[i], Tesr.Dim, vols[i]);
ut_array_1d_add (facts[i], fact, Tesr.Dim, fact);
vol += vols[i];
}
ut_array_1d_scale (fact, Tesr.Dim, 1. / vol);
ut_array_1d_scale (fact, Tesr.Dim,
1. / pow (ut_array_1d_prod (fact, Tesr.Dim),
1. / Tesr.Dim));
ut_free_2d (&facts, Tesr.CellQty);
ut_free_1d (&vols);
return;
}
int
neut_tesr_perpos_pos (struct TESR Tesr, int *per, int *pos, int *pos2)
{
int i;
ut_array_1d_int_memcpy (pos, Tesr.Dim, pos2);
for (i = 0; i < Tesr.Dim; i++)
if (pos[i] < 1 || pos[i] > Tesr.size[i])
if (!per || per[i])
{
while (pos2[i] < 1)
pos2[i] += Tesr.size[i];
while (pos2[i] > Tesr.size[i])
pos2[i] -= Tesr.size[i];
}
return 0;
}
void
neut_tesr_bbox (struct TESR Tesr, double **bbox)
{
int i;
ut_array_2d_set (bbox, 3, 1, 0);
for (i = 0; i < 3; i++)
{
bbox[i][0] = Tesr.Origin[i];
bbox[i][1] = Tesr.Origin[i] + Tesr.size[i] * Tesr.vsize[i];
}
return;
}
void
neut_tesr_bboxsize (struct TESR Tesr, double *bboxsize)
{
int i;
double **bbox = ut_alloc_2d (3, 2);
neut_tesr_bbox (Tesr, bbox);
for (i = 0; i < 3; i++)
bboxsize[i] = bbox[i][1] - bbox[i][0];
ut_free_2d (&bbox, 3);
return;
}
int
neut_tesr_diameq (struct TESR Tesr, double *pval)
{
neut_tesr_size (Tesr, pval);
if (Tesr.Dim == 3)
(*pval) = sqrt ((4 / M_PI) * (*pval));
else if (Tesr.Dim == 2)
(*pval) = pow ((6 / M_PI) * (*pval), 0.3333333333333333333333333);
return 0;
}
int
neut_tesr_radeq (struct TESR Tesr, double *pval)
{
neut_tesr_diameq (Tesr, pval);
(*pval) *= .5;
return 0;
}
int
neut_tesr_size (struct TESR Tesr, double *psize)
{
if (Tesr.Dim == 2)
neut_tesr_area (Tesr, psize);
else if (Tesr.Dim == 3)
neut_tesr_volume (Tesr, psize);
else
abort ();
return 0;
}
int
neut_tesr_rasterarea (struct TESR Tesr, double *parea)
{
if (Tesr.Dim == 2)
{
(*parea) = Tesr.vsize[0] * Tesr.size[0] * Tesr.vsize[1] * Tesr.size[1];
return 0;
}
else
{
(*parea) = 0;
return -1;
}
}
int
neut_tesr_rastersize (struct TESR Tesr, double *psize)
{
if (Tesr.Dim == 2)
neut_tesr_rasterarea (Tesr, psize);
else if (Tesr.Dim == 3)
neut_tesr_rastervolume (Tesr, psize);
else
abort ();
return 0;
}
int
neut_tesr_area (struct TESR Tesr, double *parea)
{
int i, j, qty;
if (Tesr.Dim == 2)
{
qty = 0;
for (j = 1; j <= Tesr.size[1]; j++)
for (i = 1; i <= Tesr.size[0]; i++)
if (!Tesr.CellQty || Tesr.VoxCell[i][j][1] != 0)
qty++;
(*parea) = ut_array_1d_prod (Tesr.vsize, 2) * qty;
return 0;
}
else
{
(*parea) = 0;
return -1;
}
}
int
neut_tesr_voxsize (struct TESR Tesr, double *pvol)
{
if (Tesr.Dim == 2)
return neut_tesr_voxarea (Tesr, pvol);
else if (Tesr.Dim == 3)
return neut_tesr_voxvolume (Tesr, pvol);
else
abort ();
return 0;
}
int
neut_tesr_voxarea (struct TESR Tesr, double *pvol)
{
(*pvol) = ut_array_1d_prod (Tesr.vsize, 2);
return 0;
}
int
neut_tesr_voxvolume (struct TESR Tesr, double *pvol)
{
(*pvol) = ut_array_1d_prod (Tesr.vsize, 3);
return 0;
}
int
neut_tesr_voxlengtheq (struct TESR Tesr, double *plengtheq)
{
(*plengtheq) = ut_array_1d_gmean (Tesr.vsize, Tesr.Dim);
return 0;
}
int
neut_tesr_volume (struct TESR Tesr, double *pvol)
{
if (Tesr.Dim == 3)
{
(*pvol) =
Tesr.vsize[0] * Tesr.size[0] * Tesr.vsize[1] * Tesr.size[1] *
Tesr.vsize[2] * Tesr.size[2];
return 0;
}
else
{
(*pvol) = 0;
return -1;
}
}
int
neut_tesr_rastervolume (struct TESR Tesr, double *pvol)
{
int i, j, k, qty;
if (Tesr.Dim == 3)
{
qty = 0;
for (k = 1; k <= Tesr.size[1]; k++)
for (j = 1; j <= Tesr.size[1]; j++)
for (i = 1; i <= Tesr.size[0]; i++)
if (Tesr.VoxCell[i][j][k] != 0)
qty++;
(*pvol) = ut_array_1d_prod (Tesr.vsize, 3) * qty;
return 0;
}
else
{
(*pvol) = 0;
return -1;
}
}
void
neut_tesr_group_volume (struct TESR Tesr, int group, double *pvol)
{
int i;
double tmp;
(*pvol) = 0;
for (i = 1; i <= Tesr.CellQty; i++)
if (Tesr.CellGroup && Tesr.CellGroup[i] == group)
{
neut_tesr_cell_volume (Tesr, i, &tmp);
(*pvol) += tmp;
}
return;
}
void
neut_tesr_group_volfrac (struct TESR Tesr, int group, double *pvolfrac)
{
double tesrvol, groupvol;
neut_tesr_volume (Tesr, &tesrvol);
neut_tesr_group_volume (Tesr, group, &groupvol);
(*pvolfrac) = groupvol / tesrvol;
return;
}
void
neut_tesr_group_area (struct TESR Tesr, int group, double *parea)
{
int i;
double tmp;
(*parea) = 0;
for (i = 1; i <= Tesr.CellQty; i++)
if (Tesr.CellGroup && Tesr.CellGroup[i] == group)
{
neut_tesr_cell_area (Tesr, i, &tmp);
(*parea) += tmp;
}
return;
}
void
neut_tesr_group_areafrac (struct TESR Tesr, int group, double *pareafrac)
{
double tesrarea, grouparea;
neut_tesr_area (Tesr, &tesrarea);
neut_tesr_group_area (Tesr, group, &grouparea);
(*pareafrac) = grouparea / tesrarea;
return;
}
void
neut_tesr_group_size (struct TESR Tesr, int group, double *psize)
{
(*psize) = 0;
if (Tesr.Dim == 2)
neut_tesr_group_area (Tesr, group, psize);
else if (Tesr.Dim == 3)
neut_tesr_group_volume (Tesr, group, psize);
return;
}
void
neut_tesr_group_sizefrac (struct TESR Tesr, int group, double *psizefrac)
{
(*psizefrac) = 0;
if (Tesr.Dim == 2)
neut_tesr_group_areafrac (Tesr, group, psizefrac);
else if (Tesr.Dim == 3)
neut_tesr_group_volfrac (Tesr, group, psizefrac);
return;
}
void
neut_tesr_cell_bbox_coo (struct TESR Tesr, int cell, double **bbox_coo)
{
int i, j;
int *pos = ut_alloc_1d_int (3);
double *coo = ut_alloc_1d (3);
for (j = 0; j < 2; j++)
{
ut_array_1d_int_set_3 (pos, Tesr.CellBBox[cell][0][j],
Tesr.CellBBox[cell][1][j],
Tesr.CellBBox[cell][2][j]);
neut_tesr_pos_coo (Tesr, pos, coo);
for (i = 0; i < 3; i++)
bbox_coo[i][j] = coo[i];
}
ut_free_1d (&coo);
ut_free_1d_int (&pos);
return;
}
| 0 | 0.755914 | 1 | 0.755914 | game-dev | MEDIA | 0.347496 | game-dev | 0.928088 | 1 | 0.928088 |
saiintbrisson/command-framework | 2,754 | bungee/src/main/java/me/saiintbrisson/bungee/command/command/BungeeContext.java | /*
* Copyright 2020 Luiz Carlos Mourão Paes de Carvalho
*
* 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 me.saiintbrisson.bungee.command.command;
import lombok.AllArgsConstructor;
import lombok.Getter;
import me.saiintbrisson.bungee.command.target.BungeeTargetValidator;
import me.saiintbrisson.minecraft.command.CommandFrame;
import me.saiintbrisson.minecraft.command.command.CommandHolder;
import me.saiintbrisson.minecraft.command.command.Context;
import me.saiintbrisson.minecraft.command.exception.CommandException;
import me.saiintbrisson.minecraft.command.message.MessageType;
import me.saiintbrisson.minecraft.command.target.CommandTarget;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.TextComponent;
/**
* @author Henry Fábio
* Github: https://github.com/HenryFabio
*/
@Getter
@AllArgsConstructor
public class BungeeContext implements Context<CommandSender> {
private final CommandSender sender;
private final CommandTarget target;
private final String[] args;
private final CommandFrame<?, ?, ?> commandFrame;
private final CommandHolder<?, ?> commandHolder;
@Override
public void sendMessage(String message) {
sender.sendMessage(new TextComponent(message));
}
@Override
public void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
}
@Override
public boolean testPermission(String permission, boolean silent) throws CommandException {
if (sender.hasPermission(permission)) {
return true;
}
if (!silent) {
throw new CommandException(MessageType.NO_PERMISSION, permission);
}
return false;
}
@Override
public boolean testTarget(CommandTarget target, boolean silent) throws CommandException {
if (BungeeTargetValidator.INSTANCE.validate(target, sender)) {
return true;
}
if (!silent) {
throw new CommandException(MessageType.INCORRECT_USAGE, target.name());
}
return false;
}
@Override
public String getLabel() {
throw new UnsupportedOperationException();
}
}
| 0 | 0.87149 | 1 | 0.87149 | game-dev | MEDIA | 0.85509 | game-dev | 0.735379 | 1 | 0.735379 |
Gaby-Station/Gaby-Station | 2,217 | Content.Server/Weapons/Misc/TetherGunSystem.cs | // SPDX-FileCopyrightText: 2023 Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.PowerCell;
using Content.Shared.Item.ItemToggle;
using Content.Shared.PowerCell;
using Content.Shared.Weapons.Misc;
using Robust.Shared.Physics.Components;
namespace Content.Server.Weapons.Misc;
public sealed class TetherGunSystem : SharedTetherGunSystem
{
[Dependency] private readonly PowerCellSystem _cell = default!;
[Dependency] private readonly ItemToggleSystem _toggle = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<TetherGunComponent, PowerCellSlotEmptyEvent>(OnGunEmpty);
SubscribeLocalEvent<ForceGunComponent, PowerCellSlotEmptyEvent>(OnGunEmpty);
}
private void OnGunEmpty(EntityUid uid, BaseForceGunComponent component, ref PowerCellSlotEmptyEvent args)
{
StopTether(uid, component);
}
protected override bool CanTether(EntityUid uid, BaseForceGunComponent component, EntityUid target, EntityUid? user)
{
if (!base.CanTether(uid, component, target, user))
return false;
if (!_cell.HasDrawCharge(uid, user: user))
return false;
return true;
}
protected override void StartTether(EntityUid gunUid, BaseForceGunComponent component, EntityUid target, EntityUid? user,
PhysicsComponent? targetPhysics = null, TransformComponent? targetXform = null)
{
base.StartTether(gunUid, component, target, user, targetPhysics, targetXform);
_toggle.TryActivate(gunUid);
}
protected override void StopTether(EntityUid gunUid, BaseForceGunComponent component, bool land = true, bool transfer = false)
{
base.StopTether(gunUid, component, land, transfer);
_toggle.TryDeactivate(gunUid);
}
} | 0 | 0.879333 | 1 | 0.879333 | game-dev | MEDIA | 0.990252 | game-dev | 0.893618 | 1 | 0.893618 |
exmex/HS_Multilang | 1,699 | Assets/NGUI/Scripts/Interaction/UIButtonRotation.cs | //----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2013 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example script of how a button can be rotated visibly when the mouse hovers over it or it gets pressed.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Rotation")]
public class UIButtonRotation : MonoBehaviour
{
public Transform tweenTarget;
public Vector3 hover = Vector3.zero;
public Vector3 pressed = Vector3.zero;
public float duration = 0.2f;
Quaternion mRot;
bool mStarted = false;
bool mHighlighted = false;
void Start ()
{
if (!mStarted)
{
mStarted = true;
if (tweenTarget == null) tweenTarget = transform;
mRot = tweenTarget.localRotation;
}
}
void OnEnable () { if (mStarted && mHighlighted) OnHover(UICamera.IsHighlighted(gameObject)); }
void OnDisable ()
{
if (mStarted && tweenTarget != null)
{
TweenRotation tc = tweenTarget.GetComponent<TweenRotation>();
if (tc != null)
{
tc.rotation = mRot;
tc.enabled = false;
}
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (!mStarted) Start();
TweenRotation.Begin(tweenTarget.gameObject, duration, isPressed ? mRot * Quaternion.Euler(pressed) :
(UICamera.IsHighlighted(gameObject) ? mRot * Quaternion.Euler(hover) : mRot)).method = UITweener.Method.EaseInOut;
}
}
void OnHover (bool isOver)
{
if (enabled)
{
if (!mStarted) Start();
TweenRotation.Begin(tweenTarget.gameObject, duration, isOver ? mRot * Quaternion.Euler(hover) : mRot).method = UITweener.Method.EaseInOut;
mHighlighted = isOver;
}
}
}
| 0 | 0.755491 | 1 | 0.755491 | game-dev | MEDIA | 0.942926 | game-dev | 0.626894 | 1 | 0.626894 |
OpenMITM/MuCuteClient | 4,310 | app/src/main/java/com/mucheng/mucute/client/game/module/motion/MotionFlyModule.kt | package com.mucheng.mucute.client.game.module.motion
import com.mucheng.mucute.client.game.InterceptablePacket
import com.mucheng.mucute.client.game.Module
import com.mucheng.mucute.client.game.ModuleCategory
import org.cloudburstmc.math.vector.Vector3f
import org.cloudburstmc.protocol.bedrock.data.Ability
import org.cloudburstmc.protocol.bedrock.data.AbilityLayer
import org.cloudburstmc.protocol.bedrock.data.PlayerAuthInputData
import org.cloudburstmc.protocol.bedrock.data.PlayerPermission
import org.cloudburstmc.protocol.bedrock.data.command.CommandPermission
import org.cloudburstmc.protocol.bedrock.packet.PlayerAuthInputPacket
import org.cloudburstmc.protocol.bedrock.packet.SetEntityMotionPacket
import org.cloudburstmc.protocol.bedrock.packet.UpdateAbilitiesPacket
class MotionFlyModule : Module("motion_fly", ModuleCategory.Motion) {
private val verticalSpeedUp = floatValue("verticalUpSpeed", 11.77f, 1.0f..20.0f)
private val verticalSpeedDown = floatValue("verticalDownSpeed", 16.55f, 1.0f..20.0f)
private val motionInterval = floatValue("delay", 472.17f, 100.0f..600.0f)
private var lastMotionTime = 0L
private var jitterState = false
private var canFly = false
private val flyAbilitiesPacket = UpdateAbilitiesPacket().apply {
playerPermission = PlayerPermission.OPERATOR
commandPermission = CommandPermission.OWNER
abilityLayers.add(AbilityLayer().apply {
layerType = AbilityLayer.Type.BASE
abilitiesSet.addAll(Ability.entries.toTypedArray())
abilityValues.addAll(arrayOf(
Ability.BUILD,
Ability.MINE,
Ability.DOORS_AND_SWITCHES,
Ability.OPEN_CONTAINERS,
Ability.ATTACK_PLAYERS,
Ability.ATTACK_MOBS,
Ability.MAY_FLY,
Ability.FLY_SPEED,
Ability.WALK_SPEED,
Ability.OPERATOR_COMMANDS
))
walkSpeed = 0.1f
flySpeed = 2.19f
})
}
private val resetAbilitiesPacket = UpdateAbilitiesPacket().apply {
playerPermission = PlayerPermission.OPERATOR
commandPermission = CommandPermission.OWNER
abilityLayers.add(AbilityLayer().apply {
layerType = AbilityLayer.Type.BASE
abilitiesSet.addAll(Ability.entries.toTypedArray())
abilityValues.addAll(arrayOf(
Ability.BUILD,
Ability.MINE,
Ability.DOORS_AND_SWITCHES,
Ability.OPEN_CONTAINERS,
Ability.ATTACK_PLAYERS,
Ability.ATTACK_MOBS,
Ability.OPERATOR_COMMANDS
))
walkSpeed = 0.1f
flySpeed = 0f
})
}
private fun handleFlyAbilities(isEnabled: Boolean) {
if (canFly != isEnabled) {
flyAbilitiesPacket.uniqueEntityId = session.localPlayer.uniqueEntityId
resetAbilitiesPacket.uniqueEntityId = session.localPlayer.uniqueEntityId
if (isEnabled) {
session.clientBound(flyAbilitiesPacket)
} else {
session.clientBound(resetAbilitiesPacket)
}
canFly = isEnabled
}
}
override fun beforePacketBound(interceptablePacket: InterceptablePacket) {
val packet = interceptablePacket.packet
if (packet is PlayerAuthInputPacket) {
handleFlyAbilities(isEnabled)
if (isEnabled && System.currentTimeMillis() - lastMotionTime >= motionInterval.value) {
val vertical = when {
packet.inputData.contains(PlayerAuthInputData.WANT_UP) -> verticalSpeedUp.value
packet.inputData.contains(PlayerAuthInputData.WANT_DOWN) -> -verticalSpeedDown.value
else -> 0f
}
val motionPacket = SetEntityMotionPacket().apply {
runtimeEntityId = session.localPlayer.runtimeEntityId
motion = Vector3f.from(0f, vertical + (if (jitterState) 0.1f else -0.1f), 0f)
}
session.clientBound(motionPacket)
jitterState = !jitterState
lastMotionTime = System.currentTimeMillis()
}
}
}
} | 0 | 0.745173 | 1 | 0.745173 | game-dev | MEDIA | 0.982329 | game-dev | 0.903251 | 1 | 0.903251 |
Monkestation/Monkestation2.0 | 2,331 | code/modules/mob/living/basic/vermin/mothroach.dm | /mob/living/basic/mothroach
name = "mothroach"
desc = "This is the adorable by-product of multiple attempts at genetically mixing mothpeople with cockroaches."
icon_state = "mothroach"
icon_living = "mothroach"
icon_dead = "mothroach_dead"
held_state = "mothroach"
held_lh = 'icons/mob/inhands/animal_item_lefthand.dmi'
held_rh = 'icons/mob/inhands/animal_item_righthand.dmi'
head_icon = 'icons/mob/clothing/head/pets_head.dmi'
butcher_results = list(/obj/item/food/meat/slab/mothroach = 3, /obj/item/stack/sheet/animalhide/mothroach = 1)
mob_biotypes = MOB_ORGANIC|MOB_BUG
mob_size = MOB_SIZE_SMALL
mobility_flags = MOBILITY_FLAGS_REST_CAPABLE_DEFAULT
health = 25
maxHealth = 25
speed = 1.25
gold_core_spawnable = FRIENDLY_SPAWN
can_be_held = TRUE
worn_slot_flags = ITEM_SLOT_HEAD
verb_say = "flutters"
verb_ask = "flutters inquisitively"
verb_exclaim = "flutters loudly"
verb_yell = "flutters loudly"
response_disarm_continuous = "shoos"
response_disarm_simple = "shoo"
response_harm_continuous = "hits"
response_harm_simple = "hit"
response_help_continuous = "pats"
response_help_simple = "pat"
faction = list(FACTION_NEUTRAL)
ai_controller = /datum/ai_controller/basic_controller/mothroach
/mob/living/basic/mothroach/Initialize(mapload)
. = ..()
AddElement(/datum/element/pet_bonus, "squeaks happily!")
add_verb(src, /mob/living/proc/toggle_resting)
ADD_TRAIT(src, TRAIT_VENTCRAWLER_ALWAYS, INNATE_TRAIT)
/mob/living/basic/mothroach/toggle_resting()
. = ..()
if(stat == DEAD)
return
if (resting)
icon_state = "[icon_living]_rest"
else
icon_state = "[icon_living]"
regenerate_icons()
/mob/living/basic/mothroach/attack_hand(mob/living/carbon/human/user, list/modifiers)
. = ..()
if(src.stat == DEAD)
return
else
playsound(loc, 'sound/voice/moth/scream_moth.ogg', 50, TRUE)
/mob/living/basic/mothroach/attackby(obj/item/attacking_item, mob/living/user, params)
. = ..()
if(src.stat == DEAD)
return
else
playsound(loc, 'sound/voice/moth/scream_moth.ogg', 50, TRUE)
/datum/ai_controller/basic_controller/mothroach
blackboard = list()
ai_traits = STOP_MOVING_WHEN_PULLED
ai_movement = /datum/ai_movement/basic_avoidance
idle_behavior = /datum/idle_behavior/idle_random_walk
planning_subtrees = list(
/datum/ai_planning_subtree/random_speech/mothroach,
)
| 0 | 0.858756 | 1 | 0.858756 | game-dev | MEDIA | 0.98626 | game-dev | 0.885186 | 1 | 0.885186 |
BLACKujira/SekaiTools | 9,427 | SekaiTools/Assets/Scripts/Count/NicknameCountData.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace SekaiTools.Count
{
public class NicknameCountData : ISaveData
{
public const string unitStoriesFolder = "UnitStories";
public const string eventStoriesFolder = "EventStories";
public const string cardStoriesFolder = "CardStories";
public const string mapTalkFolder = "MapTalk";
public const string liveTalkFolder = "LiveTalk";
public const string otherStoriesFolder = "OtherStories";
public List<NicknameCountMatrix_Scenario> countMatrix_Unit = new List<NicknameCountMatrix_Scenario>();
public List<NicknameCountMatrix_Scenario> countMatrix_Event = new List<NicknameCountMatrix_Scenario>();
public List<NicknameCountMatrix_Scenario> countMatrix_Card = new List<NicknameCountMatrix_Scenario>();
public List<NicknameCountMatrix_Scenario> countMatrix_Map = new List<NicknameCountMatrix_Scenario>();
public List<NicknameCountMatrix_Ceremony> countMatrix_Live = new List<NicknameCountMatrix_Ceremony>();
public List<NicknameCountMatrix_Scenario> countMatrix_Other = new List<NicknameCountMatrix_Scenario>();
public NicknameCountMatrix[] NicknameCountMatrices
{
get
{
List<NicknameCountMatrix> nicknameCountMatrices = new List<NicknameCountMatrix>();
nicknameCountMatrices.AddRange(countMatrix_Unit);
nicknameCountMatrices.AddRange(countMatrix_Event);
nicknameCountMatrices.AddRange(countMatrix_Card);
nicknameCountMatrices.AddRange(countMatrix_Map);
nicknameCountMatrices.AddRange(countMatrix_Live);
nicknameCountMatrices.AddRange(countMatrix_Other);
return nicknameCountMatrices.ToArray();
}
}
public NicknameCountMatrix[] SortedNicknameCountMatrices => NicknameCountMatrix.Sort(NicknameCountMatrices);
public int ChangedFileCount => NicknameCountMatrices.Where(ncm => ncm.ifChanged).Count();
public void AddCountMatrix(StoryType storyType, NicknameCountMatrix nicknameCountMatrix)
{
switch (storyType)
{
case StoryType.UnitStory:
countMatrix_Unit.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.EventStory:
countMatrix_Event.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.CardStory:
countMatrix_Card.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.MapTalk:
countMatrix_Map.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.LiveTalk:
countMatrix_Live.Add((NicknameCountMatrix_Ceremony)nicknameCountMatrix);
break;
case StoryType.OtherStory:
countMatrix_Other.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.SystemVoice:
break;
default:
break;
}
}
public string SavePath { get; set; }
public NicknameCountItem this[int talkerId, int nameId]
{
get => new NicknameCountItem(NicknameCountMatrices, talkerId, nameId);
}
public int GetSerifCount(int talkerId)
{
int count = 0;
NicknameCountMatrix[] nicknameCountMatrices = this.NicknameCountMatrices;
foreach (var nicknameCountMatrix in nicknameCountMatrices)
{
count += nicknameCountMatrix.nicknameCountRows[talkerId].serifCount.Count;
}
return count;
}
public int GetCountTotal(int talkerId, bool excludeSelf)
{
int total = 0;
for (int i = 1; i < 27; i++)
{
if (excludeSelf && i == talkerId) continue;
NicknameCountItem nicknameCountItem = this[talkerId, i];
total += nicknameCountItem.Total;
}
return total;
}
public NicknameCountItemByEvent GetCountItemByEvent(int talkerId, int nameId)
{
return new NicknameCountItemByEvent(NicknameCountMatrices, talkerId, nameId);
}
public NicknameCountMatrixByEvent GetCountMatrixByEvent() => new NicknameCountMatrixByEvent(countMatrix_Event.ToArray());
public static NicknameCountData Load_Classic(string folder)
{
NicknameCountData nicknameCountData = new NicknameCountData();
nicknameCountData.SavePath = folder;
void Load<T>(List<T> targetList, string folderName) where T : NicknameCountMatrix
{
string path = Path.Combine(folder, folderName);
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
foreach (var file in files)
{
T t = JsonUtility.FromJson<T>(File.ReadAllText(file));
t.fileName = Path.GetFileNameWithoutExtension(file);
t.SavePath = file;
targetList.Add(t);
}
}
}
Load(nicknameCountData.countMatrix_Unit, unitStoriesFolder);
Load(nicknameCountData.countMatrix_Event, eventStoriesFolder);
Load(nicknameCountData.countMatrix_Card, cardStoriesFolder);
Load(nicknameCountData.countMatrix_Map, mapTalkFolder);
Load(nicknameCountData.countMatrix_Live, liveTalkFolder);
Load(nicknameCountData.countMatrix_Other, otherStoriesFolder);
return nicknameCountData;
}
public static NicknameCountData Load(string folder)
{
NicknameCountData nicknameCountData = new NicknameCountData();
string[] files = ExtensionTools.GetAllFiles(folder);
foreach (var file in files)
{
string extension = Path.GetExtension(file).ToLower();
NicknameCountMatrix nicknameCountMatrix = null;
switch (extension)
{
case ".ncmsce":
nicknameCountMatrix = LoadMatrix<NicknameCountMatrix_Scenario>(file);
break;
case ".ncmcer":
nicknameCountMatrix = LoadMatrix<NicknameCountMatrix_Ceremony>(file);
break;
default:
break;
}
if (nicknameCountMatrix != null) nicknameCountData.Add(nicknameCountMatrix);
}
nicknameCountData.SavePath = folder;
return nicknameCountData;
}
static T LoadMatrix<T>(string file) where T : NicknameCountMatrix
{
T t = JsonUtility.FromJson<T>(File.ReadAllText(file));
t.fileName = Path.GetFileNameWithoutExtension(file);
t.SavePath = file;
return t;
}
public void Add(NicknameCountMatrix nicknameCountMatrix)
{
switch (nicknameCountMatrix.storyType)
{
case StoryType.UnitStory:
countMatrix_Unit.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.EventStory:
countMatrix_Event.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.CardStory:
countMatrix_Card.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.MapTalk:
countMatrix_Map.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
case StoryType.LiveTalk:
countMatrix_Live.Add((NicknameCountMatrix_Ceremony)nicknameCountMatrix);
break;
case StoryType.OtherStory:
countMatrix_Other.Add((NicknameCountMatrix_Scenario)nicknameCountMatrix);
break;
default:
break;
}
}
public int SaveChangedFiles()
{
int changedFileCount = 0;
foreach (var nicknameCountMatrix in NicknameCountMatrices)
{
if (nicknameCountMatrix.ifChanged)
{
nicknameCountMatrix.SaveData();
nicknameCountMatrix.ifChanged = false;
changedFileCount++;
Debug.Log(nicknameCountMatrix.fileName);
}
}
return changedFileCount;
}
public void SaveData()
{
//HACK 全部保存
SaveChangedFiles();
}
public NicknameCountMatrix[] GetMatricesBefore(DateTime untilDateTime)
{
return NicknameCountMatrices.Where(mat=>mat.PublishedAt<untilDateTime).ToArray();
}
}
} | 0 | 0.66723 | 1 | 0.66723 | game-dev | MEDIA | 0.518122 | game-dev | 0.526623 | 1 | 0.526623 |
Fluorohydride/ygopro-scripts | 3,233 | c63092423.lua | --弾帯城壁龍
function c63092423.initial_effect(c)
c:EnableCounterPermit(0x44)
c:EnableReviveLimit()
--connot special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(63092423,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_COUNTER)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_HAND)
e2:SetCondition(c63092423.spcon)
e2:SetTarget(c63092423.sptg)
e2:SetOperation(c63092423.spop)
c:RegisterEffect(e2)
--cannot link summon
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(1,1)
e3:SetTarget(c63092423.splimit)
c:RegisterEffect(e3)
--cannot attack
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_CANNOT_ATTACK)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e4:SetTarget(c63092423.atktg)
c:RegisterEffect(e4)
--counter
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(63092423,1))
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_SPSUMMON_SUCCESS)
e5:SetRange(LOCATION_MZONE)
e5:SetCondition(c63092423.ctcon1)
e5:SetOperation(c63092423.ctop1)
c:RegisterEffect(e5)
--counter
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(63092423,2))
e6:SetCategory(CATEGORY_COUNTER)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e6:SetCode(EVENT_PHASE+PHASE_STANDBY)
e6:SetCountLimit(1)
e6:SetRange(LOCATION_MZONE)
e6:SetOperation(c63092423.ctop2)
c:RegisterEffect(e6)
end
function c63092423.cfilter(c,tp)
return c:IsFaceup() and c:IsSummonPlayer(tp) and c:IsSummonType(SUMMON_TYPE_LINK)
end
function c63092423.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c63092423.cfilter,1,nil,tp)
end
function c63092423.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false)
and Duel.IsCanAddCounter(tp,0x44,1,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c63092423.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)~=0 then
c:AddCounter(0x44,2)
c:CompleteProcedure()
end
end
function c63092423.splimit(e,c,tp,sumtp,sumpos)
return c:GetLink()>e:GetHandler():GetCounter(0x44) and bit.band(sumtp,SUMMON_TYPE_LINK)==SUMMON_TYPE_LINK
end
function c63092423.atktg(e,c)
return not c:IsType(TYPE_LINK)
end
function c63092423.ctcon1(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(Card.IsSummonType,1,nil,SUMMON_TYPE_LINK)
end
function c63092423.ctop1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
c:RemoveCounter(tp,0x44,2,REASON_EFFECT)
end
end
function c63092423.ctop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
c:AddCounter(0x44,1)
end
end
| 0 | 0.84263 | 1 | 0.84263 | game-dev | MEDIA | 0.938074 | game-dev | 0.932093 | 1 | 0.932093 |
TylerTemp/SaintsField | 3,549 | Editor/DOTweenDetectPanel/DOTweenHelperPanel.cs | #if DOTWEEN && !SAINTSFIELD_DOTWEEN_DISABLED
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace SaintsField.Editor.DOTweenDetectPanel
{
// ReSharper disable once InconsistentNaming
public class DOTweenHelperPanel: EditorWindow
{
private static DOTweenHelperPanel _doTweenHelperPanel;
[InitializeOnLoadMethod]
// [MenuItem("Window/Saints/Help Panel")]
public static void ShowHelpPanel()
{
if (DoTweenAllGood())
{
return;
}
// Debug.Log("Popup?");
if(_doTweenHelperPanel == null)
{
_doTweenHelperPanel = GetWindow<DOTweenHelperPanel>(title: "SaintsField DOTween Helper");
}
_doTweenHelperPanel.Show();
}
private static bool DoTweenAllGood()
{
ScriptableObject doTweenSettings = Resources.Load<ScriptableObject>("DOTweenSettings");
if (doTweenSettings is null) // bypass life circle check
{
return true;
}
// Debug.Log(doTweenSettings);
Type doTweenSettingsType = doTweenSettings.GetType();
FieldInfo fieldInfo = doTweenSettingsType.GetField("createASMDEF", BindingFlags.Instance | BindingFlags.Public);
bool createAsmdef = (bool) fieldInfo.GetValue(doTweenSettings);
// Debug.Log(createAsmdef);
return createAsmdef;
}
private void OnGUI()
{
if (DoTweenAllGood())
{
Close();
}
EditorGUILayout.HelpBox("DOTween ASMDEF not created, please create it or disable SaintsField's DOTween ability", MessageType.Error);
if (GUILayout.Button("Open DOTween Panel"))
{
EditorApplication.ExecuteMenuItem("Tools/Demigiant/DOTween Utility Panel");
}
if (GUILayout.Button("Disable SaintsField's DOTween utility"))
{
AddCompileDefine("SAINTSFIELD_DOTWEEN_DISABLED");
Close();
}
}
private void OnDestroy()
{
_doTweenHelperPanel = null;
}
private static void AddCompileDefine(string newDefineCompileConstant, IEnumerable<BuildTargetGroup> targetGroups = null)
{
IEnumerable<BuildTargetGroup> targets = targetGroups ?? Enum.GetValues(typeof(BuildTargetGroup)).Cast<BuildTargetGroup>();
foreach (BuildTargetGroup grp in targets.Where(each => each != BuildTargetGroup.Unknown))
{
string defines;
try
{
defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(grp);
}
catch (ArgumentException)
{
continue;
}
if (!defines.Contains(newDefineCompileConstant))
{
if (defines.Length > 0)
defines += ";";
defines += newDefineCompileConstant;
try
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(grp, defines);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}
}
}
}
#endif
| 0 | 0.869132 | 1 | 0.869132 | game-dev | MEDIA | 0.231525 | game-dev | 0.829191 | 1 | 0.829191 |
FakeFishGames/Barotrauma | 58,483 | Barotrauma/BarotraumaShared/SharedSource/Serialization/SerializableProperty/SerializableProperty.cs | using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
using RestSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
namespace Barotrauma
{
/// <summary>
/// Is the value of the property saved when saving (serializing) the entity?
/// Can be set to false if e.g. the value doesn't ever change from the prefab value, or if changes to it shouldn't persist between rounds.
/// </summary>
public enum IsPropertySaveable
{
Yes,
No
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class Serialize : Attribute
{
public readonly object DefaultValue;
public readonly IsPropertySaveable IsSaveable;
public readonly Identifier TranslationTextTag;
/// <summary>
/// If set to true, the instance values saved in a submarine file will always override the prefab values, even if using a mod that normally overrides instance values.
/// </summary>
public bool AlwaysUseInstanceValues;
public string Description;
/// <summary>
/// Makes the property serializable to/from XML
/// </summary>
/// <param name="defaultValue">The property is set to this value during deserialization if the value is not defined in XML.</param>
/// <param name="isSaveable">Is the value saved to XML when serializing.</param>
/// <param name="translationTextTag">If set to anything else than null, SerializableEntityEditors will show what the text gets translated to or warn if the text is not found in the language files.
/// <param name="alwaysUseInstanceValues">If set to true, the instance values saved in a submarine file will always override the prefab values, even if using a mod that normally overrides instance values.
/// Setting the value to a non-empty string will let the user select the text from one whose tag starts with the given string (e.g. RoomName. would show all texts with a RoomName.* tag)</param>
public Serialize(object defaultValue, IsPropertySaveable isSaveable, string description = "", string translationTextTag = "", bool alwaysUseInstanceValues = false)
{
DefaultValue = defaultValue;
IsSaveable = isSaveable;
TranslationTextTag = translationTextTag.ToIdentifier();
Description = description;
AlwaysUseInstanceValues = alwaysUseInstanceValues;
}
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class Header : Attribute
{
public readonly LocalizedString Text;
public Header(string text = "", string localizedTextTag = null)
{
Text = localizedTextTag != null ? TextManager.Get(localizedTextTag) : text;
}
}
public sealed class SerializableProperty
{
private static readonly ImmutableDictionary<Type, string> supportedTypes = new Dictionary<Type, string>
{
{ typeof(bool), "bool" },
{ typeof(int), "int" },
{ typeof(float), "float" },
{ typeof(string), "string" },
{ typeof(Identifier), "identifier" },
{ typeof(LanguageIdentifier), "languageidentifier" },
{ typeof(LocalizedString), "localizedstring" },
{ typeof(Point), "point" },
{ typeof(Vector2), "vector2" },
{ typeof(Vector3), "vector3" },
{ typeof(Vector4), "vector4" },
{ typeof(Rectangle), "rectangle" },
{ typeof(Color), "color" },
{ typeof(string[]), "stringarray" },
{ typeof(Identifier[]), "identifierarray" }
}.ToImmutableDictionary();
private static readonly Dictionary<Type, Dictionary<Identifier, SerializableProperty>> cachedProperties =
new Dictionary<Type, Dictionary<Identifier, SerializableProperty>>();
public readonly string Name;
public readonly AttributeCollection Attributes;
public readonly Type PropertyType;
public readonly bool OverridePrefabValues;
public readonly PropertyInfo PropertyInfo;
public SerializableProperty(PropertyDescriptor property)
{
Name = property.Name;
PropertyInfo = property.ComponentType.GetProperty(property.Name);
PropertyType = property.PropertyType;
Attributes = property.Attributes;
OverridePrefabValues = GetAttribute<Serialize>()?.AlwaysUseInstanceValues ?? false;
}
public T GetAttribute<T>() where T : Attribute
{
foreach (Attribute a in Attributes)
{
if (a is T) return (T)a;
}
return default;
}
public void SetValue(object parentObject, object val)
{
PropertyInfo.SetValue(parentObject, val);
}
public bool TrySetValue(object parentObject, string value)
{
if (value == null) { return false; }
if (!supportedTypes.TryGetValue(PropertyType, out string typeName))
{
if (PropertyType.IsEnum)
{
object enumVal;
try
{
enumVal = Enum.Parse(PropertyInfo.PropertyType, value, true);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value} (not a valid {PropertyInfo.PropertyType})", e);
return false;
}
try
{
PropertyInfo.SetValue(parentObject, enumVal);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value}", e);
return false;
}
}
else
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value} (Type \"{PropertyType.Name}\" not supported)");
return false;
}
}
try
{
switch (typeName)
{
case "bool":
bool boolValue = value.ToIdentifier() == "true";
if (TrySetBoolValueWithoutReflection(parentObject, boolValue)) { return true; }
PropertyInfo.SetValue(parentObject, boolValue, null);
break;
case "int":
if (int.TryParse(value, out int intVal))
{
if (TrySetFloatValueWithoutReflection(parentObject, intVal)) { return true; }
PropertyInfo.SetValue(parentObject, intVal, null);
}
else
{
return false;
}
break;
case "float":
if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float floatVal))
{
if (TrySetFloatValueWithoutReflection(parentObject, floatVal)) { return true; }
PropertyInfo.SetValue(parentObject, floatVal, null);
}
else
{
return false;
}
break;
case "string":
PropertyInfo.SetValue(parentObject, value, null);
break;
case "point":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParsePoint(value));
break;
case "vector2":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector2(value));
break;
case "vector3":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector3(value));
break;
case "vector4":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector4(value));
break;
case "color":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseColor(value));
break;
case "rectangle":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseRect(value, true));
break;
case "identifier":
PropertyInfo.SetValue(parentObject, value.ToIdentifier());
break;
case "languageidentifier":
PropertyInfo.SetValue(parentObject, value.ToLanguageIdentifier());
break;
case "localizedstring":
PropertyInfo.SetValue(parentObject, new RawLString(value));
break;
case "stringarray":
PropertyInfo.SetValue(parentObject, ParseStringArray(value));
break;
case "identifierarray":
PropertyInfo.SetValue(parentObject, ParseIdentifierArray(value));
break;
}
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value}", e);
return false;
}
return true;
}
private static string[] ParseStringArray(string stringArrayValues)
{
return string.IsNullOrEmpty(stringArrayValues) ? Array.Empty<string>() : stringArrayValues.Split(';');
}
private static Identifier[] ParseIdentifierArray(string stringArrayValues)
{
return ParseStringArray(stringArrayValues).ToIdentifiers();
}
public bool TrySetValue(object parentObject, object value)
{
if (value == null || parentObject == null || PropertyInfo == null) return false;
try
{
if (!supportedTypes.TryGetValue(PropertyType, out string typeName))
{
if (PropertyType.IsEnum)
{
object enumVal;
try
{
enumVal = Enum.Parse(PropertyInfo.PropertyType, value.ToString(), true);
}
catch (Exception e)
{
DebugConsole.ThrowError(
$"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value} (not a valid {PropertyInfo.PropertyType})", e);
return false;
}
PropertyInfo.SetValue(parentObject, enumVal);
return true;
}
else
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value} (Type \"{PropertyType.Name}\" not supported)");
return false;
}
}
try
{
if (value.GetType() == typeof(string))
{
switch (typeName)
{
case "string":
PropertyInfo.SetValue(parentObject, value, null);
return true;
case "point":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParsePoint((string)value));
return true;
case "vector2":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector2((string)value));
return true;
case "vector3":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector3((string)value));
return true;
case "vector4":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseVector4((string)value));
return true;
case "color":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseColor((string)value));
return true;
case "rectangle":
PropertyInfo.SetValue(parentObject, XMLExtensions.ParseRect((string)value, false));
return true;
case "identifier":
PropertyInfo.SetValue(parentObject, new Identifier((string)value));
return true;
case "languageidentifier":
PropertyInfo.SetValue(parentObject, ((string)value).ToLanguageIdentifier());
return true;
case "localizedstring":
PropertyInfo.SetValue(parentObject, new RawLString((string)value));
return true;
case "stringarray":
PropertyInfo.SetValue(parentObject, ParseStringArray((string)value));
return true;
case "identifierarray":
PropertyInfo.SetValue(parentObject, ParseIdentifierArray((string)value));
return true;
default:
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value}");
DebugConsole.ThrowError($"(Cannot convert a string to a {PropertyType})");
return false;
}
}
else if (PropertyType != value.GetType())
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value}");
DebugConsole.ThrowError("(Non-matching type, should be " + PropertyType + " instead of " + value.GetType() + ")");
return false;
}
PropertyInfo.SetValue(parentObject, value, null);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to set the value of the property \"{Name}\" of \"{parentObject}\" to {value}", e);
return false;
}
return true;
}
catch (Exception e)
{
DebugConsole.ThrowError($"Error in SerializableProperty.TrySetValue (Property: {PropertyInfo.Name})", e);
return false;
}
}
public bool TrySetValue(object parentObject, float value)
{
try
{
if (TrySetFloatValueWithoutReflection(parentObject, value)) { return true; }
PropertyInfo.SetValue(parentObject, value, null);
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.TrySetValue", e.InnerException);
return false;
}
catch (Exception e)
{
DebugConsole.ThrowError($"Error in SerializableProperty.TrySetValue (Property: {PropertyInfo.Name})", e);
return false;
}
return true;
}
public bool TrySetValue(object parentObject, bool value)
{
try
{
if (TrySetBoolValueWithoutReflection(parentObject, value)) { return true; }
PropertyInfo.SetValue(parentObject, value, null);
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.TrySetValue", e.InnerException);
return false;
}
catch (Exception e)
{
DebugConsole.ThrowError($"Error in SerializableProperty.TrySetValue (Property: {PropertyInfo.Name})", e);
return false;
}
return true;
}
public bool TrySetValue(object parentObject, int value)
{
try
{
if (TrySetFloatValueWithoutReflection(parentObject, value)) { return true; }
PropertyInfo.SetValue(parentObject, value, null);
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.TrySetValue", e.InnerException);
return false;
}
catch (Exception e)
{
DebugConsole.ThrowError($"Error in SerializableProperty.TrySetValue (Property: {PropertyInfo.Name})", e);
return false;
}
return true;
}
public object GetValue(object parentObject)
{
if (parentObject == null || PropertyInfo == null) { return false; }
var value = TryGetValueWithoutReflection(parentObject);
if (value != null) { return value; }
try
{
return PropertyInfo.GetValue(parentObject, null);
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.GetValue", e.InnerException);
return false;
}
catch (Exception e)
{
DebugConsole.ThrowError("Error in SerializableProperty.GetValue", e);
return false;
}
}
public float GetFloatValue(object parentObject)
{
if (parentObject == null || PropertyInfo == null) { return 0.0f; }
if (TryGetFloatValueWithoutReflection(parentObject, out float value))
{
return value;
}
try
{
if (PropertyType == typeof(int))
{
return (int)PropertyInfo.GetValue(parentObject, null);
}
else
{
return (float)PropertyInfo.GetValue(parentObject, null);
}
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.GetValue", e.InnerException);
return 0.0f;
}
catch (Exception e)
{
DebugConsole.ThrowError("Error in SerializableProperty.GetValue", e);
return 0.0f;
}
}
public bool GetBoolValue(object parentObject)
{
if (parentObject == null || PropertyInfo == null) { return false; }
if (TryGetBoolValueWithoutReflection(parentObject, out bool value))
{
return value;
}
try
{
return (bool)PropertyInfo.GetValue(parentObject, null);
}
catch (TargetInvocationException e)
{
DebugConsole.ThrowError("Exception thrown by the target of SerializableProperty.GetValue", e.InnerException);
return false;
}
catch (Exception e)
{
DebugConsole.ThrowError("Error in SerializableProperty.GetValue", e);
return false;
}
}
public static string GetSupportedTypeName(Type type)
{
if (type.IsEnum) { return "Enum"; }
if (!supportedTypes.TryGetValue(type, out string typeName))
{
return null;
}
return typeName;
}
private readonly ImmutableDictionary<Identifier, Func<object, object>> valueGetters =
new Dictionary<Identifier, Func<object, object>>()
{
{"Voltage".ToIdentifier(), (obj) => obj is Powered p ? p.Voltage : (object) null},
{"Charge".ToIdentifier(), (obj) => obj is PowerContainer p ? p.Charge : (object) null},
{"Overload".ToIdentifier(), (obj) => obj is PowerTransfer p ? p.Overload : (object) null},
{"AvailableFuel".ToIdentifier(), (obj) => obj is Reactor r ? r.AvailableFuel : (object) null},
{"FissionRate".ToIdentifier(), (obj) => obj is Reactor r ? r.FissionRate : (object) null},
{"OxygenFlow".ToIdentifier(), (obj) => obj is Vent v ? v.OxygenFlow : (object) null},
{
"CurrFlow".ToIdentifier(),
(obj) => obj is Pump p ? (object) p.CurrFlow :
obj is OxygenGenerator o ? (object)o.CurrFlow :
null
},
{"CurrentVolume".ToIdentifier(), (obj) => obj is Engine e ? e.CurrentVolume : (object)null},
{"MotionDetected".ToIdentifier(), (obj) => obj is MotionSensor m ? m.MotionDetected : (object)null},
{"Oxygen".ToIdentifier(), (obj) => obj is Character c ? c.Oxygen : (object)null},
{"Health".ToIdentifier(), (obj) => obj is Character c ? c.Health : (object)null},
{"OxygenAvailable".ToIdentifier(), (obj) => obj is Character c ? c.OxygenAvailable : (object)null},
{"PressureProtection".ToIdentifier(), (obj) => obj is Character c ? c.PressureProtection : (object)null},
{"IsDead".ToIdentifier(), (obj) => obj is Character c ? c.IsDead : (object)null},
{"IsHuman".ToIdentifier(), (obj) => obj is Character c ? c.IsHuman : (object)null},
{"IsOn".ToIdentifier(), (obj) => obj is LightComponent l ? l.IsOn : (object)null},
{"Condition".ToIdentifier(), (obj) => obj is Item i ? i.Condition : (object)null},
{"ContainerIdentifier".ToIdentifier(), (obj) => obj is Item i ? i.ContainerIdentifier : (object)null},
{"PhysicsBodyActive".ToIdentifier(), (obj) => obj is Item i ? i.PhysicsBodyActive : (object)null},
}.ToImmutableDictionary();
/// <summary>
/// Try getting the values of some commonly used properties directly without reflection
/// </summary>
private object TryGetValueWithoutReflection(object parentObject)
{
if (PropertyType == typeof(float))
{
if (TryGetFloatValueWithoutReflection(parentObject, out float value)) { return value; }
}
else if (PropertyType == typeof(bool))
{
if (TryGetBoolValueWithoutReflection(parentObject, out bool value)) { return value; }
}
else if (PropertyType == typeof(string))
{
if (TryGetStringValueWithoutReflection(parentObject, out string value)) { return value; }
}
return null;
}
/// <summary>
/// Try getting the values of some commonly used properties directly without reflection
/// </summary>
private bool TryGetFloatValueWithoutReflection(object parentObject, out float value)
{
value = 0.0f;
switch (Name)
{
case nameof(Powered.Voltage):
{
if (parentObject is Powered powered) { value = powered.Voltage; return true; }
}
break;
case nameof(Powered.RelativeVoltage):
{
if (parentObject is Powered powered) { value = powered.RelativeVoltage; return true; }
}
break;
case nameof(Powered.CurrPowerConsumption):
{
if (parentObject is Powered powered) { value = powered.CurrPowerConsumption; return true; }
}
break;
case nameof(PowerContainer.Charge):
{
if (parentObject is PowerContainer powerContainer) { value = powerContainer.Charge; return true; }
}
break;
case nameof(Repairable.StressDeteriorationMultiplier):
{
if (parentObject is Repairable repairable) { value = repairable.StressDeteriorationMultiplier; return true; }
}
break;
case nameof(PowerContainer.ChargePercentage):
{
if (parentObject is PowerContainer powerContainer) { value = powerContainer.ChargePercentage; return true; }
}
break;
case nameof(PowerContainer.RechargeRatio):
{
if (parentObject is PowerContainer powerContainer) { value = powerContainer.RechargeRatio; return true; }
}
break;
case nameof(ItemContainer.ContainedNonBrokenItemCount):
{
if (parentObject is ItemContainer itemContainer) { value = itemContainer.ContainedNonBrokenItemCount; return true; }
}
break;
case nameof(Reactor.AvailableFuel):
{ if (parentObject is Reactor reactor) { value = reactor.AvailableFuel; return true; } }
break;
case nameof(Reactor.FissionRate):
{ if (parentObject is Reactor reactor) { value = reactor.FissionRate; return true; } }
break;
case nameof(Reactor.Temperature):
{ if (parentObject is Reactor reactor) { value = reactor.Temperature; return true; } }
break;
case nameof(Vent.OxygenFlow):
if (parentObject is Vent vent) { value = vent.OxygenFlow; return true; }
break;
case nameof(Pump.CurrFlow):
{ if (parentObject is Pump pump) { value = pump.CurrFlow; return true; } }
if (parentObject is OxygenGenerator oxygenGenerator) { value = oxygenGenerator.CurrFlow; return true; }
break;
case nameof(Engine.CurrentBrokenVolume):
{ if (parentObject is Engine engine) { value = engine.CurrentBrokenVolume; return true; } }
{ if (parentObject is Pump pump) { value = pump.CurrentBrokenVolume; return true; } }
break;
case nameof(Engine.CurrentVolume):
{ if (parentObject is Engine engine) { value = engine.CurrentVolume; return true; } }
break;
case nameof(Character.Oxygen):
{ if (parentObject is Character character) { value = character.Oxygen; return true; } }
{ if (parentObject is Hull hull) { value = hull.Oxygen; return true; } }
break;
case nameof(Character.Health):
{ if (parentObject is Character character) { value = character.Health; return true; } }
break;
case nameof(Character.OxygenAvailable):
{ if (parentObject is Character character) { value = character.OxygenAvailable; return true; } }
break;
case nameof(Character.PressureProtection):
{ if (parentObject is Character character) { value = character.PressureProtection; return true; } }
break;
case nameof(Item.Condition):
{ if (parentObject is Item item) { value = item.Condition; return true; } }
break;
case nameof(Item.ConditionPercentage):
{ if (parentObject is Item item) { value = item.ConditionPercentage; return true; } }
break;
case nameof(Item.SightRange):
{ if (parentObject is Item item) { value = item.SightRange; return true; } }
break;
case nameof(Item.SoundRange):
{ if (parentObject is Item item) { value = item.SoundRange; return true; } }
break;
case nameof(Character.SpeedMultiplier):
{ if (parentObject is Character character) { value = character.SpeedMultiplier; return true; } }
break;
case nameof(Character.PropulsionSpeedMultiplier):
{ if (parentObject is Character character) { value = character.PropulsionSpeedMultiplier; return true; } }
break;
case nameof(Character.LowPassMultiplier):
{ if (parentObject is Character character) { value = character.LowPassMultiplier; return true; } }
break;
case nameof(Character.ObstructVisionAmount):
{ if (parentObject is Character character) { value = character.ObstructVisionAmount; return true; } }
break;
case nameof(Character.HullOxygenPercentage):
{
if (parentObject is Character character)
{
value = character.HullOxygenPercentage;
return true;
}
else if (parentObject is Item item)
{
value = item.HullOxygenPercentage;
return true;
}
}
break;
case nameof(Door.Stuck):
{ if (parentObject is Door door) { value = door.Stuck; return true; } }
break;
}
return false;
}
/// <summary>
/// Try getting the values of some commonly used properties directly without reflection
/// </summary>
private bool TryGetBoolValueWithoutReflection(object parentObject, out bool value)
{
value = false;
switch (Name)
{
case nameof(ItemComponent.IsActive):
if (parentObject is ItemComponent ic) { value = ic.IsActive; return true; }
break;
case nameof(PowerTransfer.Overload):
if (parentObject is PowerTransfer powerTransfer) { value = powerTransfer.Overload; return true; }
break;
case nameof(PowerContainer.OutputDisabled):
if (parentObject is PowerContainer powerContainer) { value = powerContainer.OutputDisabled; return true; }
break;
case nameof(MotionSensor.MotionDetected):
if (parentObject is MotionSensor motionSensor) { value = motionSensor.MotionDetected; return true; }
break;
case nameof(Character.IsDead):
{ if (parentObject is Character character) { value = character.IsDead; return true; } }
break;
case nameof(Character.NeedsAir):
{ if (parentObject is Character character) { value = character.NeedsAir; return true; } }
break;
case nameof(Character.NeedsOxygen):
{ if (parentObject is Character character) { value = character.NeedsOxygen; return true; } }
break;
case nameof(Character.IsHuman):
{ if (parentObject is Character character) { value = character.IsHuman; return true; } }
break;
case nameof(LightComponent.IsOn):
{ if (parentObject is LightComponent lightComponent) { value = lightComponent.IsOn; return true; } }
break;
case nameof(Item.PhysicsBodyActive):
{
if (parentObject is Item item) { value = item.PhysicsBodyActive; return true; }
}
break;
case nameof(DockingPort.Docked):
if (parentObject is DockingPort dockingPort) { value = dockingPort.Docked; return true; }
break;
case nameof(Reactor.TemperatureCritical):
if (parentObject is Reactor reactor) { value = reactor.TemperatureCritical; return true; }
break;
case nameof(TriggerComponent.TriggerActive):
if (parentObject is TriggerComponent trigger) { value = trigger.TriggerActive; return true; }
break;
case nameof(Controller.State):
if (parentObject is Controller controller) { value = controller.State; return true; }
break;
case nameof(Holdable.Attached):
if (parentObject is Holdable holdable) { value = holdable.Attached; return true; }
break;
case nameof(Character.InWater):
{
if (parentObject is Character character)
{
value = character.InWater;
return true;
}
else if (parentObject is Item item)
{
value = item.InWater;
return true;
}
}
break;
case nameof(Rope.Snapped):
if (parentObject is Rope rope) { value = rope.Snapped; return true; }
break;
}
return false;
}
/// <summary>
/// Try getting the values of some commonly used properties directly without reflection
/// </summary>
private bool TryGetStringValueWithoutReflection(object parentObject, out string value)
{
value = null;
switch (Name)
{
case nameof(Item.ContainerIdentifier):
{
if (parentObject is Item item) { value = item.ContainerIdentifier.Value; return true; }
}
break;
}
return false;
}
/// <summary>
/// Try setting the values of some commonly used properties directly without reflection
/// </summary>
private bool TrySetFloatValueWithoutReflection(object parentObject, float value)
{
switch (Name)
{
case nameof(Item.Condition):
{ if (parentObject is Item item) { item.Condition = value; return true; } }
break;
case nameof(Powered.Voltage):
if (parentObject is Powered powered) { powered.Voltage = value; return true; }
break;
case nameof(PowerContainer.Charge):
if (parentObject is PowerContainer powerContainer) { powerContainer.Charge = value; return true; }
break;
case nameof(Reactor.AvailableFuel):
if (parentObject is Reactor reactor) { reactor.AvailableFuel = value; return true; }
break;
case nameof(Character.Oxygen):
{ if (parentObject is Character character) { character.Oxygen = value; return true; } }
break;
case nameof(Character.OxygenAvailable):
{ if (parentObject is Character character) { character.OxygenAvailable = value; return true; } }
break;
case nameof(Character.PressureProtection):
{ if (parentObject is Character character) { character.PressureProtection = value; return true; } }
break;
case nameof(Character.LowPassMultiplier):
{ if (parentObject is Character character) { character.LowPassMultiplier = value; return true; } }
break;
case nameof(Character.SpeedMultiplier):
{ if (parentObject is Character character) { character.StackSpeedMultiplier(value); return true; } }
break;
case nameof(Character.HealthMultiplier):
{ if (parentObject is Character character) { character.StackHealthMultiplier(value); return true; } }
break;
case nameof(Character.PropulsionSpeedMultiplier):
{ if (parentObject is Character character) { character.PropulsionSpeedMultiplier = value; return true; } }
break;
case nameof(Character.ObstructVisionAmount):
{ if (parentObject is Character character) { character.ObstructVisionAmount = value; return true; } }
break;
case nameof(Item.Scale):
{ if (parentObject is Item item) { item.Scale = value; return true; } }
break;
case nameof(Item.SightRange):
{ if (parentObject is Item item) { item.SightRange = value; return true; } }
break;
case nameof(Item.SoundRange):
{ if (parentObject is Item item) { item.SoundRange = value; return true; } }
break;
}
return false;
}
/// <summary>
/// Try setting the values of some commonly used properties directly without reflection
/// </summary>
private bool TrySetBoolValueWithoutReflection(object parentObject, bool value)
{
switch (Name)
{
case nameof(Character.ObstructVision):
{ if (parentObject is Character character) { character.ObstructVision = value; return true; } }
break;
case nameof(Character.HideFace):
{ if (parentObject is Character character) { character.HideFace = value; return true; } }
break;
case nameof(Character.UseHullOxygen):
{ if (parentObject is Character character) { character.UseHullOxygen = value; return true; } }
break;
case nameof(LightComponent.IsOn):
{ if (parentObject is LightComponent lightComponent) { lightComponent.IsOn = value; return true; } }
break;
case nameof(ItemComponent.IsActive):
{ if (parentObject is ItemComponent ic) { ic.IsActive = value; return true; } }
break;
}
return false;
}
public static List<SerializableProperty> GetProperties<T>(ISerializableEntity obj)
{
List<SerializableProperty> editableProperties = new List<SerializableProperty>();
foreach (var property in obj.SerializableProperties.Values)
{
if (property.Attributes.OfType<T>().Any()) editableProperties.Add(property);
}
return editableProperties;
}
public static Dictionary<Identifier, SerializableProperty> GetProperties(object obj)
{
Type objType = obj.GetType();
if (cachedProperties.ContainsKey(objType))
{
return cachedProperties[objType];
}
var properties = TypeDescriptor.GetProperties(obj.GetType()).Cast<PropertyDescriptor>();
Dictionary<Identifier, SerializableProperty> dictionary = new Dictionary<Identifier, SerializableProperty>();
foreach (var property in properties)
{
//if the getter is private, we must get it from the declaring type to access it and check if it exists
SerializableProperty serializableProperty = null;
try
{
serializableProperty = new SerializableProperty(property);
}
catch (AmbiguousMatchException)
{
//can happen e.g. with AnimController.CurrentGroundedParams, which is of an abstract type -
//let's just ignore these types of properties (you can't really do anything with SerializableProperties that are reference types anyway)
continue;
}
dictionary.Add(serializableProperty.Name.ToIdentifier(), serializableProperty);
}
cachedProperties[objType] = dictionary;
return dictionary;
}
public static Dictionary<Identifier, SerializableProperty> DeserializeProperties(object obj, XElement element = null)
{
Dictionary<Identifier, SerializableProperty> dictionary = GetProperties(obj);
#if DEBUG
var nonPublicProperties = obj.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in nonPublicProperties)
{
if (property.GetAttribute<Serialize>() != null)
{
DebugConsole.ThrowError($"The property {property.Name} in class {obj.GetType()} is set as serializable, but isn't public. Serializable properties must have at least a public getter.");
}
}
#endif
foreach (var property in dictionary.Values)
{
//set the value of the property to the default value if there is one
foreach (var ini in property.Attributes.OfType<Serialize>())
{
property.TrySetValue(obj, ini.DefaultValue);
break;
}
}
if (element != null)
{
//go through all the attributes in the xml element
//and set the value of the matching property if it is initializable
foreach (XAttribute attribute in element.Attributes())
{
if (!dictionary.TryGetValue(attribute.NameAsIdentifier(), out SerializableProperty property)) { continue; }
if (!property.Attributes.OfType<Serialize>().Any()) { continue; }
property.TrySetValue(obj, attribute.Value);
}
}
return dictionary;
}
public static void SerializeProperties(ISerializableEntity obj, XElement element, bool saveIfDefault = false, bool ignoreEditable = false)
{
var saveProperties = GetProperties<Serialize>(obj);
foreach (var property in saveProperties)
{
object value = property.GetValue(obj);
if (value == null) continue;
if (!saveIfDefault)
{
//only save
// - if the attribute is saveable and it's different from the default value
// - or can be changed in-game or in the editor
bool save = false;
foreach (var attribute in property.Attributes.OfType<Serialize>())
{
if ((attribute.IsSaveable == IsPropertySaveable.Yes && !attribute.DefaultValue.Equals(value)) ||
(!ignoreEditable && property.Attributes.OfType<Editable>().Any()))
{
save = true;
break;
}
}
if (!save) continue;
}
string stringValue;
if (!supportedTypes.TryGetValue(value.GetType(), out string typeName))
{
if (property.PropertyType.IsEnum)
{
stringValue = value.ToString();
}
else
{
DebugConsole.ThrowError("Failed to serialize the property \"" + property.Name + "\" of \"" + obj + "\" (type " + property.PropertyType + " not supported)");
continue;
}
}
else
{
switch (typeName)
{
case "float":
//make sure the decimal point isn't converted to a comma or anything else
stringValue = ((float)value).ToString("G", CultureInfo.InvariantCulture);
break;
case "point":
stringValue = XMLExtensions.PointToString((Point)value);
break;
case "vector2":
stringValue = XMLExtensions.Vector2ToString((Vector2)value);
break;
case "vector3":
stringValue = XMLExtensions.Vector3ToString((Vector3)value);
break;
case "vector4":
stringValue = XMLExtensions.Vector4ToString((Vector4)value);
break;
case "color":
stringValue = XMLExtensions.ColorToString((Color)value);
break;
case "rectangle":
stringValue = XMLExtensions.RectToString((Rectangle)value);
break;
case "stringarray":
string[] stringArray = (string[])value;
stringValue = stringArray != null ? string.Join(';', stringArray) : "";
break;
case "identifierarray":
Identifier[] identifierArray = (Identifier[])value;
stringValue = identifierArray != null ? string.Join(';', identifierArray) : "";
break;
default:
stringValue = value.ToString();
break;
}
}
element.GetAttribute(property.Name)?.Remove();
element.SetAttributeValue(property.Name, stringValue);
}
}
/// <summary>
/// Upgrade the properties of an entity saved with an older version of the game. Properties that should be upgraded are defined using "Upgrade" elements in the config file.
/// for example, <Upgrade gameversion="0.9.2.0" scale="0.5"/> would force the scale of the entity to 0.5 if it was saved with a version prior to 0.9.2.0.
/// </summary>
/// <param name="entity">The entity to upgrade</param>
/// <param name="configElement">The XML element to get the upgrade instructions from (e.g. the config of an item prefab)</param>
/// <param name="savedVersion">The game version the entity was saved with</param>
public static void UpgradeGameVersion(ISerializableEntity entity, ContentXElement configElement, Version savedVersion)
{
foreach (var subElement in configElement.Elements())
{
if (!subElement.Name.ToString().Equals("upgrade", StringComparison.OrdinalIgnoreCase)) { continue; }
var upgradeVersion = new Version(subElement.GetAttributeString("gameversion", "0.0.0.0"));
if (subElement.GetAttributeBool("campaignsaveonly", false))
{
if ((GameMain.GameSession?.LastSaveVersion ?? GameMain.Version) >= upgradeVersion) { continue; }
}
else
{
if (savedVersion >= upgradeVersion) { continue; }
}
foreach (XAttribute attribute in subElement.Attributes())
{
var attributeName = attribute.NameAsIdentifier();
if (attributeName == "gameversion" || attributeName == "campaignsaveonly") { continue; }
if (attributeName == "refreshrect")
{
if (entity is Structure structure)
{
if (!structure.ResizeHorizontal)
{
structure.Rect = structure.DefaultRect = new Rectangle(structure.Rect.X, structure.Rect.Y,
(int)structure.Prefab.ScaledSize.X,
structure.Rect.Height);
}
if (!structure.ResizeVertical)
{
structure.Rect = structure.DefaultRect = new Rectangle(structure.Rect.X, structure.Rect.Y,
structure.Rect.Width,
(int)structure.Prefab.ScaledSize.Y);
}
}
else if (entity is Item item)
{
if (!item.ResizeHorizontal)
{
item.Rect = item.DefaultRect = new Rectangle(item.Rect.X, item.Rect.Y,
(int)(item.Prefab.Size.X * item.Prefab.Scale),
item.Rect.Height);
}
if (!item.ResizeVertical)
{
item.Rect = item.DefaultRect = new Rectangle(item.Rect.X, item.Rect.Y,
item.Rect.Width,
(int)(item.Prefab.Size.Y * item.Prefab.Scale));
}
}
}
else if (attributeName == "unlockrecipe" || attributeName == "unlockrecipes")
{
var recipes = subElement.GetAttributeIdentifierImmutableHashSet("unlockrecipes",
def: subElement.GetAttributeIdentifierImmutableHashSet("unlockrecipe", ImmutableHashSet<Identifier>.Empty));
foreach (var recipe in recipes)
{
GameMain.GameSession?.UnlockRecipe(CharacterTeamType.Team1, recipe, showNotifications: false);
}
}
if (entity.SerializableProperties.TryGetValue(attributeName, out SerializableProperty property))
{
FixValue(property, entity, attribute);
if (property.Name == nameof(ItemComponent.Msg) && entity is ItemComponent component)
{
component.ParseMsg();
}
}
else if (entity is Item item1)
{
foreach (ISerializableEntity component in item1.AllPropertyObjects)
{
if (component.SerializableProperties.TryGetValue(attributeName, out SerializableProperty componentProperty))
{
FixValue(componentProperty, component, attribute);
if (componentProperty.Name == nameof(ItemComponent.Msg))
{
((ItemComponent)component).ParseMsg();
}
}
}
}
}
static void FixValue(SerializableProperty property, object parentObject, XAttribute attribute)
{
if (attribute.Value.Length > 0 && attribute.Value[0] == '*')
{
float.TryParse(attribute.Value.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out float multiplier);
if (property.PropertyType == typeof(int))
{
property.TrySetValue(parentObject, (int)(((int)property.GetValue(parentObject)) * multiplier));
}
else if (property.PropertyType == typeof(float))
{
property.TrySetValue(parentObject, (float)property.GetValue(parentObject) * multiplier);
}
else if (property.PropertyType == typeof(Vector2))
{
property.TrySetValue(parentObject, (Vector2)property.GetValue(parentObject) * multiplier);
}
else if (property.PropertyType == typeof(Point))
{
property.TrySetValue(parentObject, ((Point)property.GetValue(parentObject)).Multiply(multiplier));
}
}
else if (attribute.Value.Length > 0 && attribute.Value[0] == '+')
{
if (property.PropertyType == typeof(int))
{
float.TryParse(attribute.Value.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out float addition);
property.TrySetValue(parentObject, (int)(((int)property.GetValue(parentObject)) + addition));
}
else if (property.PropertyType == typeof(float))
{
float.TryParse(attribute.Value.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out float addition);
property.TrySetValue(parentObject, (float)property.GetValue(parentObject) + addition);
}
else if (property.PropertyType == typeof(Vector2))
{
var addition = XMLExtensions.ParseVector2(attribute.Value.Substring(1));
property.TrySetValue(parentObject, (Vector2)property.GetValue(parentObject) + addition);
}
else if (property.PropertyType == typeof(Point))
{
var addition = XMLExtensions.ParsePoint(attribute.Value.Substring(1));
property.TrySetValue(parentObject, ((Point)property.GetValue(parentObject)) + addition);
}
}
else
{
property.TrySetValue(parentObject, attribute.Value);
}
}
if (entity is Item item2)
{
var componentElement = subElement.FirstElement();
if (componentElement == null) { continue; }
ItemComponent itemComponent = item2.Components.FirstOrDefault(c => c.Name == componentElement.Name.ToString());
if (itemComponent == null) { continue; }
foreach (XAttribute attribute in componentElement.Attributes())
{
var attributeName = attribute.NameAsIdentifier();
if (itemComponent.SerializableProperties.TryGetValue(attributeName, out SerializableProperty property))
{
FixValue(property, itemComponent, attribute);
}
}
foreach (var element in componentElement.Elements())
{
switch (element.Name.ToString().ToLowerInvariant())
{
case "requireditem":
case "requireditems":
itemComponent.RequiredItems.Clear();
itemComponent.DisabledRequiredItems.Clear();
itemComponent.SetRequiredItems(element, allowEmpty: true);
break;
}
}
if (itemComponent is ItemContainer itemContainer &&
(componentElement.GetChildElement("containable") != null || componentElement.GetChildElement("subcontainer") != null))
{
itemContainer.ReloadContainableRestrictions(componentElement);
}
}
}
}
}
}
| 0 | 0.85119 | 1 | 0.85119 | game-dev | MEDIA | 0.63304 | game-dev | 0.979109 | 1 | 0.979109 |
magefree/mage | 1,178 | Mage.Sets/src/mage/cards/c/CarrionWall.java |
package mage.cards.c;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.RegenerateSourceEffect;
import mage.abilities.keyword.DefenderAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
/**
*
* @author Plopman
*/
public final class CarrionWall extends CardImpl {
public CarrionWall(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{B}{B}");
this.subtype.add(SubType.WALL);
this.power = new MageInt(3);
this.toughness = new MageInt(2);
// Defender
this.addAbility(DefenderAbility.getInstance());
// {1}{B}: Regenerate Carrion Wall.
this.addAbility(new SimpleActivatedAbility(new RegenerateSourceEffect(), new ManaCostsImpl<>("{1}{B}")));
}
private CarrionWall(final CarrionWall card) {
super(card);
}
@Override
public CarrionWall copy() {
return new CarrionWall(this);
}
}
| 0 | 0.924957 | 1 | 0.924957 | game-dev | MEDIA | 0.956333 | game-dev | 0.94242 | 1 | 0.94242 |
dufernst/LegionCore-7.3.5 | 2,426 | src/server/scripts/Scenario/BattlePetInstance/instance_walling_caverns_pet.cpp | /*
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
class instance_walling_caverns_pet : public InstanceMapScript
{
public:
instance_walling_caverns_pet() : InstanceMapScript("instance_walling_caverns_pet", 1687) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_walling_caverns_pet_InstanceMapScript(map);
}
struct instance_walling_caverns_pet_InstanceMapScript : public InstanceScript
{
instance_walling_caverns_pet_InstanceMapScript(Map* map) : InstanceScript(map) {}
std::list<ObjectGuid> gobs{};
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case 266872:
gobs.push_back(go->GetGUID());
break;
}
}
void onScenarionNextStep(uint32 newStep) override
{
gobs.sort([&](const ObjectGuid& guid1, const ObjectGuid& guid2)
{
GameObject* go1 = instance->GetGameObject(guid1);
GameObject* go2 = instance->GetGameObject(guid2);
if (!go1 || !go2)
return true;
return go1->GetDBTableGUIDLow() < go2->GetDBTableGUIDLow();
});
uint8 i = 0;
for (const auto& guid : gobs)
{
if (i != 2 && i != 5)
if (GameObject* go = instance->GetGameObject(guid))
go->SetFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_NOT_SELECTABLE);
++i;
}
i = 0;
switch (newStep)
{
case 2:
i = 0;
break;
case 4:
i = 2;
break;
case 5:
i = 3;
break;
default:
return;
}
if (i >= gobs.size())
return;
auto itr = gobs.begin();
std::advance(itr, i);
if (GameObject* go = instance->GetGameObject(*itr))
HandleGameObject(go->GetGUID(), true, go);
}
void Update(uint32 diff) override {}
};
};
void AddSC_instance_walling_caverns_pet()
{
new instance_walling_caverns_pet();
}
| 0 | 0.913501 | 1 | 0.913501 | game-dev | MEDIA | 0.98403 | game-dev | 0.850794 | 1 | 0.850794 |
tangziwen/CubeMiniGame | 3,134 | CubeEngine/External/Bullet/BulletSoftBody/btSoftRigidCollisionAlgorithm.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_SOFT_RIGID_COLLISION_ALGORITHM_H
#define BT_SOFT_RIGID_COLLISION_ALGORITHM_H
#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "LinearMath/btVector3.h"
class btSoftBody;
/// btSoftRigidCollisionAlgorithm provides collision detection between btSoftBody and btRigidBody
class btSoftRigidCollisionAlgorithm : public btCollisionAlgorithm
{
// bool m_ownManifold;
// btPersistentManifold* m_manifoldPtr;
//btSoftBody* m_softBody;
//btCollisionObject* m_rigidCollisionObject;
///for rigid versus soft (instead of soft versus rigid), we use this swapped boolean
bool m_isSwapped;
public:
btSoftRigidCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* col0,const btCollisionObjectWrapper* col1Wrap, bool isSwapped);
virtual ~btSoftRigidCollisionAlgorithm();
virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
{
//we don't add any manifolds
}
struct CreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftRigidCollisionAlgorithm));
if (!m_swapped)
{
return new(mem) btSoftRigidCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,false);
} else
{
return new(mem) btSoftRigidCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,true);
}
}
};
};
#endif //BT_SOFT_RIGID_COLLISION_ALGORITHM_H
| 0 | 0.81753 | 1 | 0.81753 | game-dev | MEDIA | 0.990991 | game-dev | 0.652758 | 1 | 0.652758 |
luanti-org/luanti | 5,570 | src/servermap.h | // Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2010-2024 celeron55, Perttu Ahola <celeron55@gmail.com>
#pragma once
#include <vector>
#include <memory>
#include "map.h"
#include "util/container.h" // UniqueQueue
#include "util/metricsbackend.h" // ptr typedefs
#include "map_settings_manager.h"
class Settings;
class MapDatabase;
class EmergeManager;
class ServerEnvironment;
struct BlockMakeData;
class MetricsBackend;
// TODO: this could wrap all calls to MapDatabase, including locking
struct MapDatabaseAccessor {
/// Lock, to be taken for any operation
std::mutex mutex;
/// Main database
MapDatabase *dbase = nullptr;
/// Fallback database for read operations
MapDatabase *dbase_ro = nullptr;
/// Load a block, taking dbase_ro into account.
/// @note call locked
void loadBlock(v3s16 blockpos, std::string &ret);
};
/*
ServerMap
This is the only map class that is able to generate map.
*/
class ServerMap : public Map
{
public:
/*
savedir: directory to which map data should be saved
*/
ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb);
~ServerMap();
/*
Get a sector from somewhere.
- Check memory
- Check disk (doesn't load blocks)
- Create blank one
*/
MapSector *createSector(v2s16 p);
/*
Blocks are generated by using these and makeBlock().
*/
bool blockpos_over_mapgen_limit(v3s16 p);
/// @brief copy data from map to prepare for mapgen
/// @return true if mapgen should actually happen
bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
/// @brief write data back to map after mapgen
/// @param now current game time
void finishBlockMake(BlockMakeData *data,
std::map<v3s16, MapBlock*> *changed_blocks, u32 now);
void cancelBlockMake(BlockMakeData *data);
/*
Get a block from somewhere.
- Memory
- Create blank
*/
MapBlock *createBlock(v3s16 p);
/*
Forcefully get a block from somewhere (blocking!).
- Memory
- Load from disk
- Create blank filled with CONTENT_IGNORE
*/
MapBlock *emergeBlock(v3s16 p, bool create_blank=true) override;
/*
Try to get a block.
If it does not exist in memory, add it to the emerge queue.
- Memory
- Emerge Queue (deferred disk or generate)
*/
MapBlock *getBlockOrEmerge(v3s16 p3d, bool generate);
bool isBlockInQueue(v3s16 pos);
void addNodeAndUpdate(v3s16 p, MapNode n,
std::map<v3s16, MapBlock*> &modified_blocks,
bool remove_metadata) override;
/*
Database functions
*/
static std::vector<std::string> getDatabaseBackends();
static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
// Call these before and after saving of blocks
void beginSave() override;
void endSave() override;
void save(ModifiedState save_level) override;
void listAllLoadableBlocks(std::vector<v3s16> &dst);
void listAllLoadedBlocks(std::vector<v3s16> &dst);
MapgenParams *getMapgenParams();
bool saveBlock(MapBlock *block) override;
static bool saveBlock(MapBlock *block, MapDatabase *db, int compression_level = -1);
// Load block in a synchronous fashion
MapBlock *loadBlock(v3s16 p);
/// Load a block that was already read from disk. Used by EmergeManager.
/// @return non-null block (but can be blank)
MapBlock *loadBlock(const std::string &blob, v3s16 p, bool save_after_load=false);
// Helper for deserializing blocks from disk
// @throws SerializationError
static void deSerializeBlock(MapBlock *block, std::istream &is);
// Blocks are removed from the map but not deleted from memory until
// deleteDetachedBlocks() is called, since pointers to them may still exist
// when deleteBlock() is called.
bool deleteBlock(v3s16 blockpos) override;
void deleteDetachedBlocks();
void step();
void updateVManip(v3s16 pos);
// For debug printing
void PrintInfo(std::ostream &out) override;
bool isSavingEnabled(){ return m_map_saving_enabled; }
u64 getSeed();
/*!
* Fixes lighting in one map block.
* May modify other blocks as well, as light can spread
* out of the specified block.
* Returns false if the block is not generated (so nothing
* changed), true otherwise.
*/
bool repairBlockLight(v3s16 blockpos,
std::map<v3s16, MapBlock *> *modified_blocks);
void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
ServerEnvironment *env);
void transforming_liquid_add(v3s16 p);
MapSettingsManager settings_mgr;
protected:
void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) override;
private:
friend class ModApiMapgen; // for m_transforming_liquid
// extra border area during mapgen (in blocks)
constexpr static v3s16 EMERGE_EXTRA_BORDER{1, 1, 1};
// Emerge manager
EmergeManager *m_emerge;
std::string m_savedir;
bool m_map_saving_enabled;
int m_map_compression_level;
std::set<v3s16> m_chunks_in_progress;
// used by deleteBlock() and deleteDetachedBlocks()
std::vector<std::unique_ptr<MapBlock>> m_detached_blocks;
// Queued transforming water nodes
UniqueQueue<v3s16> m_transforming_liquid;
f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
u32 m_unprocessed_count = 0;
u64 m_inc_trending_up_start_time = 0; // milliseconds
bool m_queue_size_timer_started = false;
/*
Metadata is re-written on disk only if this is true.
This is reset to false when written on disk.
*/
bool m_map_metadata_changed = true;
MapDatabaseAccessor m_db;
// Map metrics
MetricGaugePtr m_loaded_blocks_gauge;
MetricCounterPtr m_save_time_counter;
MetricCounterPtr m_save_count_counter;
};
| 0 | 0.967059 | 1 | 0.967059 | game-dev | MEDIA | 0.814978 | game-dev | 0.597514 | 1 | 0.597514 |
thetawavegame/thetawave | 1,552 | crates/thetawave_interface/src/audio.rs | use std::time::Duration;
use bevy_ecs::prelude::Event;
use serde::Deserialize;
use strum_macros::Display;
/// Background music types
#[derive(Deserialize, Debug, Hash, PartialEq, Eq, Clone, Display)]
pub enum BGMusicType {
Game,
Boss,
BossTransition,
Main,
}
#[derive(Deserialize, Debug, Hash, PartialEq, Eq, Clone, Display, Copy)]
pub enum SoundEffectType {
Collision(CollisionSoundType),
BarrierBounce,
ConsumablePickup,
DefenseDamage,
DefenseHeal,
EnemyFireBlast,
MenuInputSuccess,
MobExplosion,
MobHit,
PlayerExplosion,
PlayerFireBlast,
PlayerHit,
BulletDing,
BulletBounce,
MegaBlastAbility,
ObjectiveCompleted,
ButtonSelect,
ButtonRelease,
ButtonConfirm,
}
/// Subtype of sound effect for collisions
#[derive(Deserialize, Debug, Hash, PartialEq, Eq, Clone, Display, Default, Copy)]
pub enum CollisionSoundType {
Squishy,
#[default]
Normal,
}
#[derive(Event, Default)]
pub struct ChangeBackgroundMusicEvent {
/// Background music to change to, None will just stop the current music
pub bg_music_type: Option<BGMusicType>,
/// Loop from a specific time in the track, None will not loop the track
pub loop_from: Option<f64>,
/// Fade in duration for the music cycling in (bg_music_type)
pub fade_in: Option<Duration>,
/// Fade out duration for the music currently being played
pub fade_out: Option<Duration>,
}
#[derive(Event)]
pub struct PlaySoundEffectEvent {
pub sound_effect_type: SoundEffectType,
}
| 0 | 0.759501 | 1 | 0.759501 | game-dev | MEDIA | 0.797699 | game-dev | 0.727646 | 1 | 0.727646 |
neumatho/NostalgicPlayer | 45,534 | Source/Agents/Players/SidMon20/SidMon20Worker.cs | /******************************************************************************/
/* This source, or parts thereof, may be used in any software as long the */
/* license of NostalgicPlayer is keep. See the LICENSE file for more */
/* information. */
/******************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Polycode.NostalgicPlayer.Agent.Player.SidMon20.Containers;
using Polycode.NostalgicPlayer.Kit;
using Polycode.NostalgicPlayer.Kit.Bases;
using Polycode.NostalgicPlayer.Kit.Containers;
using Polycode.NostalgicPlayer.Kit.Interfaces;
using Polycode.NostalgicPlayer.Kit.Streams;
namespace Polycode.NostalgicPlayer.Agent.Player.SidMon20
{
/// <summary>
/// Main worker class
/// </summary>
internal class SidMon20Worker : ModulePlayerWithSubSongDurationAgentBase
{
#region BlockInfo class
private class BlockInfo
{
/********************************************************************/
/// <summary>
/// Constructor
/// </summary>
/********************************************************************/
public BlockInfo(uint offset, uint length)
{
Offset = offset;
Length = length;
}
/********************************************************************/
/// <summary>
///
/// </summary>
/********************************************************************/
public uint Offset
{
get;
}
/********************************************************************/
/// <summary>
///
/// </summary>
/********************************************************************/
public uint Length
{
get;
}
}
#endregion
private byte[][] waveformInfo;
private sbyte[][] arpeggios;
private sbyte[][] vibratoes;
private Sequence[][] sequences;
private Track[] tracks;
private Instrument[] instruments;
private Sample[] samples;
private SampleNegateInfo[] sampleNegateInfo;
private byte numberOfPositions;
private byte startSpeed;
private GlobalPlayingInfo playingInfo;
private bool endReached;
private const int InfoPositionLine = 3;
private const int InfoTrackLine = 4;
private const int InfoSpeedLine = 5;
#region Identify
/********************************************************************/
/// <summary>
/// Returns the file extensions that identify this player
/// </summary>
/********************************************************************/
public override string[] FileExtensions => [ "sd2", "sid2", "sid" ];
/********************************************************************/
/// <summary>
/// Test the file to see if it could be identified
/// </summary>
/********************************************************************/
public override AgentResult Identify(PlayerFileInfo fileInfo)
{
ModuleStream moduleStream = fileInfo.ModuleStream;
// Check the module size
if (moduleStream.Length < 86)
return AgentResult.Unknown;
// Check the identifier string
moduleStream.Seek(58, SeekOrigin.Begin);
if (moduleStream.ReadMark(28) == "SIDMON II - THE MIDI VERSION")
return AgentResult.Ok;
return AgentResult.Unknown;
}
#endregion
#region Loading
/********************************************************************/
/// <summary>
/// Will load the file into memory
/// </summary>
/********************************************************************/
public override AgentResult Load(PlayerFileInfo fileInfo, out string errorMessage)
{
errorMessage = string.Empty;
try
{
ModuleStream moduleStream = fileInfo.ModuleStream;
if (!LoadSongData(moduleStream, out ushort numberOfSamples, out BlockInfo positionTableInfo, out BlockInfo noteTransposeInfo, out BlockInfo instrumentTransposeInfo, out BlockInfo instrumentsInfo, out BlockInfo waveformListInfo, out BlockInfo arpeggiosInfo, out BlockInfo vibratoesInfo, out BlockInfo sampleInfoInfo, out BlockInfo trackTableInfo, out BlockInfo tracksInfo))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_SONGDATA;
return AgentResult.Error;
}
if (!LoadLists(moduleStream, waveformListInfo, arpeggiosInfo, vibratoesInfo))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_SONGDATA;
return AgentResult.Error;
}
if (!LoadSequences(moduleStream, positionTableInfo, noteTransposeInfo, instrumentTransposeInfo))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_SEQUENCES;
return AgentResult.Error;
}
if (!LoadTracks(moduleStream, trackTableInfo, tracksInfo, out uint sampleOffset))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_TRACKS;
return AgentResult.Error;
}
if (!LoadInstruments(moduleStream, instrumentsInfo))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_INSTRUMENTS;
return AgentResult.Error;
}
if (!LoadSamples(moduleStream, sampleOffset, numberOfSamples, sampleInfoInfo))
{
errorMessage = Resources.IDS_SD2_ERR_LOADING_SAMPLES;
return AgentResult.Error;
}
// At this point, the numberOfPositions holds the real number of position, but the player itself need one less
numberOfPositions--;
}
catch (Exception)
{
Cleanup();
throw;
}
// Ok, we're done
return AgentResult.Ok;
}
#endregion
#region Initialization and cleanup
/********************************************************************/
/// <summary>
/// Cleanup the player
/// </summary>
/********************************************************************/
public override void CleanupPlayer()
{
Cleanup();
base.CleanupPlayer();
}
/********************************************************************/
/// <summary>
/// Initializes the current song
/// </summary>
/********************************************************************/
public override bool InitSound(int songNumber, out string errorMessage)
{
if (!base.InitSound(songNumber, out errorMessage))
return false;
InitializeSound();
return true;
}
#endregion
#region Playing
/********************************************************************/
/// <summary>
/// This is the main player method
/// </summary>
/********************************************************************/
public override void Play()
{
PlayIt();
if (endReached)
{
OnEndReachedOnAllChannels(playingInfo.CurrentPosition);
endReached = false;
}
}
#endregion
#region Information
/********************************************************************/
/// <summary>
/// Returns all the samples available in the module. If none, null
/// is returned
/// </summary>
/********************************************************************/
public override IEnumerable<SampleInfo> Samples
{
get
{
// Build frequency table
uint[] frequencies = new uint[10 * 12];
for (int i = 0; i < 6 * 12; i++)
frequencies[2 * 12 - 9 + i] = PeriodToFrequency(Tables.Periods[1 + i]);
foreach (Sample sample in samples)
{
SampleInfo sampleInfo = new SampleInfo
{
Name = sample.Name,
Flags = SampleInfo.SampleFlag.None,
Type = SampleInfo.SampleType.Sample,
Volume = 256,
Panning = -1,
Sample = sample.SampleData,
Length = (uint)sample.SampleData.Length,
NoteFrequencies = frequencies
};
if (sample.LoopLength <= 2)
{
// No loop
sampleInfo.LoopStart = 0;
sampleInfo.LoopLength = 0;
}
else
{
// Sample loops
sampleInfo.Flags |= SampleInfo.SampleFlag.Loop;
sampleInfo.LoopStart = sample.LoopStart;
sampleInfo.LoopLength = sample.LoopLength;
}
yield return sampleInfo;
}
}
}
/********************************************************************/
/// <summary>
/// Returns the description and value on the line given. If the line
/// is out of range, false is returned
/// </summary>
/********************************************************************/
public override bool GetInformationString(int line, out string description, out string value)
{
// Find out which line to take
switch (line)
{
// Number of positions
case 0:
{
description = Resources.IDS_SD2_INFODESCLINE0;
value = (numberOfPositions + 1).ToString();
break;
}
// Used tracks
case 1:
{
description = Resources.IDS_SD2_INFODESCLINE1;
value = tracks.Length.ToString();
break;
}
// Used samples
case 2:
{
description = Resources.IDS_SD2_INFODESCLINE2;
value = samples.Length.ToString();
break;
}
// Playing position
case 3:
{
description = Resources.IDS_SD2_INFODESCLINE3;
value = playingInfo.CurrentPosition.ToString();
break;
}
// Playing tracks
case 4:
{
description = Resources.IDS_SD2_INFODESCLINE4;
value = FormatTracks();
break;
}
// Current speed
case 5:
{
description = Resources.IDS_SD2_INFODESCLINE5;
value = playingInfo.Speed.ToString();
break;
}
default:
{
description = null;
value = null;
return false;
}
}
return true;
}
#endregion
#region Duration calculation
/********************************************************************/
/// <summary>
/// Initialize all internal structures when beginning duration
/// calculation on a new sub-song
/// </summary>
/********************************************************************/
protected override void InitDuration(int subSong)
{
InitializeSound();
MarkPositionAsVisited(0);
}
/********************************************************************/
/// <summary>
/// Return the total number of positions. You only need to derive
/// from this method, if your player have one position list for all
/// channels and can restart on another position than 0
/// </summary>
/********************************************************************/
protected override int GetTotalNumberOfPositions()
{
return numberOfPositions + 1;
}
/********************************************************************/
/// <summary>
/// Create a snapshot of all the internal structures and return it
/// </summary>
/********************************************************************/
protected override ISnapshot CreateSnapshot()
{
return new Snapshot(playingInfo, instruments, sampleNegateInfo);
}
/********************************************************************/
/// <summary>
/// Initialize internal structures based on the snapshot given
/// </summary>
/********************************************************************/
protected override bool SetSnapshot(ISnapshot snapshot, out string errorMessage)
{
errorMessage = string.Empty;
// Start to make a clone of the snapshot
Snapshot currentSnapshot = (Snapshot)snapshot;
Snapshot clonedSnapshot = new Snapshot(currentSnapshot.PlayingInfo, currentSnapshot.Instruments, currentSnapshot.SampleNegateInfo);
playingInfo = clonedSnapshot.PlayingInfo;
instruments = clonedSnapshot.Instruments;
sampleNegateInfo = clonedSnapshot.SampleNegateInfo;
UpdateModuleInformation();
return true;
}
#endregion
#region Private methods
/********************************************************************/
/// <summary>
/// Load the song data information
/// </summary>
/********************************************************************/
private bool LoadSongData(ModuleStream moduleStream, out ushort numberOfSamples, out BlockInfo positionTableInfo, out BlockInfo noteTransposeInfo, out BlockInfo instrumentTransposeInfo, out BlockInfo instrumentsInfo, out BlockInfo waveformListInfo, out BlockInfo arpeggiosInfo, out BlockInfo vibratoesInfo, out BlockInfo sampleInfoInfo, out BlockInfo trackTableInfo, out BlockInfo tracksInfo)
{
// Skip MIDI mode
moduleStream.Seek(2, SeekOrigin.Begin);
numberOfPositions = moduleStream.Read_UINT8();
numberOfPositions++;
startSpeed = moduleStream.Read_UINT8();
numberOfSamples = moduleStream.Read_B_UINT16();
numberOfSamples /= 64;
uint offset = 58; // Offset to ID
offset += moduleStream.Read_B_UINT32(); // ID length
offset += moduleStream.Read_B_UINT32(); // Song length length
uint length = moduleStream.Read_B_UINT32();
positionTableInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
noteTransposeInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
instrumentTransposeInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
instrumentsInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
waveformListInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
arpeggiosInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
vibratoesInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
sampleInfoInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
trackTableInfo = new BlockInfo(offset, length);
offset += length;
length = moduleStream.Read_B_UINT32();
tracksInfo = new BlockInfo(offset, length);
if (moduleStream.EndOfStream)
return false;
return true;
}
/********************************************************************/
/// <summary>
/// Load all the different lists
/// </summary>
/********************************************************************/
private bool LoadLists(ModuleStream moduleStream, BlockInfo waveformListInfo, BlockInfo arpeggiosInfo, BlockInfo vibratoesInfo)
{
waveformInfo = LoadSingleList<byte>(moduleStream, waveformListInfo);
if (waveformInfo == null)
return false;
arpeggios = LoadSingleList<sbyte>(moduleStream, arpeggiosInfo);
if (arpeggios == null)
return false;
vibratoes = LoadSingleList<sbyte>(moduleStream, vibratoesInfo);
if (vibratoes == null)
return false;
return true;
}
/********************************************************************/
/// <summary>
/// Load a single list
/// </summary>
/********************************************************************/
private T[][] LoadSingleList<T>(ModuleStream moduleStream, BlockInfo blockInfo)
{
if ((blockInfo.Length % 16) != 0)
return null;
moduleStream.Seek(blockInfo.Offset, SeekOrigin.Begin);
uint count = blockInfo.Length / 16;
T[][] list = new T[count][];
for (int i = 0; i < count; i++)
{
list[i] = new T[16];
int bytesRead = moduleStream.Read((byte[])(Array)list[i], 0, 16);
if (bytesRead < 16)
return null;
}
return list;
}
/********************************************************************/
/// <summary>
/// Load all the sequences
/// </summary>
/********************************************************************/
private bool LoadSequences(ModuleStream moduleStream, BlockInfo positionTableInfo, BlockInfo noteTransposeInfo, BlockInfo instrumentTransposeInfo)
{
if ((positionTableInfo.Length != noteTransposeInfo.Length) || (noteTransposeInfo.Length != instrumentTransposeInfo.Length))
return false;
if (positionTableInfo.Length != (numberOfPositions * 4))
return false;
byte[] positions = new byte[positionTableInfo.Length];
sbyte[] noteTranspose = new sbyte[noteTransposeInfo.Length];
sbyte[] instrumentTranspose = new sbyte[instrumentTransposeInfo.Length];
moduleStream.Seek(positionTableInfo.Offset, SeekOrigin.Begin);
int bytesRead = moduleStream.Read(positions, 0, positions.Length);
if (bytesRead < positions.Length)
return false;
moduleStream.Seek(noteTransposeInfo.Offset, SeekOrigin.Begin);
moduleStream.ReadSigned(noteTranspose, 0, positions.Length);
if (moduleStream.EndOfStream)
return false;
moduleStream.Seek(instrumentTransposeInfo.Offset, SeekOrigin.Begin);
moduleStream.ReadSigned(instrumentTranspose, 0, positions.Length);
if (moduleStream.EndOfStream)
return false;
sequences = new Sequence[4][];
int startOffset = 0;
for (int i = 0; i < 4; i++, startOffset += numberOfPositions)
{
sequences[i] = new Sequence[numberOfPositions];
for (int j = 0; j < numberOfPositions; j++)
{
sequences[i][j] = new Sequence
{
TrackNumber = positions[startOffset + j],
NoteTranspose = noteTranspose[startOffset + j],
InstrumentTranspose = instrumentTranspose[startOffset + j]
};
}
}
return true;
}
/********************************************************************/
/// <summary>
/// Load all the tracks
/// </summary>
/********************************************************************/
private bool LoadTracks(ModuleStream moduleStream, BlockInfo trackTableInfo, BlockInfo tracksInfo, out uint sampleOffset)
{
sampleOffset = 0;
// Read track offset table
uint numberOfTracks = trackTableInfo.Length / 2;
ushort[] trackOffsetTable = new ushort[numberOfTracks];
moduleStream.Seek(trackTableInfo.Offset, SeekOrigin.Begin);
moduleStream.ReadArray_B_UINT16s(trackOffsetTable, 0, trackOffsetTable.Length);
if (moduleStream.EndOfStream)
return false;
tracks = new Track[numberOfTracks];
for (int i = 0; i < numberOfTracks; i++)
{
uint trackLength = (i == numberOfTracks - 1 ? tracksInfo.Length : trackOffsetTable[i + 1]) - trackOffsetTable[i];
byte[] trackData = new byte[trackLength];
moduleStream.Seek(tracksInfo.Offset + trackOffsetTable[i], SeekOrigin.Begin);
int bytesRead = moduleStream.Read(trackData, 0, (int)trackLength);
if (bytesRead < trackLength)
return false;
tracks[i] = new Track
{
TrackData = trackData
};
}
// Stream position now points to start of sample, but make sure it's on an even position
sampleOffset = (uint)moduleStream.Position;
if ((sampleOffset % 1) != 0)
sampleOffset++;
return true;
}
/********************************************************************/
/// <summary>
/// Load all the instruments
/// </summary>
/********************************************************************/
private bool LoadInstruments(ModuleStream moduleStream, BlockInfo instrumentsInfo)
{
if ((instrumentsInfo.Length % 32) != 0)
return false;
moduleStream.Seek(instrumentsInfo.Offset, SeekOrigin.Begin);
uint count = instrumentsInfo.Length / 32;
instruments = new Instrument[count];
for (uint i = 0; i < count; i++)
{
Instrument instrument = new Instrument();
instrument.WaveformListNumber = moduleStream.Read_UINT8();
instrument.WaveformListLength = moduleStream.Read_UINT8();
instrument.WaveformListSpeed = moduleStream.Read_UINT8();
instrument.WaveformListDelay = moduleStream.Read_UINT8();
instrument.ArpeggioNumber = moduleStream.Read_UINT8();
instrument.ArpeggioLength = moduleStream.Read_UINT8();
instrument.ArpeggioSpeed = moduleStream.Read_UINT8();
instrument.ArpeggioDelay = moduleStream.Read_UINT8();
instrument.VibratoNumber = moduleStream.Read_UINT8();
instrument.VibratoLength = moduleStream.Read_UINT8();
instrument.VibratoSpeed = moduleStream.Read_UINT8();
instrument.VibratoDelay = moduleStream.Read_UINT8();
instrument.PitchBendSpeed = moduleStream.Read_INT8();
instrument.PitchBendDelay = moduleStream.Read_UINT8();
moduleStream.Seek(2, SeekOrigin.Current);
instrument.AttackMax = moduleStream.Read_UINT8();
instrument.AttackSpeed = moduleStream.Read_UINT8();
instrument.DecayMin = moduleStream.Read_UINT8();
instrument.DecaySpeed = moduleStream.Read_UINT8();
instrument.SustainTime = moduleStream.Read_UINT8();
instrument.ReleaseMin = moduleStream.Read_UINT8();
instrument.ReleaseSpeed = moduleStream.Read_UINT8();
if (moduleStream.EndOfStream)
return false;
moduleStream.Seek(9, SeekOrigin.Current);
instruments[i] = instrument;
}
return true;
}
/********************************************************************/
/// <summary>
/// Load all the samples
/// </summary>
/********************************************************************/
private bool LoadSamples(ModuleStream moduleStream, uint sampleOffset, ushort numberOfSamples, BlockInfo sampleInfoInfo)
{
Encoding encoding = EncoderCollection.Amiga;
byte[] name = new byte[32];
samples = new Sample[numberOfSamples];
sampleNegateInfo = new SampleNegateInfo[numberOfSamples];
// First read the sample information
moduleStream.Seek(sampleInfoInfo.Offset, SeekOrigin.Begin);
for (int i = 0; i < numberOfSamples; i++)
{
Sample sample = new Sample();
SampleNegateInfo negateInfo = new SampleNegateInfo();
// Skip sample data pointer
moduleStream.Seek(4, SeekOrigin.Current);
sample.Length = moduleStream.Read_B_UINT16() * 2U;
sample.LoopStart = moduleStream.Read_B_UINT16() * 2U;
sample.LoopLength = moduleStream.Read_B_UINT16() * 2U;
if ((sample.LoopStart > sample.Length))
{
sample.LoopStart = 0;
sample.LoopLength = 0;
}
else if ((sample.LoopStart + sample.LoopLength) > sample.Length)
sample.LoopLength = sample.Length - sample.LoopStart;
// Load negate variables
negateInfo.StartOffset = (uint)(moduleStream.Read_B_UINT16() * 2);
negateInfo.EndOffset = (uint)(moduleStream.Read_B_UINT16() * 2);
negateInfo.LoopIndex = moduleStream.Read_B_UINT16();
negateInfo.Status = moduleStream.Read_B_UINT16();
negateInfo.Speed = moduleStream.Read_B_INT16();
negateInfo.Position = moduleStream.Read_B_INT32();
negateInfo.Index = moduleStream.Read_B_UINT16();
negateInfo.DoNegation = moduleStream.Read_B_INT16();
if (moduleStream.EndOfStream)
return false;
moduleStream.Seek(4, SeekOrigin.Current);
int bytesRead = moduleStream.Read(name, 0, 32);
if (bytesRead < 32)
return false;
sample.Name = encoding.GetString(name);
samples[i] = sample;
sampleNegateInfo[i] = negateInfo;
}
// Now read the sample data
moduleStream.Seek(sampleOffset, SeekOrigin.Begin);
for (int i = 0; i < numberOfSamples; i++)
{
Sample sample = samples[i];
sample.SampleData = moduleStream.ReadSampleData(i, (int)sample.Length, out int readBytes);
if (readBytes < sample.Length)
return false;
}
return true;
}
/********************************************************************/
/// <summary>
/// Frees all the memory the player have allocated
/// </summary>
/********************************************************************/
private void Cleanup()
{
waveformInfo = null;
arpeggios = null;
vibratoes = null;
sequences = null;
tracks = null;
instruments = null;
samples = null;
sampleNegateInfo = null;
}
/********************************************************************/
/// <summary>
/// Initialize sound structures
/// </summary>
/********************************************************************/
private void InitializeSound()
{
playingInfo = new GlobalPlayingInfo
{
CurrentPosition = 0,
CurrentRow = 0,
PatternLength = 64,
CurrentRast = 0,
CurrentRast2 = 0,
Speed = startSpeed,
VoiceInfo = new VoiceInfo[4]
};
for (int i = 0; i < 4; i++)
{
Instrument instrument = instruments[0];
byte sampleNumber = waveformInfo[instrument.WaveformListNumber][0];
Sample sample = samples[sampleNumber];
VoiceInfo voiceInfo = new VoiceInfo
{
SequenceList = sequences[i],
PitchBendValue = 0,
SampleVolume = 0,
WaveListDelay = 0,
WaveListOffset = 0,
ArpeggioDelay = 0,
ArpeggioOffset = 0,
VibratoDelay = 0,
VibratoOffset = 0,
PitchBendCounter = 0,
NoteSlideSpeed = 0,
EnvelopeState = EnvelopeState.Attack,
SustainCounter = 0,
Instrument = instrument,
CurrentSample = sampleNumber,
SampleData = sample.SampleData,
SampleLength = sample.Length,
LoopSample = sample.SampleData,
LoopOffset = sample.LoopStart,
LoopLength = sample.LoopLength,
SamplePeriod = 0,
OriginalNote = 0,
CurrentNote = 0,
CurrentInstrument = 0,
CurrentEffect = 0,
CurrentEffectArg = 0,
NoteSlideNote = 0
};
FindNote(voiceInfo);
playingInfo.VoiceInfo[i] = voiceInfo;
}
endReached = false;
}
/********************************************************************/
/// <summary>
/// The main play method
/// </summary>
/********************************************************************/
private void PlayIt()
{
playingInfo.CurrentRast2++;
if (playingInfo.CurrentRast2 == 3)
playingInfo.CurrentRast2 = 0;
playingInfo.CurrentRast++;
if (playingInfo.CurrentRast >= playingInfo.Speed)
{
playingInfo.CurrentRast = 0;
playingInfo.CurrentRast2 = 0;
for (int i = 0; i < 4; i++)
GetNote(playingInfo.VoiceInfo[i]);
for (int i = 0; i < 4; i++)
PlayVoice(playingInfo.VoiceInfo[i], VirtualChannels[i]);
DoNegation();
playingInfo.CurrentRow++;
if (playingInfo.CurrentRow == playingInfo.PatternLength)
{
playingInfo.CurrentRow = 0;
if (playingInfo.CurrentPosition == numberOfPositions)
{
playingInfo.CurrentPosition = -1;
endReached = true;
}
playingInfo.CurrentPosition++;
MarkPositionAsVisited(playingInfo.CurrentPosition);
ShowSongPositions();
for (int i = 0; i < 4; i++)
FindNote(playingInfo.VoiceInfo[i]);
ShowTracks();
}
}
for (int i = 0; i < 4; i++)
DoEffect(playingInfo.VoiceInfo[i], VirtualChannels[i]);
if (playingInfo.CurrentRast != 0)
DoNegation();
}
/********************************************************************/
/// <summary>
/// Negate samples
/// </summary>
/********************************************************************/
private void DoNegation()
{
SampleNegateInfo[] workingSamples = new SampleNegateInfo[4];
for (int i = 0; i < 4; i++)
{
VoiceInfo voiceInfo = playingInfo.VoiceInfo[i];
ushort sampleNumber = voiceInfo.CurrentSample;
SampleNegateInfo negateInfo = sampleNegateInfo[sampleNumber];
workingSamples[i] = negateInfo;
if (negateInfo.DoNegation == 0)
{
negateInfo.DoNegation = -1;
if (negateInfo.Index == 0)
{
negateInfo.Index = negateInfo.LoopIndex;
if (negateInfo.Status != 0)
{
Sample sample = samples[sampleNumber];
uint endOffset = negateInfo.EndOffset - 1;
int position = (int)(negateInfo.StartOffset + negateInfo.Position);
sample.SampleData[position] = (sbyte)~sample.SampleData[position];
negateInfo.Position += negateInfo.Speed;
if (negateInfo.Position < 0)
{
if (negateInfo.Status == 2)
negateInfo.Position = (int)endOffset;
else
{
negateInfo.Position += -negateInfo.Speed;
negateInfo.Speed = (short)-negateInfo.Speed;
}
}
else
{
if (negateInfo.Position > endOffset)
{
if (negateInfo.Status == 1)
negateInfo.Position = 0;
else
{
negateInfo.Position += -negateInfo.Speed;
negateInfo.Speed = (short)-negateInfo.Speed;
}
}
}
}
}
else
{
negateInfo.Index++;
negateInfo.Index &= 0x1f;
}
}
}
for (int i = 0; i < 4; i++)
workingSamples[i].DoNegation = 0;
}
/********************************************************************/
/// <summary>
/// Initialize sequence variables
/// </summary>
/********************************************************************/
private void FindNote(VoiceInfo voiceInfo)
{
Sequence sequence = voiceInfo.SequenceList[playingInfo.CurrentPosition];
voiceInfo.CurrentTrack = tracks[sequence.TrackNumber].TrackData;
voiceInfo.TrackPosition = 0;
voiceInfo.NoteTranspose = sequence.NoteTranspose;
voiceInfo.InstrumentTranspose = sequence.InstrumentTranspose;
voiceInfo.EmptyNotesCounter = 0;
}
/********************************************************************/
/// <summary>
/// Find the next note to play
/// </summary>
/********************************************************************/
private void GetNote(VoiceInfo voiceInfo)
{
GetNote2(voiceInfo);
if (voiceInfo.CurrentNote != 0)
voiceInfo.CurrentNote = (ushort)(voiceInfo.CurrentNote + voiceInfo.NoteTranspose);
}
/********************************************************************/
/// <summary>
/// Find the next note to play
/// </summary>
/********************************************************************/
private void GetNote2(VoiceInfo voiceInfo)
{
byte[] trackData = voiceInfo.CurrentTrack;
voiceInfo.CurrentNote = 0;
voiceInfo.CurrentInstrument = 0;
voiceInfo.CurrentEffect = 0;
voiceInfo.CurrentEffectArg = 0;
if (voiceInfo.EmptyNotesCounter == 0)
{
sbyte trackValue = (sbyte)(voiceInfo.TrackPosition < trackData.Length ? trackData[voiceInfo.TrackPosition++] : -1);
if (trackValue == 0)
{
voiceInfo.CurrentEffect = trackData[voiceInfo.TrackPosition++];
voiceInfo.CurrentEffectArg = trackData[voiceInfo.TrackPosition++];
return;
}
if (trackValue > 0)
{
if (trackValue >= 0x70)
{
voiceInfo.CurrentEffect = (byte)trackValue;
voiceInfo.CurrentEffectArg = trackData[voiceInfo.TrackPosition++];
return;
}
voiceInfo.CurrentNote = (ushort)trackValue;
trackValue = (sbyte)trackData[voiceInfo.TrackPosition++];
if (trackValue >= 0)
{
if (trackValue >= 0x70)
{
voiceInfo.CurrentEffect = (byte)trackValue;
voiceInfo.CurrentEffectArg = trackData[voiceInfo.TrackPosition++];
return;
}
voiceInfo.CurrentInstrument = (ushort)trackValue;
trackValue = (sbyte)trackData[voiceInfo.TrackPosition++];
if (trackValue >= 0)
{
voiceInfo.CurrentEffect = (byte)trackValue;
voiceInfo.CurrentEffectArg = trackData[voiceInfo.TrackPosition++];
return;
}
}
}
voiceInfo.EmptyNotesCounter = (ushort)(~trackValue);
}
else
voiceInfo.EmptyNotesCounter--;
}
/********************************************************************/
/// <summary>
/// Playing the voice
/// </summary>
/********************************************************************/
private void PlayVoice(VoiceInfo voiceInfo, IChannel channel)
{
voiceInfo.PitchBendValue = 0;
if (voiceInfo.CurrentNote != 0)
{
voiceInfo.SampleVolume = 0;
voiceInfo.WaveListDelay = 0;
voiceInfo.WaveListOffset = 0;
voiceInfo.ArpeggioDelay = 0;
voiceInfo.ArpeggioOffset = 0;
voiceInfo.VibratoDelay = 0;
voiceInfo.VibratoOffset = 0;
voiceInfo.PitchBendCounter = 0;
voiceInfo.NoteSlideSpeed = 0;
voiceInfo.EnvelopeState = EnvelopeState.Attack;
voiceInfo.SustainCounter = 0;
ushort instrument = voiceInfo.CurrentInstrument;
if (instrument != 0)
{
instrument = (ushort)(instrument - 1 + voiceInfo.InstrumentTranspose);
if (instrument < instruments.Length)
{
voiceInfo.Instrument = instruments[instrument];
byte[] waveFormList = waveformInfo[voiceInfo.Instrument.WaveformListNumber];
voiceInfo.CurrentSample = waveFormList[0];
Sample sample = samples[voiceInfo.CurrentSample];
voiceInfo.SampleData = sample.SampleData;
voiceInfo.SampleLength = sample.Length;
voiceInfo.LoopSample = sample.SampleData;
voiceInfo.LoopOffset = sample.LoopStart;
voiceInfo.LoopLength = sample.LoopLength;
}
}
sbyte[] arpeggio = arpeggios[voiceInfo.Instrument.ArpeggioNumber];
int note = voiceInfo.CurrentNote + arpeggio[0];
if ((note >= 0) && (note < Tables.Periods.Length))
{
voiceInfo.OriginalNote = (ushort)note;
voiceInfo.SamplePeriod = Tables.Periods[note];
if (voiceInfo.SampleLength != 0)
{
channel.PlaySample((short)voiceInfo.CurrentSample, voiceInfo.SampleData, 0, voiceInfo.SampleLength);
if (voiceInfo.LoopLength > 2)
channel.SetLoop(voiceInfo.LoopSample, voiceInfo.LoopOffset, voiceInfo.LoopLength);
}
else
channel.Mute();
}
else
channel.Mute();
channel.SetAmigaPeriod(voiceInfo.SamplePeriod);
}
}
/********************************************************************/
/// <summary>
/// Handle effects
/// </summary>
/********************************************************************/
private void DoEffect(VoiceInfo voiceInfo, IChannel channel)
{
DoAdsrCurve(voiceInfo, channel);
DoWaveForm(voiceInfo, channel);
DoArpeggio(voiceInfo);
DoSoundTracker(voiceInfo, channel);
DoVibrato(voiceInfo);
DoPitchBend(voiceInfo);
DoNoteSlide(voiceInfo);
voiceInfo.SamplePeriod = (ushort)(voiceInfo.SamplePeriod + voiceInfo.PitchBendValue);
if (voiceInfo.SamplePeriod < 95)
voiceInfo.SamplePeriod = 95;
else if (voiceInfo.SamplePeriod > 5760)
voiceInfo.SamplePeriod = 5760;
channel.SetAmigaPeriod(voiceInfo.SamplePeriod);
}
/********************************************************************/
/// <summary>
/// Handle ADSR
/// </summary>
/********************************************************************/
private void DoAdsrCurve(VoiceInfo voiceInfo, IChannel channel)
{
Instrument instrument = voiceInfo.Instrument;
switch (voiceInfo.EnvelopeState)
{
case EnvelopeState.Attack:
{
voiceInfo.SampleVolume += instrument.AttackSpeed;
if (voiceInfo.SampleVolume >= instrument.AttackMax)
{
voiceInfo.SampleVolume = instrument.AttackMax;
voiceInfo.EnvelopeState = EnvelopeState.Decay;
}
break;
}
case EnvelopeState.Decay:
{
if (instrument.DecaySpeed == 0)
voiceInfo.EnvelopeState = EnvelopeState.Sustain;
else
{
voiceInfo.SampleVolume -= instrument.DecaySpeed;
if (voiceInfo.SampleVolume <= instrument.DecayMin)
{
voiceInfo.SampleVolume = instrument.DecayMin;
voiceInfo.EnvelopeState = EnvelopeState.Sustain;
}
}
break;
}
case EnvelopeState.Sustain:
{
if (voiceInfo.SustainCounter == instrument.SustainTime)
voiceInfo.EnvelopeState = EnvelopeState.Release;
else
voiceInfo.SustainCounter++;
break;
}
case EnvelopeState.Release:
{
if (instrument.ReleaseSpeed == 0)
voiceInfo.EnvelopeState = EnvelopeState.Done;
else
{
voiceInfo.SampleVolume -= instrument.ReleaseSpeed;
if (voiceInfo.SampleVolume <= instrument.ReleaseMin)
{
voiceInfo.SampleVolume = instrument.ReleaseMin;
voiceInfo.EnvelopeState = EnvelopeState.Done;
}
}
break;
}
}
channel.SetVolume((ushort)voiceInfo.SampleVolume);
}
/********************************************************************/
/// <summary>
/// Handle wave form list change
/// </summary>
/********************************************************************/
private void DoWaveForm(VoiceInfo voiceInfo, IChannel channel)
{
Instrument instrument = voiceInfo.Instrument;
if (instrument.WaveformListLength != 0)
{
if (voiceInfo.WaveListDelay == instrument.WaveformListDelay)
{
voiceInfo.WaveListDelay -= instrument.WaveformListSpeed;
if (voiceInfo.WaveListOffset == instrument.WaveformListLength)
voiceInfo.WaveListOffset = -1;
voiceInfo.WaveListOffset++;
sbyte waveFormValue = (sbyte)waveformInfo[instrument.WaveformListNumber][voiceInfo.WaveListOffset];
if (waveFormValue >= 0)
{
voiceInfo.CurrentSample = (ushort)waveFormValue;
Sample sample = samples[voiceInfo.CurrentSample];
voiceInfo.LoopSample = sample.SampleData;
voiceInfo.LoopOffset = sample.LoopStart;
voiceInfo.LoopLength = sample.LoopLength;
if (channel.IsActive)
{
channel.SetSample(voiceInfo.LoopSample, voiceInfo.LoopOffset, voiceInfo.LoopLength);
channel.SetLoop(voiceInfo.LoopOffset, voiceInfo.LoopLength);
}
}
else
voiceInfo.WaveListOffset--;
}
else
voiceInfo.WaveListDelay++;
}
}
/********************************************************************/
/// <summary>
/// Handle arpeggios
/// </summary>
/********************************************************************/
private void DoArpeggio(VoiceInfo voiceInfo)
{
Instrument instrument = voiceInfo.Instrument;
if (instrument.ArpeggioLength != 0)
{
if (voiceInfo.ArpeggioDelay == instrument.ArpeggioDelay)
{
voiceInfo.ArpeggioDelay -= instrument.ArpeggioSpeed;
if (voiceInfo.ArpeggioOffset == instrument.ArpeggioLength)
voiceInfo.ArpeggioOffset = -1;
voiceInfo.ArpeggioOffset++;
sbyte arpeggioValue = arpeggios[instrument.ArpeggioNumber][voiceInfo.ArpeggioOffset];
short newNote = (short)(voiceInfo.OriginalNote + arpeggioValue);
voiceInfo.SamplePeriod = Tables.Periods[newNote];
}
else
voiceInfo.ArpeggioDelay++;
}
}
/********************************************************************/
/// <summary>
/// Handle vibratos
/// </summary>
/********************************************************************/
private void DoVibrato(VoiceInfo voiceInfo)
{
Instrument instrument = voiceInfo.Instrument;
if (instrument.VibratoLength != 0)
{
if (voiceInfo.VibratoDelay == instrument.VibratoDelay)
{
voiceInfo.VibratoDelay -= instrument.VibratoSpeed;
if (voiceInfo.VibratoOffset == instrument.VibratoLength)
voiceInfo.VibratoOffset = -1;
voiceInfo.VibratoOffset++;
sbyte vibratoValue = vibratoes[instrument.VibratoNumber][voiceInfo.VibratoOffset];
voiceInfo.SamplePeriod = (ushort)(voiceInfo.SamplePeriod + vibratoValue);
}
else
voiceInfo.VibratoDelay++;
}
}
/********************************************************************/
/// <summary>
/// Handle pitch bend
/// </summary>
/********************************************************************/
private void DoPitchBend(VoiceInfo voiceInfo)
{
Instrument instrument = voiceInfo.Instrument;
if (instrument.PitchBendSpeed != 0)
{
if (voiceInfo.PitchBendCounter == instrument.PitchBendDelay)
voiceInfo.PitchBendValue = (short)(voiceInfo.PitchBendValue + instrument.PitchBendSpeed);
else
voiceInfo.PitchBendCounter++;
}
}
/********************************************************************/
/// <summary>
/// Handle note slide
/// </summary>
/********************************************************************/
private void DoNoteSlide(VoiceInfo voiceInfo)
{
if ((voiceInfo.CurrentEffect != 0) && (voiceInfo.CurrentEffect < 0x70) && (voiceInfo.CurrentEffectArg != 0))
{
voiceInfo.NoteSlideNote = Tables.Periods[voiceInfo.CurrentEffect];
int direction = voiceInfo.NoteSlideNote - voiceInfo.SamplePeriod;
if (direction == 0)
return;
short effectArg = (short)voiceInfo.CurrentEffectArg;
if (direction < 0)
effectArg = (short)-effectArg;
voiceInfo.NoteSlideSpeed = effectArg;
}
short speed = voiceInfo.NoteSlideSpeed;
if (speed != 0)
{
if (speed < 0)
{
voiceInfo.SamplePeriod = (ushort)(voiceInfo.SamplePeriod + speed);
if (voiceInfo.SamplePeriod <= voiceInfo.NoteSlideNote)
{
voiceInfo.SamplePeriod = voiceInfo.NoteSlideNote;
voiceInfo.NoteSlideSpeed = 0;
}
}
else
{
voiceInfo.SamplePeriod = (ushort)(voiceInfo.SamplePeriod + speed);
if (voiceInfo.SamplePeriod >= voiceInfo.NoteSlideNote)
{
voiceInfo.SamplePeriod = voiceInfo.NoteSlideNote;
voiceInfo.NoteSlideSpeed = 0;
}
}
}
}
/********************************************************************/
/// <summary>
/// Handle SoundTracker effects
/// </summary>
/********************************************************************/
private void DoSoundTracker(VoiceInfo voiceInfo, IChannel channel)
{
ushort effect = voiceInfo.CurrentEffect;
if (effect >= 0x70)
{
effect &= 0x0f;
if ((playingInfo.CurrentRast != 0) || (effect >= 5))
{
switch (effect)
{
// Arpeggio
case 0x0:
{
byte[] arpTab =
[
(byte)(voiceInfo.CurrentEffectArg >> 4),
0,
(byte)(voiceInfo.CurrentEffectArg & 0x0f),
0
];
byte arpValue = arpTab[playingInfo.CurrentRast2];
voiceInfo.SamplePeriod = Tables.Periods[voiceInfo.OriginalNote + arpValue];
break;
}
// Pitch up
case 0x1:
{
voiceInfo.PitchBendValue = (short)-voiceInfo.CurrentEffectArg;
break;
}
// Pitch down
case 0x2:
{
voiceInfo.PitchBendValue = (short)voiceInfo.CurrentEffectArg;
break;
}
// Volume up
case 0x3:
{
if (voiceInfo.EnvelopeState == EnvelopeState.Done)
{
if ((playingInfo.CurrentRast == 0) && (voiceInfo.CurrentInstrument != 0))
voiceInfo.SampleVolume = voiceInfo.Instrument.AttackSpeed;
short volume = (short)(voiceInfo.SampleVolume + voiceInfo.CurrentEffectArg * 4);
if (volume >= 256)
volume = 255;
voiceInfo.SampleVolume = volume;
}
break;
}
// Volume down
case 0x4:
{
if (voiceInfo.EnvelopeState == EnvelopeState.Done)
{
if ((playingInfo.CurrentRast == 0) && (voiceInfo.CurrentInstrument != 0))
voiceInfo.SampleVolume = voiceInfo.Instrument.AttackSpeed;
short volume = (short)(voiceInfo.SampleVolume - voiceInfo.CurrentEffectArg * 4);
if (volume < 0)
volume = 0;
voiceInfo.SampleVolume = volume;
}
break;
}
// Set ADSR attack
case 0x5:
{
Instrument instrument = voiceInfo.Instrument;
instrument.AttackMax = (byte)voiceInfo.CurrentEffectArg;
instrument.AttackSpeed = (byte)voiceInfo.CurrentEffectArg;
break;
}
// Set pattern length
case 0x6:
{
if (voiceInfo.CurrentEffectArg != 0)
playingInfo.PatternLength = (byte)voiceInfo.CurrentEffectArg;
break;
}
// Volume change
case 0xc:
{
ushort volume = voiceInfo.CurrentEffectArg;
channel.SetAmigaVolume((ushort)(volume > 64 ? 64 : volume));
volume *= 4;
if (volume >= 255)
volume = 255;
voiceInfo.SampleVolume = (short)volume;
break;
}
// Speed change
case 0xf:
{
byte speed = (byte)(voiceInfo.CurrentEffectArg & 0x0f);
if ((speed != 0) && (speed != playingInfo.Speed))
{
playingInfo.Speed = speed;
ShowSpeed();
}
break;
}
}
}
}
}
/********************************************************************/
/// <summary>
/// Will update the module information with current song positions
/// </summary>
/********************************************************************/
private void ShowSongPositions()
{
OnModuleInfoChanged(InfoPositionLine, playingInfo.CurrentPosition.ToString());
}
/********************************************************************/
/// <summary>
/// Will update the module information with track numbers
/// </summary>
/********************************************************************/
private void ShowTracks()
{
OnModuleInfoChanged(InfoTrackLine, FormatTracks());
}
/********************************************************************/
/// <summary>
/// Will update the module information with current speed
/// </summary>
/********************************************************************/
private void ShowSpeed()
{
OnModuleInfoChanged(InfoSpeedLine, playingInfo.Speed.ToString());
}
/********************************************************************/
/// <summary>
/// Will update the module information with all dynamic values
/// </summary>
/********************************************************************/
private void UpdateModuleInformation()
{
ShowSongPositions();
ShowTracks();
ShowSpeed();
}
/********************************************************************/
/// <summary>
/// Return a string containing the playing tracks
/// </summary>
/********************************************************************/
private string FormatTracks()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++)
{
sb.Append(playingInfo.VoiceInfo[i].SequenceList[playingInfo.CurrentPosition].TrackNumber);
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
return sb.ToString();
}
#endregion
}
}
| 0 | 0.789372 | 1 | 0.789372 | game-dev | MEDIA | 0.470234 | game-dev,audio-video-media | 0.903901 | 1 | 0.903901 |
LiXizhi/NPLRuntime | 3,293 | Client/trunk/externals/bullet-2.75/src/BulletCollision/CollisionDispatch/btManifoldResult.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 MANIFOLD_RESULT_H
#define MANIFOLD_RESULT_H
class btCollisionObject;
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btManifoldPoint;
#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
#include "LinearMath/btTransform.h"
typedef bool (*ContactAddedCallback)(btManifoldPoint& cp, const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1);
extern ContactAddedCallback gContactAddedCallback;
//#define DEBUG_PART_INDEX 1
///btManifoldResult is a helper class to manage contact results.
class btManifoldResult : public btDiscreteCollisionDetectorInterface::Result
{
btPersistentManifold* m_manifoldPtr;
//we need this for compounds
btTransform m_rootTransA;
btTransform m_rootTransB;
btCollisionObject* m_body0;
btCollisionObject* m_body1;
int m_partId0;
int m_partId1;
int m_index0;
int m_index1;
public:
btManifoldResult()
#ifdef DEBUG_PART_INDEX
:
m_partId0(-1),
m_partId1(-1),
m_index0(-1),
m_index1(-1)
#endif //DEBUG_PART_INDEX
{
}
btManifoldResult(btCollisionObject* body0,btCollisionObject* body1);
virtual ~btManifoldResult() {};
void setPersistentManifold(btPersistentManifold* manifoldPtr)
{
m_manifoldPtr = manifoldPtr;
}
const btPersistentManifold* getPersistentManifold() const
{
return m_manifoldPtr;
}
btPersistentManifold* getPersistentManifold()
{
return m_manifoldPtr;
}
virtual void setShapeIdentifiersA(int partId0,int index0)
{
m_partId0=partId0;
m_index0=index0;
}
virtual void setShapeIdentifiersB( int partId1,int index1)
{
m_partId1=partId1;
m_index1=index1;
}
virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth);
SIMD_FORCE_INLINE void refreshContactPoints()
{
btAssert(m_manifoldPtr);
if (!m_manifoldPtr->getNumContacts())
return;
bool isSwapped = m_manifoldPtr->getBody0() != m_body0;
if (isSwapped)
{
m_manifoldPtr->refreshContactPoints(m_rootTransB,m_rootTransA);
} else
{
m_manifoldPtr->refreshContactPoints(m_rootTransA,m_rootTransB);
}
}
const btCollisionObject* getBody0Internal() const
{
return m_body0;
}
const btCollisionObject* getBody1Internal() const
{
return m_body1;
}
};
#endif //MANIFOLD_RESULT_H
| 0 | 0.958413 | 1 | 0.958413 | game-dev | MEDIA | 0.974054 | game-dev | 0.958731 | 1 | 0.958731 |
kripken/intensityengine | 2,278 | src/thirdparty/bullet/src/BulletMultiThreaded/btParallelConstraintSolver.cpp | /*
Copyright (C) 2010 Sony Computer Entertainment Inc.
All rights reserved.
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 "btParallelConstraintSolver.h"
#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
btParallelConstraintSolver::btParallelConstraintSolver()
{
//initialize MiniCL here
}
btParallelConstraintSolver::~btParallelConstraintSolver()
{
//exit MiniCL
}
btScalar btParallelConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
{
{
int i;
btPersistentManifold* manifold = 0;
// btCollisionObject* colObj0=0,*colObj1=0;
for (i=0;i<numManifolds;i++)
{
manifold = manifoldPtr[i];
convertContact(manifold,infoGlobal);
}
}
btContactSolverInfo info = infoGlobal;
int numConstraintPool = m_tmpSolverContactConstraintPool.size();
int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
///@todo: use stack allocator for such temporarily memory, same for solver bodies/constraints
m_orderTmpConstraintPool.resize(numConstraintPool);
m_orderFrictionConstraintPool.resize(numFrictionPool);
{
int i;
for (i=0;i<numConstraintPool;i++)
{
m_orderTmpConstraintPool[i] = i;
}
for (i=0;i<numFrictionPool;i++)
{
m_orderFrictionConstraintPool[i] = i;
}
}
return 0.f;
}
| 0 | 0.658403 | 1 | 0.658403 | game-dev | MEDIA | 0.83635 | game-dev | 0.681814 | 1 | 0.681814 |
pixel-quest/pixel-games | 24,770 | games/dance_v2/dance_v2.lua | --[[
Название: Танцы (Версия 2)
Автор: Avondale, дискорд - avonda
Описание механики:
Идеи по доработке:
]]
math.randomseed(os.time())
require("avonlib")
local CLog = require("log")
local CInspect = require("inspect")
local CHelp = require("help")
local CJson = require("json")
local CTime = require("time")
local CAudio = require("audio")
local CColors = require("colors")
local tGame = {
Cols = 24,
Rows = 15,
Buttons = {},
}
local tConfig = {}
-- стейты или этапы игры
local GAMESTATE_SETUP = 1
local GAMESTATE_GAME = 2
local GAMESTATE_POSTGAME = 3
local GAMESTATE_FINISH = 4
local bGamePaused = false
local iGameState = GAMESTATE_SETUP
local iPrevTickTime = 0
local tGameStats = {
StageLeftDuration = 0,
StageTotalDuration = 0,
CurrentStars = 0,
TotalStars = 0,
CurrentLives = 0,
TotalLives = 0,
Players = { -- максимум 6 игроков
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
{ Score = 0, Lives = 0, Color = CColors.NONE },
},
TargetScore = 1,
StageNum = 0,
TotalStages = 0,
TargetColor = CColors.NONE,
ScoreboardVariant = 7,
}
local tGameResults = {
Won = false,
AfterDelay = false,
PlayersCount = 0,
Score = 0,
Color = CColors.NONE,
}
local tFloor = {}
local tButtons = {}
local tFloorStruct = {
iColor = CColors.NONE,
iBright = CColors.BRIGHT0,
bClick = false,
bDefect = false,
iWeight = 0,
iPixelID = 0
}
local tButtonStruct = {
bClick = false,
bDefect = false,
}
local bAnyButtonClick = false
local tPlayerInGame = {}
local tTeamColors = {}
tTeamColors[1] = CColors.BLUE
tTeamColors[2] = CColors.MAGENTA
tTeamColors[3] = CColors.CYAN
tTeamColors[4] = CColors.WHITE
tTeamColors[5] = CColors.YELLOW
tTeamColors[6] = CColors.GREEN
function StartGame(gameJson, gameConfigJson)
tGame = CJson.decode(gameJson)
tConfig = CJson.decode(gameConfigJson)
for iX = 1, tGame.Cols do
tFloor[iX] = {}
for iY = 1, tGame.Rows do
tFloor[iX][iY] = CHelp.ShallowCopy(tFloorStruct)
end
end
for _, iId in pairs(tGame.Buttons) do
tButtons[iId] = CHelp.ShallowCopy(tButtonStruct)
end
iPrevTickTime = CTime.unix()
local err = CAudio.PreloadFile("audio_v2/"..tGame["SongName"])
if err ~= nil then error(err); end
if AL.RoomHasNFZ(tGame) then
AL.LoadNFZInfo()
end
tGame.iMinX = 1
tGame.iMinY = 1
tGame.iMaxX = tGame.Cols
tGame.iMaxY = tGame.Rows
if AL.NFZ.bLoaded then
tGame.iMinX = AL.NFZ.iMinX
tGame.iMinY = AL.NFZ.iMinY
tGame.iMaxX = AL.NFZ.iMaxX
tGame.iMaxY = AL.NFZ.iMaxY
tGame.CenterX = AL.NFZ.iCenterX
tGame.CenterY = AL.NFZ.iCenterY
end
tGame.StartPositions = {}
tGame.StartPositionsSizeX = 4
tGame.StartPositionsSizeY = tGame.iMaxY - tGame.iMinY + 1
if tConfig.SmallZones then
tGame.StartPositionsSizeY = math.floor(tGame.iMaxY/2) - math.floor(tGame.iMinY/2)
end
local iStartX = math.floor((tGame.Cols - (tGame.iMaxX-tGame.iMinX))/2) + tGame.iMinX
if tGame.ArenaMode then iStartX = iStartX + 1; end
local iX = iStartX
local iY = tGame.iMinY
for iPlayerID = 1, 6 do
tGame.StartPositions[iPlayerID] = {}
tGame.StartPositions[iPlayerID].X = iX
tGame.StartPositions[iPlayerID].Y = iY
tGame.StartPositions[iPlayerID].Color = tTeamColors[iPlayerID]
if not tGame.ArenaMode then
iX = iX + tGame.StartPositionsSizeX + 1
if iX + tGame.StartPositionsSizeX-1 > tGame.iMaxX then
iX = iStartX
iY = iY + tGame.StartPositionsSizeY+1
if iY > tGame.iMaxY then break; end
end
else
iX = iX + 6
if iX > tGame.iMaxX then break; end
end
end
CPixels.PIXEL_START_Y = tGame.StartPositionsSizeY
CGameMode.Announcer()
end
function NextTick()
if iGameState == GAMESTATE_SETUP then
GameSetupTick()
end
if iGameState == GAMESTATE_GAME then
GameTick()
end
if iGameState == GAMESTATE_POSTGAME then
PostGameTick()
if not tGameResults.AfterDelay then
tGameResults.AfterDelay = true
return tGameResults
end
end
if iGameState == GAMESTATE_FINISH then
tGameResults.AfterDelay = false
return tGameResults
end
AL.CountTimers((CTime.unix() - iPrevTickTime) * 1000)
iPrevTickTime = CTime.unix()
end
function GameSetupTick()
SetGlobalColorBright(CColors.WHITE, tConfig.Bright-1)
if not CGameMode.bCountDownStarted then SetAllButtonColorBright(CColors.BLUE, tConfig.Bright, true) end
CPaint.PlayerZones()
local iPlayersReady = 0
for iPlayerID = 1, #tGame.StartPositions do
if CheckPositionClick(tGame.StartPositions[iPlayerID], tGame.StartPositionsSizeX, tGame.StartPositionsSizeY) then
tPlayerInGame[iPlayerID] = true
tGameStats.Players[iPlayerID].Color = tGame.StartPositions[iPlayerID].Color
elseif not CGameMode.bCountDownStarted then
AL.NewTimer(250, function()
if not CheckPositionClick(tGame.StartPositions[iPlayerID], tGame.StartPositionsSizeX, tGame.StartPositionsSizeY) and not CGameMode.bCountDownStarted then
tPlayerInGame[iPlayerID] = false
tGameStats.Players[iPlayerID].Color = CColors.NONE
end
end)
end
if tPlayerInGame[iPlayerID] then iPlayersReady = iPlayersReady + 1; end
end
if bAnyButtonClick or ((iPlayersReady > 1 or iPlayersReady == #tGame.StartPositions) and CGameMode.bCanAutoStart) then
bAnyButtonClick = false
if iPlayersReady < 1 or CGameMode.bCountDownStarted then return; end
CGameMode.StartCountDown(10)
end
tGameResults.PlayersCount = iPlayersReady
end
function GameTick()
SetGlobalColorBright(CColors.WHITE, tConfig.Bright-2)
SetAllButtonColorBright(CColors.NONE, 0, false)
CPaint.PlayerZones()
CPaint.Pixels()
end
function PostGameTick()
end
function RangeFloor(setPixel, setButton)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
setPixel(iX , iY, tFloor[iX][iY].iColor, tFloor[iX][iY].iBright)
end
end
for i, tButton in pairs(tButtons) do
setButton(i, tButton.iColor, tButton.iBright)
end
end
function SwitchStage()
end
--GAMEMODE
CGameMode = {}
CGameMode.iCountdown = 0
CGameMode.bCountDownStarted = false
CGameMode.bCanAutoStart = false
CGameMode.iWinnerID = 0
CGameMode.Announcer = function()
CAudio.PlayVoicesSync("dance2/dance2_guide.mp3")
CAudio.PlayVoicesSync("choose-color.mp3")
AL.NewTimer(CAudio.GetVoicesDuration("dance2/dance2_guide.mp3") * 1000, function()
CGameMode.bCanAutoStart = true
end)
end
CGameMode.StartCountDown = function(iCountDownTime)
CGameMode.bCountDownStarted = true
CGameMode.iCountdown = iCountDownTime
AL.NewTimer(1000, function()
CAudio.ResetSync()
tGameStats.StageLeftDuration = CGameMode.iCountdown
if CGameMode.iCountdown <= 0 then
CGameMode.StartGame()
return nil
else
CAudio.PlayLeftAudio(CGameMode.iCountdown)
CGameMode.iCountdown = CGameMode.iCountdown - 1
return 1000
end
end)
end
CGameMode.StartGame = function()
iGameState = GAMESTATE_GAME
CAudio.PlayDanceSync(tGame["SongName"])
CGameMode.LoadSongPixels()
AL.NewTimer(0, function()
CPixels.PixelMovement()
return tConfig.PixelMoveDelayMS
end)
AL.NewTimer(1000, function()
tGameStats.StageLeftDuration = tGameStats.StageLeftDuration - 1
if tGameStats.StageLeftDuration <= 0 then
CGameMode.EndGame()
return nil
end
return 1000
end)
end
CGameMode.EndGame = function()
local iMaxScore = -1
for i = 1, #tGame.StartPositions do
if tPlayerInGame[i] and tGameStats.Players[i] and tGameStats.Players[i].Score > iMaxScore then
iMaxScore = tGameStats.Players[i].Score
CGameMode.iWinnerID = i
end
end
tGameResults.Color = tGameStats.Players[CGameMode.iWinnerID].Color
tGameResults.Won = true
CAudio.PlaySystemSyncFromScratch(CAudio.GAME_SUCCESS)
CAudio.PlaySyncColorSound(tGameStats.Players[CGameMode.iWinnerID].Color)
CAudio.PlayVoicesSync(CAudio.VICTORY)
iGameState = GAMESTATE_POSTGAME
SetGlobalColorBright(tGameStats.Players[CGameMode.iWinnerID].Color, tConfig.Bright)
AL.NewTimer(10000, function()
iGameState = GAMESTATE_FINISH
end)
end
CGameMode.LoadSongPixels = function()
for iBatchID = 1, #tGame.Song+1 do
if tGame.Song[iBatchID] then
AL.NewTimer(tConfig.SongStartDelayMS + (tGame.Song[iBatchID][1] + tConfig.PixelMoveDelayMS), function()
CGameMode.SpawnBatch(iBatchID)
end)
if iBatchID > 1 and tGame.Song[iBatchID-1][1] + 500 < tGame.Song[iBatchID][1] then
AL.NewTimer((tGame.Song[iBatchID-1][1] - tConfig.PixelMoveDelayMS + 250), function()
tGame.Song[-1] = {1, "H", "H", "H", "H"}
CGameMode.SpawnBatch(-1)
end)
end
if iBatchID == #tGame.Song then
tGame.Song[iBatchID+1] = {tGame.Song[iBatchID][1]+1000, "F", "F", "F", "F"}
tGameStats.StageLeftDuration = math.floor(tGame.Song[iBatchID][1]/1000) + 10
end
end
end
end
CGameMode.SpawnBatch = function(iBatchID)
local iBatchPixelCount = 0
for i = 2, #tGame.Song[iBatchID] do
if tGame.Song[iBatchID][i] and tGame.Song[iBatchID][i] ~= "N" then
iBatchPixelCount = iBatchPixelCount + 1
local iPixelX = i
CPixels.tPixelFactory[iPixelX] = nil
local iPixelType = CPixels.PIXEL_TYPE_NORMAL
if string.match(tGame.Song[iBatchID][i], "P" ) then
iPixelType = CPixels.PIXEL_TYPE_LONG
end
local iVelX = 0
--[[
if iBatchPixelCount == 1 and i == #tGame.Song[iBatchID] and (math.random(1,100) >= 80) then
iVelX = -1
end
]]
local iColor = CColors.GREEN
local bBad = false
if string.match(tGame.Song[iBatchID][i], "L") then
iColor = CColors.GREEN
elseif string.match(tGame.Song[iBatchID][i], "R") then
iColor = CColors.YELLOW
elseif string.match(tGame.Song[iBatchID][i], "F") then
iColor = CColors.WHITE
end
if string.match(tGame.Song[iBatchID][i], "H") then
iColor = CColors.RED
bBad = true
end
CGameMode.SpawnPixelForAllPlayers(iPixelType, iPixelX, iVelX, iColor, bBad)
end
end
end
CGameMode.SpawnPixelForAllPlayers = function(iPixelType, iPixelX, iVelX, iColor, bBad)
local iVelY = 1
if CPixels.PIXEL_START_Y > tGame.StartPositionsSizeY/2 then iVelY = -1; end
for iPlayerID = 1, #tGame.StartPositions do
if tPlayerInGame[iPlayerID] then
CPixels.SpawnPixel(iPlayerID, iPixelType, iPixelX, iVelX, iVelY, iColor, bBad)
end
end
end
CGameMode.AddPlayerScore = function(iPlayerID, iScore)
tGameResults.Score = tGameResults.Score + iScore
tGameStats.Players[iPlayerID].Score = tGameStats.Players[iPlayerID].Score + iScore
if tGameStats.TargetScore < tGameStats.Players[iPlayerID].Score then
tGameStats.TargetScore = tGameStats.Players[iPlayerID].Score
end
end
--//
--Song Pixels
CPixels = {}
CPixels.tPixels = {}
CPixels.tPixelFactory = {}
CPixels.PIXEL_START_Y = 0
CPixels.PIXEL_TYPE_NORMAL = 1
CPixels.PIXEL_TYPE_LONG = 2
CPixels.SpawnPixel = function(iPlayerID, iPixelType, iPixelX, iVelX, iVelY, iColor, bBad)
local iPixelID = #CPixels.tPixels+1
CPixels.tPixels[iPixelID] = {}
CPixels.tPixels[iPixelID].iPlayerID = iPlayerID
CPixels.tPixels[iPixelID].iX = tGame.StartPositions[iPlayerID].X + iPixelX-2
CPixels.tPixels[iPixelID].iY = tGame.StartPositions[iPlayerID].Y + CPixels.PIXEL_START_Y -1
CPixels.tPixels[iPixelID].iVelX = iVelX
CPixels.tPixels[iPixelID].iVelY = iVelY
CPixels.tPixels[iPixelID].iColor = iColor
CPixels.tPixels[iPixelID].iPixelType = iPixelType
CPixels.tPixels[iPixelID].bBad = bBad
CPixels.tPixels[iPixelID].bCollected = false
if iPixelType == CPixels.PIXEL_TYPE_LONG then
CPixels.tPixelFactory[iPixelX] = {}
CPixels.tPixelFactory[iPixelX].iVelX = iVelX
CPixels.tPixelFactory[iPixelX].iColor = iColor
CPixels.tPixelFactory[iPixelX].bBad = bBad
end
if CPixels.tPixels[iPixelID].iColor == tGame.StartPositions[iPlayerID].Color then
CPixels.tPixels[iPixelID].iColor = CColors.BLUE
end
end
CPixels.PixelMovement = function()
for iPixelID = 1, #CPixels.tPixels do
if CPixels.tPixels[iPixelID] then
local iPlayerID = CPixels.tPixels[iPixelID].iPlayerID
CPixels.tPixels[iPixelID].iY = CPixels.tPixels[iPixelID].iY + CPixels.tPixels[iPixelID].iVelY
if CPixels.tPixels[iPixelID].iY > tGame.StartPositions[iPlayerID].Y-1 and CPixels.tPixels[iPixelID].iY <= tGame.StartPositions[iPlayerID].Y + tGame.StartPositionsSizeY-1 then
if CPixels.tPixels[iPixelID].iVelX ~= 0 then
CPixels.tPixels[iPixelID].iX = CPixels.tPixels[iPixelID].iX + CPixels.tPixels[iPixelID].iVelX
if CPixels.tPixels[iPixelID].iX < tGame.StartPositions[iPlayerID].X or CPixels.tPixels[iPixelID].iX >= tGame.StartPositions[iPlayerID].X + tGame.StartPositionsSizeX then
CPixels.tPixels[iPixelID].iVelX = -CPixels.tPixels[iPixelID].iVelX
CPixels.tPixels[iPixelID].iX = CPixels.tPixels[iPixelID].iX + (CPixels.tPixels[iPixelID].iVelX*2)
end
end
if tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY].bClick and tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY].iWeight > 5 then
CPixels.PlayerCollectPixel(iPixelID)
end
else
CPixels.tPixels[iPixelID] = nil
end
end
end
for iPixelFactoryID = 2, tGame.StartPositionsSizeX+1 do
if CPixels.tPixelFactory[iPixelFactoryID] ~= nil then
CGameMode.SpawnPixelForAllPlayers(CPixels.PIXEL_TYPE_NORMAL, iPixelFactoryID, CPixels.tPixelFactory[iPixelFactoryID].iVelX, CPixels.tPixelFactory[iPixelFactoryID].iColor, CPixels.tPixelFactory[iPixelFactoryID].bBad)
end
end
end
CPixels.PlayerCollectPixel = function(iPixelID)
if CPixels.tPixels[iPixelID] and not CPixels.tPixels[iPixelID].bCollected then
CPixels.tPixels[iPixelID].bCollected = true
CPixels.tPixels[iPixelID].iColor = tGameStats.Players[CPixels.tPixels[iPixelID].iPlayerID].Color
if not CPixels.tPixels[iPixelID].bBad then
CGameMode.AddPlayerScore(CPixels.tPixels[iPixelID].iPlayerID, 1)
else
CGameMode.AddPlayerScore(CPixels.tPixels[iPixelID].iPlayerID, -5)
end
end
end
--//
--PAINT
CPaint = {}
CPaint.PlayerZones = function()
for iPlayerID = 1, #tGame.StartPositions do
if iGameState == GAMESTATE_SETUP then
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositions[iPlayerID].X + tGame.StartPositionsSizeX-1 do
for iY = tGame.StartPositions[iPlayerID].Y, tGame.StartPositions[iPlayerID].Y + tGame.StartPositionsSizeY-1 do
tFloor[iX][iY].iColor = tGame.StartPositions[iPlayerID].Color
tFloor[iX][iY].iBright = tConfig.Bright
if not tPlayerInGame[iPlayerID] then
tFloor[iX][iY].iBright = tConfig.Bright-3
end
end
end
if tPlayerInGame[iPlayerID] and tGameStats.StageLeftDuration > 0 and tGameStats.StageLeftDuration < 10 then
local iStartX = tGame.StartPositions[iPlayerID].X + tGame.StartPositionsSizeX-1
local iStartY = tGame.StartPositions[iPlayerID].Y + math.floor(tGame.StartPositionsSizeY/2) + 2
local iX = iStartX
local iY = iStartY
for iLetterX = 1, tLoadedLetters[tGameStats.StageLeftDuration].iSizeX do
for iLetterY = 1, tLoadedLetters[tGameStats.StageLeftDuration].iSizeY do
if tLoadedLetters[tGameStats.StageLeftDuration].tPaint[iLetterY][iLetterX] > 0 then
tFloor[iX][iY].iColor = CColors.RED
tFloor[iX][iY].iBright = tConfig.Bright
end
iY = iY-1
end
iX = iX - 1
iY = iStartY
if iX < tGame.StartPositions[iPlayerID].X then
iX = iStartX
end
end
end
else
for iX = tGame.StartPositions[iPlayerID].X, tGame.StartPositions[iPlayerID].X + tGame.StartPositionsSizeX-1 do
for iY = tGame.StartPositions[iPlayerID].Y, tGame.StartPositions[iPlayerID].Y + tGame.StartPositionsSizeY-1 do
tFloor[iX][iY].iColor = tGame.StartPositions[iPlayerID].Color
tFloor[iX][iY].iBright = 1
if not tPlayerInGame[iPlayerID] then
tFloor[iX][iY].iColor = CColors.NONE
end
end
end
end
end
end
CPaint.Pixels = function()
for iPixelID = 1, #CPixels.tPixels do
if CPixels.tPixels[iPixelID] then
if tFloor[CPixels.tPixels[iPixelID].iX] and tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY] then
tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY].iColor = CPixels.tPixels[iPixelID].iColor
tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY].iBright = tConfig.Bright
tFloor[CPixels.tPixels[iPixelID].iX][CPixels.tPixels[iPixelID].iY].iPixelID = iPixelIDP
end
end
end
end
--//
--UTIL прочие утилиты
function CheckPositionClick(tStart, iSizeX, iSizeY)
for iX = tStart.X, tStart.X + iSizeX - 1 do
for iY = tStart.Y, tStart.Y + iSizeY - 1 do
if tFloor[iX] and tFloor[iX][iY] then
if tFloor[iX][iY].bClick then
return true
end
end
end
end
return false
end
function SetPositionColorBright(tStart, iSize, iColor, iBright)
for i = 0, iSize * iSize - 1 do
local iX = tStart.X + i % iSize
local iY = tStart.Y + math.floor(i / iSize)
if not (iX < 1 or iX > tGame.Cols or iY < 1 or iY > tGame.Rows) then
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
end
function SetRectColorBright(iX, iY, iSizeX, iSizeY, iColor, iBright)
for i = iX, iX + iSizeX do
for j = iY, iY + iSizeY do
if not (i < 1 or i > tGame.Cols or j < 1 or j > tGame.Rows) and not tFloor[i][j].bAnimated then
tFloor[i][j].iColor = iColor
tFloor[i][j].iBright = iBright
end
end
end
end
function SetGlobalColorBright(iColor, iBright)
for iX = 1, tGame.Cols do
for iY = 1, tGame.Rows do
tFloor[iX][iY].iColor = iColor
tFloor[iX][iY].iBright = iBright
end
end
for i, tButton in pairs(tButtons) do
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
function SetAllButtonColorBright(iColor, iBright, bCheckDefect)
for i, tButton in pairs(tButtons) do
if not bCheckDefect or not tButtons[i].bDefect then
tButtons[i].iColor = iColor
tButtons[i].iBright = iBright
end
end
end
--//
--//
function GetStats()
return tGameStats
end
function PauseGame()
bGamePaused = true
end
function ResumeGame()
bGamePaused = false
iPrevTickTime = CTime.unix()
end
function PixelClick(click)
if tFloor[click.X] and tFloor[click.X][click.Y] then
if bGamePaused then
tFloor[click.X][click.Y].bClick = false
return;
end
if iGameState == GAMESTATE_SETUP then
if click.Click then
tFloor[click.X][click.Y].bClick = true
tFloor[click.X][click.Y].bHold = false
elseif not tFloor[click.X][click.Y].bHold then
AL.NewTimer(500, function()
if not tFloor[click.X][click.Y].bHold then
tFloor[click.X][click.Y].bHold = true
AL.NewTimer(750, function()
if tFloor[click.X][click.Y].bHold then
tFloor[click.X][click.Y].bClick = false
end
end)
end
end)
end
tFloor[click.X][click.Y].iWeight = click.Weight
return
end
tFloor[click.X][click.Y].bClick = click.Click
tFloor[click.X][click.Y].iWeight = click.Weight
if iGameState == GAMESTATE_GAME then
if click.Click and not tFloor[click.X][click.Y].bDefect then
if tFloor[click.X][click.Y].iPixelID and tFloor[click.X][click.Y].iPixelID > 0 then
CPixels.PlayerCollectPixel(tFloor[click.X][click.Y].iPixelID)
end
end
end
end
end
function DefectPixel(defect)
if tFloor[defect.X] and tFloor[defect.X][defect.Y] then
tFloor[defect.X][defect.Y].bDefect = defect.Defect
end
end
function ButtonClick(click)
if tButtons[click.Button] == nil or bGamePaused or tButtons[click.Button].bDefect then return end
tButtons[click.Button].bClick = click.Click
if click.Click and not tButtons[click.Button].bDefect then
bAnyButtonClick = true
end
end
function DefectButton(defect)
if tButtons[defect.Button] == nil then return end
tButtons[defect.Button].bDefect = defect.Defect
if defect.Defect then
tButtons[defect.Button].iColor = CColors.NONE
tButtons[defect.Button].iBright = CColors.BRIGHT0
end
end
tLoadedLetters = {}
tLoadedLetters[1] =
{
iSizeX = 3,
iSizeY = 5,
tPaint = {
{0, 1, 0,},
{1, 1, 0,},
{0, 1, 0,},
{0, 1, 0,},
{1, 1, 1,}
}
}
tLoadedLetters[2] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{0, 0, 1, 0},
{0, 1, 0, 0},
{1, 1, 1, 1}
}
}
tLoadedLetters[3] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{0, 0, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 0}
}
}
tLoadedLetters[4] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 0, 1, 0},
{0, 1, 1, 0},
{1, 0, 1, 0},
{1, 1, 1, 1},
{0, 0, 1, 0}
}
}
tLoadedLetters[5] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{1, 1, 1, 1},
{1, 0, 0, 0},
{1, 1, 1, 0},
{0, 0, 0, 1},
{1, 1, 1, 0}
}
}
tLoadedLetters[6] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 1, 1, 0},
{1, 0, 0, 0},
{1, 1, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 0}
}
}
tLoadedLetters[7] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{1, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 1, 0},
{0, 0, 1, 0}
}
}
tLoadedLetters[8] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 0}
}
}
tLoadedLetters[9] =
{
iSizeX = 4,
iSizeY = 5,
tPaint = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 1, 0}
}
} | 0 | 0.539683 | 1 | 0.539683 | game-dev | MEDIA | 0.76598 | game-dev | 0.835322 | 1 | 0.835322 |
DanceManiac/Advanced-X-Ray-Public | 1,669 | SourcesAXR/xrGame/ai/monsters/pseudogigant/pseudo_gigant.h | #pragma once
#include "../BaseMonster/base_monster.h"
#include "../controlled_entity.h"
#include "../../../../xrServerEntities/script_export_space.h"
class CPseudoGigant : public CBaseMonster,
public CControlledEntity<CPseudoGigant> {
typedef CBaseMonster inherited;
typedef CControlledEntity<CPseudoGigant> CControlled;
private:
xr_vector<CObject*> m_nearest;
// step_effector
struct {
float time;
float amplitude;
float period_number;
} step_effector;
SAttackEffector m_threaten_effector;
ref_sound m_sound_threaten_hit; // ,
ref_sound m_sound_start_threaten; // ,
u32 m_time_next_threaten;
u32 m_threaten_delay_min;
u32 m_threaten_delay_max;
float m_threaten_dist_min;
float m_threaten_dist_max;
float m_kick_damage;
u32 m_time_kick_actor_slow_down;
SVelocityParam m_fsVelocityJumpPrepare;
SVelocityParam m_fsVelocityJumpGround;
LPCSTR m_kick_particles;
public:
CPseudoGigant ();
virtual ~CPseudoGigant ();
virtual void Load (LPCSTR section);
virtual void reinit ();
virtual bool ability_earthquake () {return true;}
virtual void event_on_step ();
virtual bool check_start_conditions (ControlCom::EControlType type);
virtual void on_activate_control (ControlCom::EControlType);
virtual void on_threaten_execute ();
virtual void HitEntityInJump (const CEntity *pEntity);
virtual void TranslateActionToPathParams ();
virtual char* get_monster_class_name () { return "pseudogigant"; }
DECLARE_SCRIPT_REGISTER_FUNCTION
};
add_to_type_list(CPseudoGigant)
#undef script_type_list
#define script_type_list save_type_list(CPseudoGigant)
| 0 | 0.63978 | 1 | 0.63978 | game-dev | MEDIA | 0.984158 | game-dev | 0.518304 | 1 | 0.518304 |
jswigart/omni-bot | 17,259 | Installer/Files/et/nav/alchemycastle_b3.gm | //script created by palota
global Map =
{
BoatPos = -1,
tankDamaged = true,
sideWallDestroyed = false,
entranceBlown = false,
bridgeBuilt = false,
ShowMovers = false,
Movers = { "MOVER_tank", "MOVER_boat1_move", },
NavDoor = function(_this)
{
wpinfo = _this.navigation.wpinfo;
if(wpinfo==null)
{
wpinfo = Util.WpNameInfo(_this.CurrentNavigation);
_this.navigation.wpinfo = wpinfo;
}
pos = wpinfo.position;
vec = wpinfo.facing.Normalize();
pos1 = pos - vec * 50;
pos1 = Vector3(pos1.x, pos1.y, pos.z);
pos2 = pos + vec * 140;
pos2 = Vector3(pos2.x, pos2.y, pos.z);
for(i=0; i<4; i+=1)
{
if(_this.Goto(pos) == EVENT.PATH_FAILED )
{
return;
}
_this.AddAimRequest(Priority.High, "facing", wpinfo.facing);
tr = TraceLine(pos, pos2, null, TRACE.SOLID, 0, true);
if(tr.fraction == 1)
{
_this.Bot.MoveTowards(pos2);
sleep(0.8);
break;
}
sleep(0.1);
_this.Bot.PressButton(BTN.USE);
_this.Bot.MoveTowards(pos1);
//wait while door opens
sleep(1);
}
},
Nav_well_down = function(_this,x,y)
{
_this.AddAimRequest(Priority.High, "facing", Vector3(x,y,1.5));
sleep(0.5);
_this.Bot.HoldButton(BTN.BACKWARD, 3.7);
sleep(3.7);
},
Navigation =
{
axis_door1 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
axis_door2 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
axis_door3 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
axis_door4 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
axis_door5 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
axis_door6 =
{
navigate = function(_this) { Map.NavDoor(_this); },
},
/*documents =
{
gotowp = "doc",
navigate = function(_this)
{
for(i=0; i<40 && !_this.Bot.HasEntityFlag(ENTFLAG.CARRYINGGOAL); i+=1){
_this.Bot.MoveTowards(_this.wpinfo.position);
_this.AddAimRequest(Priority.High, "facing", _this.wpinfo.facing);
_this.Bot.PressButton(BTN.USE);
sleep(0.3);
}
}
},*/
water_trap =
{
navigate = function(_this)
{
_this.Bot.HoldButton(BTN.JUMP, 4);
_this.Bot.HoldButton(BTN.STRAFE_R, 4);
_this.Bot.HoldButton(BTN.FORWARD, 4);
sleep(4);
}
},
roof_hole =
{
navigate = function(_this)
{
for(j=0; j<10 && _this.Bot.GetPosition().x > -4800; j+=1){
_this.Bot.HoldButton(BTN.JUMP, 1);
sleep(1);
}
}
},
tower_ladder =
{
navigate = function(_this)
{
_this.AddAimRequest(Priority.High, "facing", Vector3(-1,0,1));
_this.Bot.HoldButton(BTN.FORWARD, 1);
sleep(1);
_this.Bot.HoldButton(BTN.CROUCH, 1);
_this.Bot.HoldButton(BTN.BACKWARD, 2);
sleep(2);
}
},
well_north =
{
navigate = function(_this)
{
Map.Nav_well_down(_this, 1, 0);
}
},
well_west =
{
navigate = function(_this)
{
Map.Nav_well_down(_this, 0, -1);
}
},
well_east =
{
navigate = function(_this)
{
Map.Nav_well_down(_this, -1, 0);
}
},
},
RideMovers =
{
boat =
{
movergoal = "MOVER_boat1_move",
rideposition = Vector3(0,0,39),
startwp = "boat_start",
exitwp = "boat_end",
stance = BTN.CROUCH,
board = function(_this)
{
return Map.BoatPos == 1;
},
leave = function(_this)
{
if(_this.Bot.GetPosition().z < 630){
_this.Finished();
return true;
}
return Map.BoatPos == 2;
},
},
},
Boat_Start =
{
Name = "Boat_Start",
TriggerOnEntity = GetGoal("MOVER_boat1_move").GetEntity(),
OnEnter = function(ent)
{
Map.BoatPos = 1;
},
OnExit = function(ent) { Map.BoatPos = -1; },
},
Boat_End =
{
Name = "Boat_End",
TriggerOnEntity = GetGoal("MOVER_boat1_move").GetEntity(),
OnEnter = function(ent)
{
Map.BoatPos = 2;
},
OnExit = function(ent) { Map.BoatPos = -1; },
},
Axis_Build_Barriers = function()
{
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_West_Barrier" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_South_Barrier" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_East_Barrier" );
},
SetCheckpoint = function(axis)
{
if (Map.entranceBlown){
if (axis){ p = 60; }else{ p = 20; }
Util.SetPercentInProgress(p, "CHECKPOINT_forward_bunker");
}
SetAvailableMapGoals( TEAM.AXIS, axis, ".*MG42_barrier2" );
SetAvailableMapGoals( TEAM.AXIS, axis, "MOBILEMORTAR.*" );
SetAvailableMapGoals( TEAM.AXIS, axis, "SNIPE_bridge" );
SetAvailableMapGoals( TEAM.ALLIES, axis, ".*MG42_allied" );
SetAvailableMapGoals( TEAM.ALLIES, !axis && !Map.entranceBlown, "DEFEND_barrier2_.*" );
},
SetBridge = function()
{
SetAvailableMapGoals( TEAM.AXIS, Map.bridgeBuilt && !Map.entranceBlown, "DEFEND_sidewall.*" );
SetAvailableMapGoals( TEAM.AXIS, Map.sideWallDestroyed && !Map.entranceBlown, "PLANT_Bridge" );
SetAvailableMapGoals( TEAM.ALLIES, Map.bridgeBuilt || Map.entranceBlown, "PLANT_Side_Wall" );
b = Map.bridgeBuilt && Map.sideWallDestroyed || Map.entranceBlown;
SetAvailableMapGoals( TEAM.ALLIES, b, "FLAG_allied_obj" );
SetAvailableMapGoals( TEAM.ALLIES, b, "CAPPOINT_radio" );
SetAvailableMapGoals( TEAM.ALLIES, b, "PLANT_West_Barrier" );
SetAvailableMapGoals( TEAM.ALLIES, b, "PLANT_South_Barrier" );
SetAvailableMapGoals( TEAM.ALLIES, b, "PLANT_East_Barrier" );
SetAvailableMapGoals( TEAM.ALLIES, b, "PLANT_Axis_Command_Post" );
SetAvailableMapGoals( TEAM.AXIS, b, "DEFEND_doc_room.*" );
},
forward_bunker_Allies_Captured = function( trigger )
{
Map.SetCheckpoint(false);
Util.MapDebugPrint( "forward_bunker_Allies_Captured" );
},
forward_bunker_Axis_Captured = function( trigger )
{
Map.SetCheckpoint(true);
Util.MapDebugPrint( "forward_bunker_Axis_Captured" );
},
Tank_At_South_Corner = function( trigger )
{
Server.MinClassCount[TEAM.ALLIES][CLASS.SOLDIER] = 0;
Server.MinClassCount[TEAM.ALLIES][CLASS.ENGINEER] = 3;
SetAvailableMapGoals( TEAM.AXIS, false, "ATTACK_south.*" );
Util.OnTriggerPosition( "MOVER_tank", "barrier1", 250.0, Map.Tank_At_Barrier1 );
Util.MapDebugPrint("Tank_At_South_Corner");
},
Tank_At_Barrier1 = function( trigger )
{
SetAvailableMapGoals( TEAM.ALLIES, false, "ESCORT_tank" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_allied_tower" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_checkpoint.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_Axis_Command_Post" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_sidewall.*" );
SetGoalPriority( "PLANT_Tank_Barrier", 0.9, TEAM.ALLIES);
SetGoalPriority( "BUILD_Tank", 0.9, TEAM.ALLIES);
Util.OnTriggerPosition( "MOVER_tank", "barrier1_2", 210.0, Map.Tank_Passed_Barrier1 );
Util.MapDebugPrint("Tank_At_Barrier1");
},
Tank_Passed_Barrier1 = function( trigger )
{
SetAvailableMapGoals( TEAM.AXIS, false, "AIRSTRIKE_south_mg" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_barrier2_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_entrance.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ESCORT_tank" );
Map.Axis_Build_Barriers();
Util.OnTriggerPosition( "MOVER_tank", "barrier2_1", 180.0, Map.Tank_At_Barrier2 );
Util.MapDebugPrint("Tank_Passed_Barrier1");
},
Tank_At_Barrier2 = function( trigger )
{
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_south.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ESCORT_tank" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_radio1" );
SetAvailableMapGoals( TEAM.ALLIES, false, ".*MG42_allied" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_outer.*" );
SetGoalPriority( "MOUNT_tank", 0.59);
SetGoalPriority( "PLANT_Tank_Barrier_1", 0.9, TEAM.ALLIES);
SetGoalPriority( "CHECKPOINT_forward_bunker", 0.91, TEAM.ALLIES, CLASS.ENGINEER);
Util.MapDebugPrint("Tank_At_Barrier2");
},
Bridge_Built = function( trigger )
{
Map.bridgeBuilt = true;
Map.SetBridge();
Util.MapDebugPrint( "Bridge_Built" );
},
Bridge_Destroyed = function( trigger )
{
Map.bridgeBuilt = false;
Map.SetBridge();
Util.MapDebugPrint( "Bridge_Destroyed" );
},
Side_Wall_Destroyed = function( trigger )
{
Map.sideWallDestroyed = true;
Map.SetBridge();
Map.Axis_Build_Barriers();
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_radio1" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_outer.*" );
Util.MapDebugPrint( "Side_Wall_Destroyed" );
},
Main_Entrance_Blown = function( trigger )
{
Map.entranceBlown = true;
Map.SetBridge();
Map.SetCheckpoint(false);
Util.EnableGoal("HEALTHCAB_.*");
Util.EnableGoal("AMMOCAB_.*");
SetAvailableMapGoals( TEAM.AXIS, false, "PLANTMINE_entrance.*" );
SetAvailableMapGoals( TEAM.AXIS, false, ".*_sidewall.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_checkpoint.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_barrier2_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "MOUNT_tank" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOBILEMG42_entrance.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_axis_tower.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_entrance.*" );
SetAvailableMapGoals( TEAM.AXIS, true, ".*MG42_roof" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_inner.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANTMINE_door.*" );
SetGoalPriority("FLAG_allied_obj", 0.5);
Util.SetMaxUsersInProgress(99, "FLAG_allied_obj");
SetGoalPriority( "CHECKPOINT_forward_bunker", 0.6, TEAM.ALLIES, CLASS.ENGINEER);
Server.MinClassCount[TEAM.ALLIES][CLASS.ENGINEER] = 1;
Server.MinClassCount[TEAM.ALLIES][CLASS.COVERTOPS] = 3;
Util.MapDebugPrint( "Main_Entrance_Blown" );
},
Tank_Repaired = function( trigger )
{
Map.tankDamaged = false;
SetAvailableMapGoals( TEAM.AXIS, true, "MOUNTMG42_barrier2" );
Util.MapDebugPrint( "Tank_Repaired" );
},
Tank_Damaged = function( trigger )
{
Map.tankDamaged = true;
SetAvailableMapGoals( TEAM.AXIS, false, "MOUNTMG42_barrier2" );
Util.MapDebugPrint( "Tank_Damaged" );
},
Barrier_Built = function(which)
{
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_doc_" + which + ".*" );
Util.DisableGoal("ROUTE_gate_" + which);
Util.EnableGoal("ROUTE_ladder_" + which);
Util.MapDebugPrint( which + " Barrier_Built" );
},
Barrier_Destroyed = function(which)
{
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_doc_" + which + ".*" );
Util.EnableGoal("ROUTE_gate_" + which);
Util.DisableGoal("ROUTE_ladder_" + which);
Util.MapDebugPrint( which + " Barrier_Destroyed" );
},
South_Barrier_Built = function( trigger )
{
Map.Barrier_Built("south");
},
West_Barrier_Built = function( trigger )
{
Map.Barrier_Built("west");
},
East_Barrier_Built = function( trigger )
{
Map.Barrier_Built("east");
},
South_Barrier_Destroyed = function( trigger )
{
Map.Barrier_Destroyed("south");
},
West_Barrier_Destroyed = function( trigger )
{
Map.Barrier_Destroyed("west");
},
East_Barrier_Destroyed = function( trigger )
{
Map.Barrier_Destroyed("east");
},
Documents_Taken = function( trigger )
{
Util.EnableGoal("ATTACK_radio.*");
Util.MapDebugPrint( "Documents_Taken" );
},
Documents_Returned = function( trigger )
{
Util.DisableGoal("ATTACK_radio.*");
Util.MapDebugPrint( "Documents_Returned" );
},
};
global OnMapLoad = function()
{
OnTriggerRegion(AABB(-4870,-2700,600, -4820,-2600,650), Map.Boat_Start);
OnTriggerRegion(AABB(-2450,-2700,600, -2400,-2600,650), Map.Boat_End);
OnTrigger( "The tank has been repaired!", Map.Tank_Repaired );
OnTrigger( "The tank has been damaged!", Map.Tank_Damaged );
OnTrigger( "Axis reclaim the Forward Bunker!", Map.forward_bunker_Axis_Captured );
OnTrigger( "Allies capture the Forward Bunker!", Map.forward_bunker_Allies_Captured );
OnTrigger( "The Bridge has been constructed.", Map.Bridge_Built );
OnTrigger( "The Bridge has been destroyed.", Map.Bridge_Destroyed );
OnTrigger( "^1The Allied have blown the Side Wall!", Map.Side_Wall_Destroyed );
OnTrigger("^1The Allied have blown the Main Entrance!", Map.Main_Entrance_Blown);
OnTrigger( "The West Barrier has been constructed.", Map.West_Barrier_Built );
OnTrigger( "The South Barrier has been constructed.", Map.South_Barrier_Built );
OnTrigger( "The East Barrier has been constructed.", Map.East_Barrier_Built );
OnTrigger( "The West Barrier has been destroyed.", Map.West_Barrier_Destroyed );
OnTrigger( "The South Barrier has been destroyed.", Map.South_Barrier_Destroyed );
OnTrigger( "The East Barrier has been destroyed.", Map.East_Barrier_Destroyed );
OnTrigger( "Allies have stolen Secret War Dokuments!", Map.Documents_Taken );
OnTrigger( "Flag returned allied_obj!", Map.Documents_Returned );
Util.DisableGoal(".*", true);
Util.EnableGoal("HEALTHCAB_.*1");
Util.EnableGoal("AMMOCAB_.*1");
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_south.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ATTACK_south.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Allied_Command_Post" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_Tank_Barrier" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_Tank_Barrier_1" );
SetAvailableMapGoals( TEAM.AXIS, true, "CHECKPOINT_forward_bunker" );
SetAvailableMapGoals( TEAM.AXIS, true, "AMMOCAB_south_ammocabinet" );
SetAvailableMapGoals( TEAM.AXIS, true, "HEALTHCAB_south_healthcabinet" );
SetAvailableMapGoals( TEAM.AXIS, true, "AIRSTRIKE_south_mg" );
SetGoalPriority( "ATTACK_south.*", 0.75, TEAM.AXIS);
SetGoalPriority( "BUILD_Axis_Command_Post", 0.8, TEAM.AXIS);
SetGoalPriority( "PLANT_Allied_Command_Post", 0.58, TEAM.AXIS);
SetGoalPriority( "BUILD_Tank_Barrier", 1.5, TEAM.AXIS);
SetGoalPriority( "BUILD_Tank_Barrier_1", 1.3, TEAM.AXIS);
SetGoalPriority( "BUILD_West_Barrier", 1.2, TEAM.AXIS );
SetGoalPriority( "BUILD_South_Barrier", 1.2, TEAM.AXIS );
SetGoalPriority( "BUILD_East_Barrier", 1.2, TEAM.AXIS );
SetGoalPriority( "ATTACK_radio.*", 0.59, TEAM.AXIS );
SetGoalPriority( ".*MG42_roof", 0.51, TEAM.AXIS );
SetGoalPriority( "DEFEND_doc_south.*", 0.51, TEAM.AXIS );
SetGoalPriority( "DEFEND_doc_east.*", 0.51, TEAM.AXIS );
SetGoalPriority( "DEFEND_doc_west.*", 0.51, TEAM.AXIS );
SetGoalPriority( "MOUNTMG42.*", 0.5, TEAM.AXIS, CLASS.ENGINEER );
SetAvailableMapGoals( TEAM.ALLIES, true, "ESCORT_tank" );
SetAvailableMapGoals( TEAM.ALLIES, true, "MOUNT_tank" );
SetAvailableMapGoals( TEAM.ALLIES, true, "CHECKPOINT_forward_bunker" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Tank" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Bridge" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Allied_Command_Post" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Tank_Barrier" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Tank_Barrier_1" );
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_allied_tower" );
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_radio1" );
SetGoalPriority( "BUILD_Bridge", 0.92, TEAM.ALLIES);
SetGoalPriority( "PLANT_Side_Wall", 0.92, TEAM.ALLIES);
SetGoalPriority( "PLANT_Tank_Barrier", 0.8, TEAM.ALLIES);
SetGoalPriority( "PLANT_Tank_Barrier_1", 0.79, TEAM.ALLIES);
SetGoalPriority( "ESCORT_tank", 0.75, TEAM.ALLIES);
SetGoalPriority( "SNIPE_allied_tower", 0.9, TEAM.ALLIES);
SetGoalPriority( "BUILD_Tank", 0.95, TEAM.ALLIES);
SetGoalPriority( "PLANTMINE_door.*", 0.81, TEAM.ALLIES);
SetGoalPriority( "REPAIRMG42_allied", 0.9, TEAM.ALLIES);
Map.SetCheckpoint(true);
foreach (goal in { ".*MG42.*", "SNIPE.*", "BUILD_Bridge", "PLANT_Side_Wall",
"PLANT_Bridge", "BUILD_Axis_Command_Post" }){
Util.SetMaxUsers(1, goal);
}
Util.SetMaxUsers(5, "ATTACK_radio.*");
Util.SetMaxUsersInProgress(2, "FLAG_allied_obj");
Util.AddUseWp("PLANT_Bridge", "bridge");
Util.AddUseWp("PLANT_Side_Wall", "sidewall");
Util.AddUseWp("PLANT_Side_Wall", "sidewall2");
SetMapGoalProperties( "DEFEND.*", {mincamptime=30, maxcamptime=100} );
SetMapGoalProperties( "SNIPE_.*", {mincamptime=60, maxcamptime=160} );
Util.OnTriggerPosition( "MOVER_tank", "south_corner", 150.0, Map.Tank_At_South_Corner );
ETUtil.SetCabinets();
MapRoutes =
{
CHECKPOINT_forward_bunker = {
ROUTE_allies_spawn = {
ROUTE_allies_south = { Weight=2, ROUTE_allies1 = {}},
ROUTE_allies2 = {},
ROUTE_allies4 = {},
},
ROUTE_axis_spawn = {
ROUTE_axis_door_east = {},
ROUTE_entrance = { ROUTE_axis_door_south = {} },
},
},
BUILD_Allied_Command_Post = {
ROUTE_allies_spawn = {
ROUTE_radio_south = {},
},
},
FLAG_allied_obj = {
ROUTE_flag = {
ROUTE_sewer = { Weight=2 },
ROUTE_cellar = {},
ROUTE_gate_south = { Weight=6 },
ROUTE_gate_west = { Weight=6,
ROUTE_attic = {},
ROUTE_entrance = {},
},
ROUTE_gate_east = { Weight=6,
ROUTE_attic = {},
ROUTE_entrance = {},
},
},
},
CAPPOINT_radio = {
ROUTE_doc = {
ROUTE_slide = { ROUTE_sidewall = {} },
ROUTE_gate_south = {},
ROUTE_gate_west = {},
ROUTE_gate_east = { ROUTE_sidewall = {} },
ROUTE_ladder_south = {},
ROUTE_ladder_west = {},
ROUTE_ladder_east = { ROUTE_sidewall = {} },
},
},
MOBILEMG42_entrance2 = {
ROUTE_axis_spawn = {
ROUTE_entrance = {}
}
},
};
MapRoutes.PLANT_Tank_Barrier = MapRoutes.CHECKPOINT_forward_bunker;
MapRoutes.PLANT_Tank_Barrier_1 = MapRoutes.CHECKPOINT_forward_bunker;
Util.Routes(MapRoutes);
};
| 0 | 0.957449 | 1 | 0.957449 | game-dev | MEDIA | 0.944922 | game-dev | 0.919631 | 1 | 0.919631 |
JianghongJohn/cocoscreator-ddz | 2,703 | assets/Script/WaitingRoom.js |
// Learn cc.Class:
// - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
// - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
// - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
// - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html
cc.Class({
extends: cc.Component,
properties: {
roomNumber:cc.Label,
leftName:cc.Label,
rightName:cc.Label,
playerName:cc.Label,
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
//获取房间信息
this.roomNumber.string = "房间号:"+Global.roomNum ;
let self = this;
self.playerName.string = Global.playerName;
if (Global.roomWaitType == 'join') {
Network.socket.emit("getRoomData",Global.roomNum);
}
Network.socket.on("getRoomDataBack" ,function(data){
console.log(data);
var playerIndex = 0;
for (let index = 0; index < data.length; index++) {
const player = data[index];
if (player == Global.playerName) {
playerIndex = index;
Global.roomIndex = playerIndex;
}
}
if(data.length==2){
if (playerIndex == 0) {
self.leftName.string = "等待加入";
self.rightName.string = data[1]?data[1]:"等待加入";
} else if(playerIndex == 1) {
self.leftName.string = data[0]?data[0]:"等待加入";
self.rightName.string = "等待加入";
}
}else{
if (playerIndex == 0) {
self.leftName.string = data[2]?data[2]:"等待加入";
self.rightName.string = data[1]?data[1]:"等待加入";
} else if(playerIndex == 1) {
self.leftName.string = data[0]?data[0]:"等待加入";
self.rightName.string = data[2]?data[2]:"等待加入";
}else{
self.leftName.string = data[1]?data[1]:"等待加入";
self.rightName.string = data[0]?data[0]:"等待加入";
}
}
if (data.length == 3) {
cc.director.loadScene('game');
}
});
},
start () {
},
// update (dt) {},
});
| 0 | 0.692559 | 1 | 0.692559 | game-dev | MEDIA | 0.146336 | game-dev | 0.842914 | 1 | 0.842914 |
Sandern/lambdawars | 16,366 | src/game/shared/swarm/asw_weapon_welder_shared.cpp | #include "cbase.h"
#include "in_buttons.h"
#include "soundenvelope.h"
#ifdef CLIENT_DLL
#include "c_asw_player.h"
#include "c_asw_weapon.h"
#include "c_asw_marine.h"
#include "c_asw_door_area.h"
#include "c_asw_door.h"
#include "c_asw_marine_resource.h"
#include "FX.h"
#define CASW_Marine C_ASW_Marine
#define CASW_Door_Area C_ASW_Door_Area
#define CASW_Door C_ASW_Door
#else
#include "asw_marine.h"
#include "asw_player.h"
#include "asw_weapon.h"
#include "asw_door_area.h"
#include "asw_door.h"
#include "npcevent.h"
#include "shot_manipulator.h"
#include "asw_gamerules.h"
#include "asw_marine_resource.h"
#endif
#include "asw_marine_skills.h"
#include "asw_weapon_welder_shared.h"
#include "asw_weapon_parse.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Weapon_Welder, DT_ASW_Weapon_Welder )
BEGIN_NETWORK_TABLE( CASW_Weapon_Welder, DT_ASW_Weapon_Welder )
#ifdef CLIENT_DLL
// recvprops
RecvPropBool (RECVINFO(m_bWeldSeal)),
#else
// sendprops
SendPropBool (SENDINFO(m_bWeldSeal)),
#endif
END_NETWORK_TABLE()
BEGIN_PREDICTION_DATA( CASW_Weapon_Welder )
END_PREDICTION_DATA()
LINK_ENTITY_TO_CLASS( asw_weapon_welder, CASW_Weapon_Welder );
PRECACHE_WEAPON_REGISTER(asw_weapon_welder);
#ifndef CLIENT_DLL
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CASW_Weapon_Welder )
DEFINE_FIELD( m_iAutomaticWeldDirection, FIELD_INTEGER ),
END_DATADESC()
#endif /* not client */
CASW_Weapon_Welder::CASW_Weapon_Welder()
{
m_fWeldTime = 0;
m_bWeldSeal = false;
m_pWeldDoor = NULL;
m_pWeldingSound = NULL;
m_bPlayingWelderSound = false;
#ifdef CLIENT_DLL
m_bWeldSealLast = false;
#endif
}
CASW_Weapon_Welder::~CASW_Weapon_Welder()
{
if ( m_pWeldingSound )
{
CSoundEnvelopeController::GetController().Shutdown(m_pWeldingSound);
}
#ifdef CLIENT_DLL
if ( m_hWeldEffects )
{
ParticleProp()->StopEmissionAndDestroyImmediately( m_hWeldEffects );
m_hWeldEffects = NULL;
}
#endif
}
void CASW_Weapon_Welder::Precache()
{
// precache the weapon model here?
PrecacheScriptSound("ASW_Welder.WeldLoop");
PrecacheParticleSystem( "welding_door_seal" );
PrecacheParticleSystem( "welding_door_cut" );
BaseClass::Precache();
}
void CASW_Weapon_Welder::PrimaryAttack( void )
{
WeldDoor( true ); // seal
}
void CASW_Weapon_Welder::SecondaryAttack( void )
{
WeldDoor( false ); // cut
}
void CASW_Weapon_Welder::WeldDoor(bool bSeal)
{
CASW_Marine *pMarine = GetMarine();
if ( !pMarine || !pMarine->GetCommander() )
return;
bool bWelding = false;
CASW_Door* pDoor = FindDoor();
if ( pDoor )
{
bWelding = true;
Vector vecFacingPoint = pDoor->GetWeldFacingPoint(pMarine);
Vector diff = vecFacingPoint - pMarine->GetAbsOrigin();
diff.z = 0;
VectorNormalize(diff);
QAngle angCurrentFacing = pMarine->ASWEyeAngles();
Vector vecCurrentFacing = vec3_origin;
AngleVectors(angCurrentFacing, &vecCurrentFacing);
vecCurrentFacing.z = 0;
VectorNormalize(vecCurrentFacing);
bool bFacing = DotProduct(diff, vecCurrentFacing) > 0.6f;
if ( !pMarine->IsInhabited() )
{
bFacing = true; // AI marines don't know how to face the door yet
}
if ( bFacing && !pDoor->IsOpen() )
{
// do our muzzle flash, if we're going to alter the weld some
if ( bSeal && pDoor->GetSealAmount() < 1.0f )
{
pMarine->DoMuzzleFlash();
m_bIsFiring = true;
}
else if ( !bSeal && pDoor->GetSealAmount() > 0 )
{
pMarine->DoMuzzleFlash();
m_bIsFiring = true;
}
}
#ifdef CLIENT_DLL
pMarine->SetFacingPoint(vecFacingPoint, GetFireRate()*2.0f);
#else
if ( gpGlobals->maxClients <= 1 )
{
pMarine->SetFacingPoint(vecFacingPoint, GetFireRate()*2.0f);
}
#endif
if ( bFacing )
{
if ( pDoor->IsOpen() )
{
#ifndef CLIENT_DLL
if ( bSeal )
{
pDoor->CloseForWeld( pMarine ); // shut the door first, so we can start welding it
}
#endif
}
else
{
// tell the weapon to weld over the next fire rate interval
m_fWeldTime = GetFireRate() + 0.004f;
m_bWeldSeal = bSeal;
#ifndef CLIENT_DLL
m_pWeldDoor = pDoor;
//Msg( "Setting weld door to %d\n", pDoor->entindex() );
// network door which door we're working on so all players can see progress
if ( pMarine->GetMarineResource() )
pMarine->GetMarineResource()->m_hWeldingDoor = pDoor;
#endif
}
}
}
else
{
//Msg( "Couldn't find door to weld\n" );
}
if ( pMarine->GetActiveWeapon() != this )
{
bool bAttack1, bAttack2, bReload, bOldReload, bOldAttack1;
GetButtons( bAttack1, bAttack2, bReload, bOldReload, bOldAttack1 );
if ( bAttack1 || bAttack2 || bReload || pMarine->GetCurrentMeleeAttack() )
{
bWelding = false;
}
}
if ( !bWelding )
{
m_iAutomaticWeldDirection = 0;
m_bShotDelayed = false;
#ifdef GAME_DLL
if ( pMarine->GetMarineResource() )
{
pMarine->GetMarineResource()->m_hWeldingDoor = NULL;
}
m_pWeldDoor = NULL;
pMarine->OnWeldFinished();
#endif
m_bIsFiring = false;
}
else
{
if ( bSeal )
{
m_flNextPrimaryAttack = m_flNextPrimaryAttack + GetFireRate();
}
else
{
m_flNextSecondaryAttack = m_flNextSecondaryAttack + GetFireRate();
}
}
}
// make the weapon weld if needed
void CASW_Weapon_Welder::ItemPostFrame()
{
#ifndef CLIENT_DLL
CASW_Marine *pMarine = GetMarine();
if ( !pMarine || !pMarine->GetCommander() )
{
if ( m_bPlayingWelderSound )
{
m_bIsFiring = false;
if ( pMarine->GetMarineResource() )
{
pMarine->GetMarineResource()->m_hWeldingDoor = NULL;
}
m_pWeldDoor = NULL;
pMarine->OnWeldFinished();
//Msg( "Clearing weld door as no marine\n" );
}
return BaseItemPostFrame();
}
if ( m_fWeldTime > 0 && m_pWeldDoor )
{
m_fWeldTime -= gpGlobals->frametime;
if ( m_fWeldTime <= 0 )
{
m_bIsFiring = false;
if ( pMarine->GetMarineResource() )
{
pMarine->GetMarineResource()->m_hWeldingDoor = NULL;
}
}
float fSkillScale = MarineSkills()->GetHighestSkillValueNearby(pMarine->GetAbsOrigin(), ENGINEERING_AURA_RADIUS,
ASW_MARINE_SKILL_ENGINEERING, ASW_MARINE_SUBSKILL_ENGINEERING_WELDING);
CASW_Marine *pSkillMarine = MarineSkills()->GetLastSkillMarine();
if ( fSkillScale > 0.0f && pSkillMarine && pSkillMarine->GetMarineResource() )
{
pSkillMarine->m_fUsingEngineeringAura = gpGlobals->curtime;
m_pWeldDoor->m_fSkillMarineHelping = gpGlobals->curtime;
}
else
{
m_pWeldDoor->m_fSkillMarineHelping = 0;
}
if ( fSkillScale < 1.0 )
{
fSkillScale = 0.6f;
}
float fSealAmount = gpGlobals->frametime * fSkillScale;
m_pWeldDoor->WeldDoor( m_bWeldSeal, fSealAmount, pMarine ); // if the door is shut, we can weld
}
#else
if ( m_fWeldTime > 0 )
{
m_fWeldTime -= gpGlobals->frametime;
if ( m_fWeldTime <= 0 )
{
m_bIsFiring = false;
}
}
#endif
// check for ending automatic welding
if ( m_bShotDelayed )
{
if ( m_pWeldDoor )
{
if ( ( m_iAutomaticWeldDirection > 0 && m_pWeldDoor->GetSealAmount() >= 1.0f ) ||
( m_iAutomaticWeldDirection < 0 && m_pWeldDoor->GetSealAmount() <= 0.0f ) )
{
m_bShotDelayed = false;
#ifdef GAME_DLL
if ( pMarine->GetMarineResource() )
{
pMarine->GetMarineResource()->m_hWeldingDoor = NULL;
}
m_pWeldDoor = NULL;
pMarine->OnWeldFinished();
#endif
m_bIsFiring = false;
}
}
else
{
if ( !FindDoor() )
{
m_bShotDelayed = false;
#ifdef GAME_DLL
if ( pMarine->GetMarineResource() )
{
pMarine->GetMarineResource()->m_hWeldingDoor = NULL;
}
m_pWeldDoor = NULL;
pMarine->OnWeldFinished();
#endif
m_bIsFiring = false;
}
}
}
BaseItemPostFrame();
}
// simplified version of the one in CASW_Weapon, don't worry about ammo or clips for the welder
void CASW_Weapon_Welder::BaseItemPostFrame()
{
//CBasePlayer *pOwner = GetCommander();
CASW_Marine* pOwner = GetMarine();
if (!pOwner)
return;
bool bAttack1, bAttack2, bReload, bOldReload, bOldAttack1;
GetButtons(bAttack1, bAttack2, bReload, bOldReload, bOldAttack1 );
// check for automatic welding
if ( m_bShotDelayed )
{
if ( m_iAutomaticWeldDirection > 0 )
{
bAttack1 = true;
//Msg( "doing automatic attack1 since bShotDelayed\n" );
}
else if ( m_iAutomaticWeldDirection < 0 )
{
bAttack2 = true;
//Msg( "doing automatic attack2 since bShotDelayed\n" );
}
}
//Track the duration of the fire
//FIXME: Check for IN_ATTACK2 as well?
//FIXME: What if we're calling ItemBusyFrame?
m_fFireDuration = bAttack1 ? ( m_fFireDuration + gpGlobals->frametime ) : 0.0f;
if ( UsesClipsForAmmo1() )
{
CheckReload();
}
bool bFired = false;
if ( bAttack2 && m_flNextSecondaryAttack <= gpGlobals->curtime )
{
bFired = true;
SecondaryAttack();
}
if ( !bFired && bAttack1 && m_flNextPrimaryAttack <= gpGlobals->curtime )
{
// If the firing button was just pressed, reset the firing time
if ( pOwner && bAttack1 )
{
m_flNextPrimaryAttack = gpGlobals->curtime;
}
PrimaryAttack();
}
if ( !bAttack1 && !bAttack2 )
m_bIsFiring = false;
// -----------------------
// No buttons down
// -----------------------
if (!(bAttack1 || bAttack2 || bReload))
{
// no fire buttons down or reloading
if ( !ReloadOrSwitchWeapons() && !m_bInReload )
{
WeaponIdle();
}
}
}
#ifdef CLIENT_DLL
void CASW_Weapon_Welder::ProcessMuzzleFlashEvent()
{
// attach muzzle flash particle system effect
int iAttachment = GetMuzzleAttachment();
if ( iAttachment > 0 )
{
Vector sparkOrigin, sparkNormal;
QAngle sparkAngles;
if ( GetAttachment( iAttachment, sparkOrigin, sparkAngles ) )
{
AngleVectors(sparkAngles, &sparkNormal);
FX_Sparks( sparkOrigin, 1, 1, sparkNormal, 3, 32, 128 ); // disabled for now
}
}
C_BaseCombatWeapon::ProcessMuzzleFlashEvent();
OnMuzzleFlashed();
}
void CASW_Weapon_Welder::OnDataChanged( DataUpdateType_t type )
{
BaseClass::OnDataChanged( type );
if ( type == DATA_UPDATE_CREATED )
{
// We want to think every frame.
SetNextClientThink( CLIENT_THINK_ALWAYS );
}
UpdateDoorWeldingEffects();
}
void CASW_Weapon_Welder::ClientThink()
{
BaseClass::ClientThink();
UpdateDoorWeldingEffects();
}
void CASW_Weapon_Welder::UpdateDoorWeldingEffects( void )
{
if ( !m_bIsFiring || !GetMarine() || !GetMarine()->GetMarineResource() )
{
RemoveWeldingEffects();
StopWelderSound();
return;
}
C_ASW_Door* pDoor = GetMarine()->GetMarineResource()->m_hWeldingDoor.Get();
if ( !pDoor || pDoor->IsOpen() )
{
RemoveWeldingEffects();
StopWelderSound();
return;
}
StartWelderSound();
if ( !m_hWeldEffects || m_bWeldSealLast != m_bWeldSeal )
{
CreateWeldingEffects( pDoor );
}
if ( m_hWeldEffects )
{
m_hWeldEffects->SetControlPoint( 0, pDoor->GetWeldFacingPoint( GetMarine() ) );
m_hWeldEffects->SetControlPointForwardVector( 0, pDoor->GetSparkNormal( GetMarine() ) );
}
m_bWeldSealLast = m_bWeldSeal;
}
void CASW_Weapon_Welder::CreateWeldingEffects( C_ASW_Door* pDoor )
{
if ( !m_bIsFiring || !GetOwner() || !pDoor )
return;
if ( m_hWeldEffects )
{
RemoveWeldingEffects();
}
if ( !m_hWeldEffects )
{
if ( m_bWeldSeal )
m_hWeldEffects = ParticleProp()->Create( "welding_door_seal", PATTACH_CUSTOMORIGIN );
else
m_hWeldEffects = ParticleProp()->Create( "welding_door_cut", PATTACH_CUSTOMORIGIN );
if ( m_hWeldEffects )
{
m_hWeldEffects->SetControlPoint( 0, pDoor->GetSparkNormal( GetMarine() ) );
m_hWeldEffects->SetControlPointForwardVector( 0, pDoor->GetWeldFacingPoint( GetMarine() ) );
}
/*
m_pLaserPointerEffect->SetControlPoint( 1, vecOrigin );
m_pLaserPointerEffect->SetControlPoint( 2, tr.endpos );
m_pLaserPointerEffect->SetControlPointForwardVector ( 1, vecDirShooting );
Vector vecImpactY, vecImpactZ;
VectorVectors( tr.plane.normal, vecImpactY, vecImpactZ );
vecImpactY *= -1.0f;
m_pLaserPointerEffect->SetControlPointOrientation( 2, vecImpactY, vecImpactZ, tr.plane.normal );
m_pLaserPointerEffect->SetControlPoint( 3, Vector( alpha, 0, 0 ) );
if ( m_hWeldEffects )
{
ParticleProp()->AddControlPoint( m_pLaserPointerEffect, 1, this, PATTACH_CUSTOMORIGIN );
ParticleProp()->AddControlPoint( m_pLaserPointerEffect, 2, this, PATTACH_CUSTOMORIGIN );
}
*/
}
}
void CASW_Weapon_Welder::RemoveWeldingEffects( void )
{
if ( m_hWeldEffects )
{
m_hWeldEffects->StopEmission( false, false, true );
m_hWeldEffects = NULL;
}
}
#endif // CLIENT_DLL
// get the continuous welding sound for this weapon
// in multiplayer, server doesn't send the sound to the owning player as he'll make the sound himself clientside
CSoundPatch *CASW_Weapon_Welder::GetWelderSound( void )
{
if ( m_pWeldingSound == NULL )
{
#ifdef CLIENT_DLL
CPASAttenuationFilter filter( this );
#else
CPASAttenuationFilter filter( this );
if ( gpGlobals->maxClients > 1 )
{
CASW_Marine *pMarine = GetMarine();
if (pMarine)
{
CASW_Player *pPlayer = pMarine->GetCommander();
if ( pPlayer )
filter.RemoveRecipient(pPlayer);
}
}
#endif
m_pWeldingSound = CSoundEnvelopeController::GetController().SoundCreate( filter, entindex(), CHAN_AUTO, "ASW_Welder.WeldLoop", ATTN_NORM );
}
return m_pWeldingSound;
}
void CASW_Weapon_Welder::StartWelderSound()
{
if ( GetWelderSound() && !m_bPlayingWelderSound )
{
m_bPlayingWelderSound = true;
CSoundEnvelopeController::GetController().Play( GetWelderSound(), 1.0f, 100 );
}
}
void CASW_Weapon_Welder::StopWelderSound()
{
if ( m_pWeldingSound && m_bPlayingWelderSound )
{
m_bPlayingWelderSound = false;
CSoundEnvelopeController::GetController().SoundFadeOut( m_pWeldingSound, 0.1f, true );
m_pWeldingSound = NULL;
//Msg( "Stopping welder sound\n" );
}
}
bool CASW_Weapon_Welder::OffhandActivate()
{
CASW_Marine *pMarine = GetMarine();
if ( !pMarine || !pMarine->GetCommander() )
return false;
bool bRecommendedSeal = false;
float fSealAmount = -1.0f;
CASW_Door *pDoor = FindDoor();
if ( pDoor )
{
fSealAmount = pDoor->GetSealAmount();
bRecommendedSeal = pDoor->IsRecommendedSeal();
}
if ( fSealAmount < 0.0f )
{
return true;
}
// start automatic welding
if ( !m_bShotDelayed )
{
m_bShotDelayed = true;
#ifdef GAME_DLL
pMarine->OnWeldStarted();
#endif
if ( fSealAmount == 0.0f || ( bRecommendedSeal && fSealAmount < 1.0f ) )
{
m_iAutomaticWeldDirection = 1;
}
else
{
// default to unsealing the door
m_iAutomaticWeldDirection = -1;
}
}
else
{
// already welding, just flip direction
m_iAutomaticWeldDirection = -m_iAutomaticWeldDirection;
}
return true;
}
float CASW_Weapon_Welder::GetFireRate()
{
//float flRate = 0.07f;
float flRate = GetWeaponInfo()->m_flFireRate;
//CALL_ATTRIB_HOOK_FLOAT( flRate, mod_fire_rate );
return flRate;
}
CASW_Door* CASW_Weapon_Welder::FindDoor()
{
CASW_Marine *pMarine = GetMarine();
if ( !pMarine )
return NULL;
if ( pMarine->IsInhabited() )
{
CASW_Player *pPlayer = pMarine->GetCommander();
if ( !pPlayer )
return NULL;
// find our door area
for ( int i = 0; i < pPlayer->GetNumUseEntities(); i++ )
{
CBaseEntity* pEnt = pPlayer->GetUseEntity( i );
CASW_Door_Area* pDoorArea = dynamic_cast< CASW_Door_Area* >( pEnt );
if ( pDoorArea )
{
CASW_Door* pDoor = pDoorArea->GetASWDoor();
if ( pDoor && pDoor->GetHealth() > 0 )
{
return pDoor;
}
}
}
}
else
{
#ifdef GAME_DLL
CASW_Door_Area *pClosestArea = NULL;
float flClosestDist = FLT_MAX;
for ( int i = 0; i < IASW_Use_Area_List::AutoList().Count(); i++ )
{
CASW_Use_Area *pArea = static_cast< CASW_Use_Area* >( IASW_Use_Area_List::AutoList()[ i ] );
if ( pArea->Classify() == CLASS_ASW_DOOR_AREA )
{
CASW_Door_Area *pDoorArea = assert_cast<CASW_Door_Area*>( pArea );
CASW_Door* pDoor = pDoorArea->GetASWDoor();
if ( !pDoor || pDoor->GetHealth() <= 0 )
{
continue;
}
float flDist = GetAbsOrigin().DistTo( pArea->WorldSpaceCenter() );
if ( flDist < flClosestDist && pArea->CollisionProp()->IsPointInBounds( pMarine->WorldSpaceCenter() ) )
{
flClosestDist = flDist;
pClosestArea = pDoorArea;
}
}
}
if ( pClosestArea )
{
CASW_Door* pDoor = pClosestArea->GetASWDoor();
if ( pDoor )
{
return pDoor;
}
}
#endif
}
return NULL;
}
| 0 | 0.950889 | 1 | 0.950889 | game-dev | MEDIA | 0.931761 | game-dev | 0.85608 | 1 | 0.85608 |
PreviousAlone/Nnngram | 1,861 | TMessagesProj/jni/voip/webrtc/base/android/jni_weak_ref.h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_ANDROID_JNI_WEAK_REF_H_
#define BASE_ANDROID_JNI_WEAK_REF_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/base_export.h"
// Manages WeakGlobalRef lifecycle.
// This class is not thread-safe w.r.t. get() and reset(). Multiple threads may
// safely use get() concurrently, but if the user calls reset() (or of course,
// calls the destructor) they'll need to provide their own synchronization.
class BASE_EXPORT JavaObjectWeakGlobalRef {
public:
JavaObjectWeakGlobalRef();
JavaObjectWeakGlobalRef(const JavaObjectWeakGlobalRef& orig);
JavaObjectWeakGlobalRef(JavaObjectWeakGlobalRef&& orig) noexcept;
JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj);
JavaObjectWeakGlobalRef(JNIEnv* env,
const base::android::JavaRef<jobject>& obj);
virtual ~JavaObjectWeakGlobalRef();
void operator=(const JavaObjectWeakGlobalRef& rhs);
void operator=(JavaObjectWeakGlobalRef&& rhs);
base::android::ScopedJavaLocalRef<jobject> get(JNIEnv* env) const;
// Returns true if the weak reference has not been initialized to point at
// an object (or ḣas had reset() called).
// Do not call this to test if the object referred to still exists! The weak
// reference remains initialized even if the target object has been collected.
bool is_uninitialized() const { return obj_ == nullptr; }
void reset();
private:
void Assign(const JavaObjectWeakGlobalRef& rhs);
jweak obj_;
};
// Get the real object stored in the weak reference returned as a
// ScopedJavaLocalRef.
BASE_EXPORT base::android::ScopedJavaLocalRef<jobject> GetRealObject(
JNIEnv* env, jweak obj);
#endif // BASE_ANDROID_JNI_WEAK_REF_H_
| 0 | 0.887636 | 1 | 0.887636 | game-dev | MEDIA | 0.277841 | game-dev | 0.545007 | 1 | 0.545007 |
raniejade/godot-kotlin | 31,653 | godot-kotlin/src/nativeGen/kotlin/godot/RigidBody.kt | // DO NOT EDIT, THIS FILE IS GENERATED FROM api.json
package godot
import gdnative.godot_method_bind
import gdnative.godot_string
import godot.core.Allocator
import godot.core.Godot
import godot.core.Variant
import godot.core.VariantArray
import godot.core.Vector3
import kotlin.Boolean
import kotlin.Float
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.reflect.KCallable
import kotlinx.cinterop.BooleanVar
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.COpaquePointerVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.DoubleVar
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.cstr
import kotlinx.cinterop.invoke
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.readValue
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.value
open class RigidBody(
@Suppress("UNUSED_PARAMETER")
__ignore: String?
) : PhysicsBody(null) {
var angularDamp: Float
get() {
return getAngularDamp()
}
set(value) {
setAngularDamp(value)
}
var angularVelocity: Vector3
get() {
return getAngularVelocity()
}
set(value) {
setAngularVelocity(value)
}
var axisLockAngularX: Boolean
get() {
return getAxisLock(8)
}
set(value) {
setAxisLock(8, value)
}
var axisLockAngularY: Boolean
get() {
return getAxisLock(16)
}
set(value) {
setAxisLock(16, value)
}
var axisLockAngularZ: Boolean
get() {
return getAxisLock(32)
}
set(value) {
setAxisLock(32, value)
}
var axisLockLinearX: Boolean
get() {
return getAxisLock(1)
}
set(value) {
setAxisLock(1, value)
}
var axisLockLinearY: Boolean
get() {
return getAxisLock(2)
}
set(value) {
setAxisLock(2, value)
}
var axisLockLinearZ: Boolean
get() {
return getAxisLock(4)
}
set(value) {
setAxisLock(4, value)
}
var bounce: Float
get() {
return getBounce()
}
set(value) {
setBounce(value)
}
var canSleep: Boolean
get() {
return isAbleToSleep()
}
set(value) {
setCanSleep(value)
}
var contactMonitor: Boolean
get() {
return isContactMonitorEnabled()
}
set(value) {
setContactMonitor(value)
}
var contactsReported: Int
get() {
return getMaxContactsReported()
}
set(value) {
setMaxContactsReported(value)
}
var continuousCd: Boolean
get() {
return isUsingContinuousCollisionDetection()
}
set(value) {
setUseContinuousCollisionDetection(value)
}
var customIntegrator: Boolean
get() {
return isUsingCustomIntegrator()
}
set(value) {
setUseCustomIntegrator(value)
}
var friction: Float
get() {
return getFriction()
}
set(value) {
setFriction(value)
}
var gravityScale: Float
get() {
return getGravityScale()
}
set(value) {
setGravityScale(value)
}
var linearDamp: Float
get() {
return getLinearDamp()
}
set(value) {
setLinearDamp(value)
}
var linearVelocity: Vector3
get() {
return getLinearVelocity()
}
set(value) {
setLinearVelocity(value)
}
var mass: Float
get() {
return getMass()
}
set(value) {
setMass(value)
}
var mode: Mode
get() {
return getMode()
}
set(value) {
setMode(value.value)
}
var physicsMaterialOverride: PhysicsMaterial
get() {
return getPhysicsMaterialOverride()
}
set(value) {
setPhysicsMaterialOverride(value)
}
var sleeping: Boolean
get() {
return isSleeping()
}
set(value) {
setSleeping(value)
}
var weight: Float
get() {
return getWeight()
}
set(value) {
setWeight(value)
}
/**
* RigidBody::body_entered signal
*/
val signalBodyEntered: Signal1<Node> = Signal1("body_entered")
/**
* RigidBody::body_exited signal
*/
val signalBodyExited: Signal1<Node> = Signal1("body_exited")
/**
* RigidBody::body_shape_entered signal
*/
val signalBodyShapeEntered: Signal4<Int, Node, Int, Int> = Signal4("body_shape_entered")
/**
* RigidBody::body_shape_exited signal
*/
val signalBodyShapeExited: Signal4<Int, Node, Int, Int> = Signal4("body_shape_exited")
/**
* RigidBody::sleeping_state_changed signal
*/
val signalSleepingStateChanged: Signal0 = Signal0("sleeping_state_changed")
constructor() : this(null) {
if (Godot.shouldInitHandle()) {
_handle = __new()
}
}
/**
* Specialized setter for angularVelocity
*/
fun angularVelocity(cb: Vector3.() -> Unit) {
val _p = angularVelocity
cb(_p)
angularVelocity = _p
}
/**
* Specialized setter for linearVelocity
*/
fun linearVelocity(cb: Vector3.() -> Unit) {
val _p = linearVelocity
cb(_p)
linearVelocity = _p
}
open fun _body_enter_tree(arg0: Int) {
TODO()
}
open fun _body_exit_tree(arg0: Int) {
TODO()
}
open fun _direct_state_changed(arg0: Object) {
TODO()
}
open fun _integrate_forces(state: PhysicsDirectBodyState) {
TODO()
}
open fun _reload_physics_characteristics() {
TODO()
}
fun addCentralForce(force: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.addCentralForce.call(self._handle, listOf(force), null)
}
}
fun addForce(force: Vector3, position: Vector3) {
val self = this
return Allocator.allocationScope {
val _args = mutableListOf<Any?>()
_args.add(force)
_args.add(position)
__method_bind.addForce.call(self._handle, _args, null)
}
}
fun addTorque(torque: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.addTorque.call(self._handle, listOf(torque), null)
}
}
fun applyCentralImpulse(impulse: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.applyCentralImpulse.call(self._handle, listOf(impulse), null)
}
}
fun applyImpulse(position: Vector3, impulse: Vector3) {
val self = this
return Allocator.allocationScope {
val _args = mutableListOf<Any?>()
_args.add(position)
_args.add(impulse)
__method_bind.applyImpulse.call(self._handle, _args, null)
}
}
fun applyTorqueImpulse(impulse: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.applyTorqueImpulse.call(self._handle, listOf(impulse), null)
}
}
fun getAngularDamp(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getAngularDamp.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getAngularVelocity(): Vector3 {
val self = this
return Allocator.allocationScope {
val _ret = Vector3()
val _retPtr = _ret._value.ptr
__method_bind.getAngularVelocity.call(self._handle, emptyList(), _retPtr)
_ret._value = _retPtr.pointed.readValue()
_ret
}
}
fun getAxisLock(axis: Int): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.getAxisLock.call(self._handle, listOf(axis), _retPtr)
_ret.value
}
}
fun getBounce(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getBounce.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getCollidingBodies(): VariantArray {
val self = this
return Allocator.allocationScope {
val _ret = VariantArray()
val _retPtr = _ret._value.ptr
__method_bind.getCollidingBodies.call(self._handle, emptyList(), _retPtr)
_ret._value = _retPtr.pointed.readValue()
_ret
}
}
fun getFriction(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getFriction.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getGravityScale(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getGravityScale.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getLinearDamp(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getLinearDamp.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getLinearVelocity(): Vector3 {
val self = this
return Allocator.allocationScope {
val _ret = Vector3()
val _retPtr = _ret._value.ptr
__method_bind.getLinearVelocity.call(self._handle, emptyList(), _retPtr)
_ret._value = _retPtr.pointed.readValue()
_ret
}
}
fun getMass(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getMass.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun getMaxContactsReported(): Int {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getMaxContactsReported.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun getMode(): Mode {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getMode.call(self._handle, emptyList(), _retPtr)
RigidBody.Mode.from(_ret.value)
}
}
fun getPhysicsMaterialOverride(): PhysicsMaterial {
val self = this
return Allocator.allocationScope {
lateinit var _ret: PhysicsMaterial
val _tmp = alloc<COpaquePointerVar>()
val _retPtr = _tmp.ptr
__method_bind.getPhysicsMaterialOverride.call(self._handle, emptyList(), _retPtr)
_ret = objectToType<PhysicsMaterial>(_tmp.value!!)
_ret
}
}
fun getWeight(): Float {
val self = this
return Allocator.allocationScope {
val _ret = alloc<DoubleVar>()
val _retPtr = _ret.ptr
__method_bind.getWeight.call(self._handle, emptyList(), _retPtr)
_ret.value.toFloat()
}
}
fun isAbleToSleep(): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.isAbleToSleep.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun isContactMonitorEnabled(): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.isContactMonitorEnabled.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun isSleeping(): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.isSleeping.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun isUsingContinuousCollisionDetection(): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.isUsingContinuousCollisionDetection.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun isUsingCustomIntegrator(): Boolean {
val self = this
return Allocator.allocationScope {
val _ret = alloc<BooleanVar>()
val _retPtr = _ret.ptr
__method_bind.isUsingCustomIntegrator.call(self._handle, emptyList(), _retPtr)
_ret.value
}
}
fun setAngularDamp(angularDamp: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setAngularDamp.call(self._handle, listOf(angularDamp), null)
}
}
fun setAngularVelocity(angularVelocity: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.setAngularVelocity.call(self._handle, listOf(angularVelocity), null)
}
}
fun setAxisLock(axis: Int, lock: Boolean) {
val self = this
return Allocator.allocationScope {
val _args = mutableListOf<Any?>()
_args.add(axis)
_args.add(lock)
__method_bind.setAxisLock.call(self._handle, _args, null)
}
}
fun setAxisVelocity(axisVelocity: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.setAxisVelocity.call(self._handle, listOf(axisVelocity), null)
}
}
fun setBounce(bounce: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setBounce.call(self._handle, listOf(bounce), null)
}
}
fun setCanSleep(ableToSleep: Boolean) {
val self = this
return Allocator.allocationScope {
__method_bind.setCanSleep.call(self._handle, listOf(ableToSleep), null)
}
}
fun setContactMonitor(enabled: Boolean) {
val self = this
return Allocator.allocationScope {
__method_bind.setContactMonitor.call(self._handle, listOf(enabled), null)
}
}
fun setFriction(friction: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setFriction.call(self._handle, listOf(friction), null)
}
}
fun setGravityScale(gravityScale: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setGravityScale.call(self._handle, listOf(gravityScale), null)
}
}
fun setLinearDamp(linearDamp: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setLinearDamp.call(self._handle, listOf(linearDamp), null)
}
}
fun setLinearVelocity(linearVelocity: Vector3) {
val self = this
return Allocator.allocationScope {
__method_bind.setLinearVelocity.call(self._handle, listOf(linearVelocity), null)
}
}
fun setMass(mass: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setMass.call(self._handle, listOf(mass), null)
}
}
fun setMaxContactsReported(amount: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setMaxContactsReported.call(self._handle, listOf(amount), null)
}
}
fun setMode(mode: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setMode.call(self._handle, listOf(mode), null)
}
}
fun setPhysicsMaterialOverride(physicsMaterialOverride: PhysicsMaterial) {
val self = this
return Allocator.allocationScope {
__method_bind.setPhysicsMaterialOverride.call(self._handle, listOf(physicsMaterialOverride),
null)
}
}
fun setSleeping(sleeping: Boolean) {
val self = this
return Allocator.allocationScope {
__method_bind.setSleeping.call(self._handle, listOf(sleeping), null)
}
}
fun setUseContinuousCollisionDetection(enable: Boolean) {
val self = this
return Allocator.allocationScope {
__method_bind.setUseContinuousCollisionDetection.call(self._handle, listOf(enable), null)
}
}
fun setUseCustomIntegrator(enable: Boolean) {
val self = this
return Allocator.allocationScope {
__method_bind.setUseCustomIntegrator.call(self._handle, listOf(enable), null)
}
}
fun setWeight(weight: Float) {
val self = this
return Allocator.allocationScope {
__method_bind.setWeight.call(self._handle, listOf(weight), null)
}
}
enum class Mode(
val value: Int
) {
RIGID(0),
STATIC(1),
CHARACTER(2),
KINEMATIC(3);
companion object {
fun from(value: Int): Mode {
for (enumValue in values()) {
if (enumValue.value == value) {
return enumValue
}
}
throw AssertionError("""Unsupported enum value: $value""")
}
}
}
companion object {
internal fun __new(): COpaquePointer = Allocator.allocationScope {
val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("RigidBody".cstr.ptr)
requireNotNull(fnPtr) { "No instance found for RigidBody" }
val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>()
fn()
}
/**
* Container for method_bind pointers for RigidBody
*/
private object __method_bind {
val addCentralForce: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"add_central_force".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method add_central_force" }
}
val addForce: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"add_force".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method add_force" }
}
val addTorque: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"add_torque".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method add_torque" }
}
val applyCentralImpulse: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"apply_central_impulse".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method apply_central_impulse" }
}
val applyImpulse: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"apply_impulse".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method apply_impulse" }
}
val applyTorqueImpulse: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"apply_torque_impulse".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method apply_torque_impulse" }
}
val getAngularDamp: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_angular_damp".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_angular_damp" }
}
val getAngularVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_angular_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_angular_velocity" }
}
val getAxisLock: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_axis_lock".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_axis_lock" }
}
val getBounce: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_bounce".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_bounce" }
}
val getCollidingBodies: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_colliding_bodies".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_colliding_bodies" }
}
val getFriction: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_friction".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_friction" }
}
val getGravityScale: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_gravity_scale".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_gravity_scale" }
}
val getLinearDamp: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_linear_damp".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_linear_damp" }
}
val getLinearVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_linear_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_linear_velocity" }
}
val getMass: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_mass".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_mass" }
}
val getMaxContactsReported: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_max_contacts_reported".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_max_contacts_reported" }
}
val getMode: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_mode".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_mode" }
}
val getPhysicsMaterialOverride: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_physics_material_override".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_physics_material_override" }
}
val getWeight: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"get_weight".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_weight" }
}
val isAbleToSleep: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"is_able_to_sleep".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_able_to_sleep" }
}
val isContactMonitorEnabled: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"is_contact_monitor_enabled".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_contact_monitor_enabled" }
}
val isSleeping: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"is_sleeping".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_sleeping" }
}
val isUsingContinuousCollisionDetection: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"is_using_continuous_collision_detection".cstr.ptr)
requireNotNull(ptr) {
"No method_bind found for method is_using_continuous_collision_detection" }
}
val isUsingCustomIntegrator: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"is_using_custom_integrator".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_using_custom_integrator" }
}
val setAngularDamp: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_angular_damp".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_angular_damp" }
}
val setAngularVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_angular_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_angular_velocity" }
}
val setAxisLock: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_axis_lock".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_axis_lock" }
}
val setAxisVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_axis_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_axis_velocity" }
}
val setBounce: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_bounce".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_bounce" }
}
val setCanSleep: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_can_sleep".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_can_sleep" }
}
val setContactMonitor: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_contact_monitor".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_contact_monitor" }
}
val setFriction: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_friction".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_friction" }
}
val setGravityScale: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_gravity_scale".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_gravity_scale" }
}
val setLinearDamp: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_linear_damp".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_linear_damp" }
}
val setLinearVelocity: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_linear_velocity".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_linear_velocity" }
}
val setMass: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_mass".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_mass" }
}
val setMaxContactsReported: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_max_contacts_reported".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_max_contacts_reported" }
}
val setMode: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_mode".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_mode" }
}
val setPhysicsMaterialOverride: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_physics_material_override".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_physics_material_override" }
}
val setSleeping: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_sleeping".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_sleeping" }
}
val setUseContinuousCollisionDetection: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_use_continuous_collision_detection".cstr.ptr)
requireNotNull(ptr) {
"No method_bind found for method set_use_continuous_collision_detection" }
}
val setUseCustomIntegrator: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_use_custom_integrator".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_use_custom_integrator" }
}
val setWeight: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("RigidBody".cstr.ptr,
"set_weight".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_weight" }
}}
}
}
| 0 | 0.855707 | 1 | 0.855707 | game-dev | MEDIA | 0.471287 | game-dev | 0.911366 | 1 | 0.911366 |
renjianfeng/flightSimulator | 10,505 | .history/src/Scene/GameScene/fireCon_20181012141608.ts | /**
* 子弹控制系统 by renjianfeng
*/
import {AssetsManager} from "../../public"
import {SceneManager} from "../../public"
import {Func} from "../../public"
export class FireCon{
private static instance: FireCon;
public static get ins(): FireCon {
if (!this.instance) {
this.instance = new FireCon();
}
return this.instance;
}
//子弹
private bullets=[]
//击中子弹爆炸
private booms=[]
//准星
private starUi
//准星图片
private image2
private ray
private hit
private display
private scene
//帧率时间补偿
private times;
private fireSpeed=50;
private j;
private freeState;
private creatUI(){
this.starUi = new BABYLON.GUI.Rectangle();
this.starUi.width = "30px";
this.starUi.height = "30px";
this.starUi.alpha=0.8;
//this.rect1.cornerRadius = 5;
// this.rect1.color = "#009855";
this.starUi.thickness = 0;
// this.rect1.background = new BABYLON.Color4(0,0,0,0);
this.display.advancedTexture.addControl( this.starUi);
this.image2 = new BABYLON.GUI.Image("but", AssetsManager.ins.resourceObject["images"]["gameScene"]["jiantou3"].src);
this.starUi.addControl(this.image2)
}
public init(display){
this.scene=SceneManager.ins.scene;
this.display=display
//创建准星
this.creatUI()
//创建事件
this.addEvent()
//创建子弹列表
for(var i=0;i<=160;i++){
this.bullets[i]= BABYLON.MeshBuilder.CreateSphere("frees", {diameterX: 2, diameterY: 2, diameterZ: 14}, this.scene);
this.bullets[i].lifeState=false;
this.bullets[i].isPickable=false;
this.bullets[i].material=this.display.freeMateial;
this.bullets[i].checkCollisions = false;;
}
//创建爆炸列表
for(var i=0;i<=160;i++){
this.booms[i]= BABYLON.MeshBuilder.CreateSphere("boom", {diameter: 10}, this.scene);
this.booms[i].boom=new TWEEN.Tween(this.booms[i].scaling);
this.booms[i].lifeState=false;
this.booms[i].isPickable=false;
this.booms[i].material=this.display.boomMateial;
this.bullets[i].checkCollisions = false;;
// this.frees[i].scaling=new BABYLON.Vector3(1,0.001,0.001)
// this.frees[i].rotation=new BABYLON.Vector3(0,0.3,Math.PI*0.5)
}
//获得位置
var origin = this.display.cameraBox.position;
//创建向前矢量
var forward = new BABYLON.Vector3(0,0,1);
forward = Func.ins.vecToLocal(forward, this.display.cameraBox);
//创建方向
var direction = forward.subtract(origin);
direction = BABYLON.Vector3.Normalize(direction);
//var length = 100;
//创建属性
this.ray = new BABYLON.Ray(origin, direction, 3000);
}
private addEvent(){
document.addEventListener("mousedown",(e)=>{
if(e.button==0){
this.freeState=true;
}
})
document.addEventListener("mouseup",(e)=>{
if(e.button==0){
this.freeState=false;
}
})
setInterval(()=>{
if(this.freeState){
var ram=Math.random()/50;
if(this.j<=this.bullets.length-1){
this.bullets[this.j].position=new BABYLON.Vector3(this.display.cameraBox.absolutePosition.x+ram,this.display.cameraBox.absolutePosition.y+ram,this.display.cameraBox.absolutePosition.z) ;
this.bullets[this.j].rotation=new BABYLON.Vector3(this.display.cameraBox.rotation.x+ram,this.display.cameraBox.rotation.y+ram,this.display.cameraBox.rotation.z);
this.bullets[this.j].lifeState=true;
this.j++;
// this.timerNpc.start();
}else{
this.j=0;
this.bullets[this.j].position=new BABYLON.Vector3(this.display.cameraBox.absolutePosition.x,this.display.cameraBox.absolutePosition.y,this.display.cameraBox.absolutePosition.z) ;
this.bullets[this.j].rotation=new BABYLON.Vector3(this.display.cameraBox.rotation.x,this.display.cameraBox.rotation.y,this.display.cameraBox.rotation.z);
this.bullets[this.j].lifeState=true;
}
}
},50)
}
public update(times) {
/* if(!this.freeState){
return;
} */
this.times= times;
var origin = this.display.cameraBox.position;
var forward = new BABYLON.Vector3(0,0,1000);
forward = Func.ins.vecToLocal(forward, this.display.cameraBox);
var direction = forward.subtract(origin);
direction = BABYLON.Vector3.Normalize(direction);
this.ray.origin = origin;
this.ray.direction =direction;
/* let rayHelper = new BABYLON.RayHelper(this.ray);
rayHelper.show(this.scene,new BABYLON.Color3(1,1,1)); */
this.hit = this.scene.pickWithRay(this.ray);
var ram=Math.random;
// this.rect2.linkWithMesh(this.display.cameraBox)
if (this.hit.pickedMesh){
this.starUi.moveToVector3(this.hit.pickedPoint,this.scene)
// this.rect1.isVisible = true;
// this.rect2.color = "#ffc107";
}else{
// this.rect1.isVisible = true;
this.starUi.moveToVector3(this.display.pickMesh.absolutePosition,this.scene)
// this.rect2.color = "#009855";
}
this.bullets.forEach((free,i)=>{
if(free.lifeState==true){
var forword=new BABYLON.Vector3(free.forward.x*this.times*this.fireSpeed,free.forward.y*this.times*this.fireSpeed,free.forward.z*this.times*this.fireSpeed)
free.moveWithCollisions(forword);
free.isVisible=true;
if (this.hit.pickedMesh){
/* console.log("hit.pickedMesh.name")
console.log(hit.pickedMesh.name)
console.log(hit.pickedPoint) */
if(!free.boomPosition){
free.boomPosition=new BABYLON.Vector3(this.hit.pickedPoint.x,this.hit.pickedPoint.y,this.hit.pickedPoint.z)
}
//this.booms[i].position=hit.pickedPoint;
}
if(free.boomPosition){
var jl2=Func.ins.getDistance(
free.position.x,
free.position.y,
free.position.z,
free.boomPosition.x,
free.boomPosition.y,
free.boomPosition.z,
)
if(jl2<=50){
console.log(44444)
free.lifeState=false;
this.booms[i].position=new BABYLON.Vector3(free.position.x,free.position.y,free.position.z);
// this.booms[i].scaling=new BABYLON.Vector3(1,1,1);
this.booms[i].scaling.x=4;
this.booms[i].scaling.y=4;
this.booms[i].scaling.z=4;
this.booms[i].boom.to({ x:1 ,y:1,z:1}, 1000);
this.booms[i].boom.start();
this.booms[i].boom.onComplete(()=>{
this.booms[i].scaling.x=0;
this.booms[i].scaling.y=0;
this.booms[i].scaling.z=0;
})
free.boomPosition=null;
}
}
/* var pointToIntersect = new BABYLON.Vector3(10, -5, 0);
if (balloon3.intersectsPoint(pointToIntersect)){
balloon3.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
} */
/* if (this.scene.getMeshByName("default").intersectsPoint(free.position)) {
//free.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
this.booms[i].position=new BABYLON.Vector3(free.position.x,free.position.y,free.position.z);
free.lifeState=false
} else {
//free.material.emissiveColor = new BABYLON.Color4(1, 1, 1, 1);
} */
/* this.rayEventCon(
"frontPick",
new BABYLON.Vector3(0, 0, -1),
new BABYLON.Vector3(0, 0, 0),
this.scene.getMeshByName("default"),
free,
5,
(e)=>{
//console.log(e)
if(e){
//console.log("撞到前面")
this.booms[i].position=new BABYLON.Vector3(free.position.x,free.position.y,free.position.z);
free.lifeState=false
}
}
)
*/
var jl=Func.ins.getDistance(
free.position.x,
free.position.y,
free.position.z,
this.display.cameraBox.position.x,
this.display.cameraBox.position.y,
this.display.cameraBox.position.z
)
if(jl>=3000){
free.lifeState=false;
free.boomPosition=null;
/* free.position=new BABYLON.Vector3(this.display.cameraBox.absolutePosition.x,this.display.cameraBox.absolutePosition.y,this.display.cameraBox.absolutePosition.z) ;
free.rotation=new BABYLON.Vector3(this.display.cameraBox.rotation.x,this.display.cameraBox.rotation.y,this.display.cameraBox.rotation.z);
*/ }
}else{
/* free.position=new BABYLON.Vector3(this.display.cameraBox.absolutePosition.x,this.display.cameraBox.absolutePosition.y,this.display.cameraBox.absolutePosition.z) ;
free.rotation=new BABYLON.Vector3(this.display.cameraBox.rotation.x,this.display.cameraBox.rotation.y,this.display.cameraBox.rotation.z);
*/ free.isVisible=false;
}
})
}
}
| 0 | 0.759573 | 1 | 0.759573 | game-dev | MEDIA | 0.677437 | game-dev | 0.89848 | 1 | 0.89848 |
eatdreamcat/WaveEquation | 2,394 | FluidSimulator/Packages/com.unity.render-pipelines.universal@14.0.9/Runtime/Tiling/TileRangeExpansionJob.cs | using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
namespace UnityEngine.Rendering.Universal
{
[BurstCompile(FloatMode = FloatMode.Fast, DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
struct TileRangeExpansionJob : IJobFor
{
[ReadOnly]
public NativeArray<InclusiveRange> tileRanges;
[NativeDisableParallelForRestriction]
public NativeArray<uint> tileMasks;
public int rangesPerItem;
public int itemsPerTile;
public int wordsPerTile;
public int2 tileResolution;
public void Execute(int jobIndex)
{
var rowIndex = jobIndex % tileResolution.y;
var viewIndex = jobIndex / tileResolution.y;
var compactCount = 0;
var itemIndices = new NativeArray<short>(itemsPerTile, Allocator.Temp);
var itemRanges = new NativeArray<InclusiveRange>(itemsPerTile, Allocator.Temp);
// Compact the light ranges for the current row.
for (var itemIndex = 0; itemIndex < itemsPerTile; itemIndex++)
{
var range = tileRanges[viewIndex * rangesPerItem * itemsPerTile + itemIndex * rangesPerItem + 1 + rowIndex];
if (!range.isEmpty)
{
itemIndices[compactCount] = (short)itemIndex;
itemRanges[compactCount] = range;
compactCount++;
}
}
var rowBaseMaskIndex = viewIndex * wordsPerTile * tileResolution.x * tileResolution.y + rowIndex * wordsPerTile * tileResolution.x;
for (var tileIndex = 0; tileIndex < tileResolution.x; tileIndex++)
{
var tileBaseIndex = rowBaseMaskIndex + tileIndex * wordsPerTile;
for (var i = 0; i < compactCount; i++)
{
var itemIndex = (int)itemIndices[i];
var wordIndex = itemIndex / 32;
var itemMask = 1u << (itemIndex % 32);
var range = itemRanges[i];
if (range.Contains((short)tileIndex))
{
tileMasks[tileBaseIndex + wordIndex] |= itemMask;
}
}
}
itemIndices.Dispose();
itemRanges.Dispose();
}
}
}
| 0 | 0.832687 | 1 | 0.832687 | game-dev | MEDIA | 0.507064 | game-dev | 0.976788 | 1 | 0.976788 |
octotep/bevy_crossterm | 4,844 | examples/demo/sprites.rs | use bevy::prelude::*;
use bevy_crossterm::prelude::*;
pub fn setup(
commands: &mut Commands,
scene_root: Res<Entity>,
window: Res<CrosstermWindow>,
asset_server: Res<AssetServer>,
mut sprites: ResMut<Assets<Sprite>>,
mut stylemaps: ResMut<Assets<StyleMap>>,
) {
const MARGIN: i32 = 4;
let mut explain_text = "Sprites are the lifeblood of bevy_crossterm.\n\nSprites are rectangular regions of (unicode) text which are rendered on the screen at a given Position. Sprites can also be visible/invisible and \"transparent\" which allows bevy_crossterm to skip rendering unstyled spaces, so the sprites underneath are visible.\n\nPositions have an x, y, and z coordinate to allow them to be properly ordered front-to-back.".to_string();
let explain_width = window.x_center() as i32 - MARGIN * 2; // Half the screen plus some margins
textwrap::fill_inplace(&mut explain_text, explain_width as usize);
let explain_text = explain_text.replace("\n", "\n\n");
let explain_sprite = Sprite::new(explain_text);
let explain_pos = Position::with_xy(
MARGIN,
window.y_center() as i32 - explain_sprite.y_center() as i32,
);
let default_style = stylemaps.add(StyleMap::default());
let big_box_handle: Handle<Sprite> = asset_server.get_handle("demo/big_box.txt");
let big_box_sprite = sprites.get(&big_box_handle).unwrap();
let big_box_pos = Position::with_xy(
window.width() as i32 / 4 * 3 - big_box_sprite.width() as i32 - MARGIN,
window.height() as i32 / 10 * 1,
);
let small_box_handle: Handle<Sprite> = asset_server.get_handle("demo/small_box.txt");
let small_box_pos = Position::with_xy(
window.width() as i32 / 4 * 3 + MARGIN,
window.height() as i32 / 10 * 1 + 1,
);
let big_combo_pos = Position::with_xy(
(window.width() as i32 / 4 * 3) - (big_box_sprite.x_center() as i32),
(window.height() as i32 / 10 * 5) - (big_box_sprite.y_center() as i32),
);
let small_combo_pos = Position::new(
(window.width() as i32 / 4 * 3) - (big_box_sprite.x_center() as i32) + 1,
(window.height() as i32 / 10 * 5) - (big_box_sprite.y_center() as i32) + 1,
1,
);
let big_combo_trans_pos = Position::with_xy(
(window.width() as i32 / 4 * 3) - (big_box_sprite.x_center() as i32),
(window.height() as i32 / 10 * 8) - (big_box_sprite.y_center() as i32),
);
let small_combo_trans_pos = Position::new(
(window.width() as i32 / 4 * 3) - (big_box_sprite.x_center() as i32) + 1,
(window.height() as i32 / 10 * 8) - (big_box_sprite.y_center() as i32) + 1,
1,
);
let mut white = StyleMap::with_fg(Color::White);
white.style.attributes.set(Attribute::Bold);
let white_handle = stylemaps.add(white);
let grey_handle = stylemaps.add(StyleMap::with_fg(Color::DarkGrey));
let transparent = Visible::transparent();
commands
.spawn(SpriteBundle {
sprite: sprites.add(explain_sprite),
stylemap: default_style.clone(),
position: explain_pos,
..Default::default()
})
.with(Parent(*scene_root))
// These are the two boxes separately
.spawn(SpriteBundle {
sprite: asset_server.get_handle("demo/big_box.txt"),
position: big_box_pos,
stylemap: grey_handle.clone(),
..Default::default()
})
.with(Parent(*scene_root))
.spawn(SpriteBundle {
sprite: asset_server.get_handle("demo/small_box.txt"),
stylemap: white_handle.clone(),
position: small_box_pos,
..Default::default()
})
.with(Parent(*scene_root))
// These are the sprites that make up the non-transparent demo
.spawn(SpriteBundle {
sprite: big_box_handle.clone(),
position: big_combo_pos,
stylemap: grey_handle.clone(),
..Default::default()
})
.with(Parent(*scene_root))
.spawn(SpriteBundle {
sprite: small_box_handle.clone(),
position: small_combo_pos,
stylemap: white_handle.clone(),
..Default::default()
})
.with(Parent(*scene_root))
// These are the sprites that make up the trasparent demo
.spawn(SpriteBundle {
sprite: big_box_handle.clone(),
position: big_combo_trans_pos,
stylemap: grey_handle.clone(),
..Default::default()
})
.with(Parent(*scene_root))
.spawn(SpriteBundle {
sprite: small_box_handle.clone(),
position: small_combo_trans_pos,
stylemap: white_handle.clone(),
visible: transparent,
})
.with(Parent(*scene_root));
}
| 0 | 0.840287 | 1 | 0.840287 | game-dev | MEDIA | 0.721317 | game-dev | 0.816534 | 1 | 0.816534 |
Squalr/Squally | 3,803 | Source/Scenes/Platformer/Quests/CastleValgrind/CureKingLine/OutsideThroneRoom.cpp | #include "OutsideThroneRoom.h"
#include "cocos/2d/CCActionEase.h"
#include "cocos/2d/CCActionInstant.h"
#include "cocos/2d/CCActionInterval.h"
#include "cocos/base/CCEventCustom.h"
#include "cocos/base/CCEventListenerCustom.h"
#include "cocos/base/CCValue.h"
#include "Engine/Animations/SmartAnimationNode.h"
#include "Engine/Dialogue/DialogueOption.h"
#include "Engine/Events/ObjectEvents.h"
#include "Engine/Events/QuestEvents.h"
#include "Engine/Quests/QuestLine.h"
#include "Entities/Platformer/Npcs/CastleValgrind/Tyracius.h"
#include "Entities/Platformer/Squally/Squally.h"
#include "Events/DialogueEvents.h"
#include "Events/PlatformerEvents.h"
#include "Objects/Platformer/Interactables/Doors/Portal.h"
#include "Scenes/Platformer/Components/Entities/Dialogue/EntityDialogueBehavior.h"
#include "Scenes/Platformer/Dialogue/DialogueSet.h"
#include "Scenes/Platformer/Dialogue/Voices.h"
#include "Scenes/Platformer/Level/Physics/PlatformerPhysicsTypes.h"
#include "Scenes/Platformer/Quests/CastleValgrind/CureKingLine/DefeatAgnes.h"
#include "Resources/EntityResources.h"
#include "Resources/SoundResources.h"
#include "Strings/Strings.h"
using namespace cocos2d;
const std::string OutsideThroneRoom::MapKeyQuest = "outside-throne-room";
OutsideThroneRoom* OutsideThroneRoom::create(GameObject* owner, QuestLine* questLine)
{
OutsideThroneRoom* instance = new OutsideThroneRoom(owner, questLine);
instance->autorelease();
return instance;
}
OutsideThroneRoom::OutsideThroneRoom(GameObject* owner, QuestLine* questLine) : super(owner, questLine, OutsideThroneRoom::MapKeyQuest, false)
{
}
OutsideThroneRoom::~OutsideThroneRoom()
{
}
void OutsideThroneRoom::onEnter()
{
super::onEnter();
}
void OutsideThroneRoom::onLoad(QuestState questState)
{
ObjectEvents::WatchForObject<Squally>(this, [=](Squally* squally)
{
this->squally = squally;
}, Squally::MapKey);
ObjectEvents::WatchForObject<Tyracius>(this, [=](Tyracius* tyracius)
{
this->tyracius = tyracius;
this->attachTyraciusBehavior();
}, Tyracius::MapKey);
}
void OutsideThroneRoom::onActivate(bool isActiveThroughSkippable, bool isInitialActivation)
{
}
void OutsideThroneRoom::attachTyraciusBehavior()
{
if (this->tyracius == nullptr)
{
return;
}
this->tyracius->watchForComponent<EntityDialogueBehavior>([=](EntityDialogueBehavior* interactionBehavior)
{
interactionBehavior->getMainDialogueSet()->addDialogueOption(DialogueOption::create(
Strings::Platformer_Quests_CastleValgrind_CureKing_Tyracius_A_WhatAreYouDoingHere::create(),
[=]()
{
if (this->questLine->isCompleteUpToInclusive(DefeatAgnes::MapKeyQuest))
{
DialogueEvents::TriggerOpenDialogue(DialogueEvents::DialogueOpenArgs(
Strings::Platformer_Quests_CastleValgrind_CureKing_Tyracius_S_StayHidden::create(),
DialogueEvents::DialogueVisualArgs(
DialogueBox::DialogueDock::Bottom,
DialogueBox::DialogueAlignment::Right,
DialogueEvents::BuildPreviewNode(&this->squally, false),
DialogueEvents::BuildPreviewNode(&this->tyracius, true)
),
[=]()
{
},
Voices::GetNextVoiceLong()
));
}
else
{
DialogueEvents::TriggerOpenDialogue(DialogueEvents::DialogueOpenArgs(
Strings::Platformer_Quests_CastleValgrind_CureKing_Tyracius_B_Coward::create(),
DialogueEvents::DialogueVisualArgs(
DialogueBox::DialogueDock::Bottom,
DialogueBox::DialogueAlignment::Right,
DialogueEvents::BuildPreviewNode(&this->squally, false),
DialogueEvents::BuildPreviewNode(&this->tyracius, true)
),
[=]()
{
},
Voices::GetNextVoiceLong()
));
}
}),
1.0f
);
});
}
void OutsideThroneRoom::onComplete()
{
}
void OutsideThroneRoom::onSkipped()
{
this->removeAllListeners();
}
| 0 | 0.864455 | 1 | 0.864455 | game-dev | MEDIA | 0.954465 | game-dev | 0.563765 | 1 | 0.563765 |
ProjectIgnis/CardScripts | 1,058 | unofficial/c511005643.lua | --Dandilion (Anime)
--scripted by GameMaster(GM)
--cleaned up by MLD
local s,id=GetID()
function s.initial_effect(c)
--token
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,0)
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsPlayerAffectedByEffect(tp,CARD_BLUEEYES_SPIRIT) or Duel.GetLocationCount(tp,LOCATION_MZONE)<=1
or not Duel.IsPlayerCanSpecialSummonMonster(tp,15341822,0,TYPES_TOKEN,0,0,1,RACE_PLANT,ATTRIBUTE_WIND) then return end
for i=1,2 do
local token=Duel.CreateToken(tp,15341821+i)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
Duel.SpecialSummonComplete()
end | 0 | 0.928896 | 1 | 0.928896 | game-dev | MEDIA | 0.98221 | game-dev | 0.93093 | 1 | 0.93093 |
libgdx/libgdx | 9,501 | extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btTranslationalLimitMotor2.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btTranslationalLimitMotor2 extends BulletBase {
private long swigCPtr;
protected btTranslationalLimitMotor2 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btTranslationalLimitMotor2, normally you should not need this constructor it's intended for low-level
* usage. */
public btTranslationalLimitMotor2 (long cPtr, boolean cMemoryOwn) {
this("btTranslationalLimitMotor2", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btTranslationalLimitMotor2 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btTranslationalLimitMotor2(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setLowerLimit (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_lowerLimit_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getLowerLimit () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_lowerLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setUpperLimit (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_upperLimit_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getUpperLimit () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_upperLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setBounce (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_bounce_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getBounce () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_bounce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setStopERP (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_stopERP_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getStopERP () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_stopERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setStopCFM (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_stopCFM_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getStopCFM () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_stopCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setMotorERP (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_motorERP_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getMotorERP () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_motorERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setMotorCFM (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_motorCFM_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getMotorCFM () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_motorCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setEnableMotor (boolean[] value) {
DynamicsJNI.btTranslationalLimitMotor2_enableMotor_set(swigCPtr, this, value);
}
public boolean[] getEnableMotor () {
return DynamicsJNI.btTranslationalLimitMotor2_enableMotor_get(swigCPtr, this);
}
public void setServoMotor (boolean[] value) {
DynamicsJNI.btTranslationalLimitMotor2_servoMotor_set(swigCPtr, this, value);
}
public boolean[] getServoMotor () {
return DynamicsJNI.btTranslationalLimitMotor2_servoMotor_get(swigCPtr, this);
}
public void setEnableSpring (boolean[] value) {
DynamicsJNI.btTranslationalLimitMotor2_enableSpring_set(swigCPtr, this, value);
}
public boolean[] getEnableSpring () {
return DynamicsJNI.btTranslationalLimitMotor2_enableSpring_get(swigCPtr, this);
}
public void setServoTarget (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_servoTarget_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getServoTarget () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_servoTarget_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setSpringStiffness (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_springStiffness_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getSpringStiffness () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_springStiffness_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setSpringStiffnessLimited (boolean[] value) {
DynamicsJNI.btTranslationalLimitMotor2_springStiffnessLimited_set(swigCPtr, this, value);
}
public boolean[] getSpringStiffnessLimited () {
return DynamicsJNI.btTranslationalLimitMotor2_springStiffnessLimited_get(swigCPtr, this);
}
public void setSpringDamping (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_springDamping_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getSpringDamping () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_springDamping_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setSpringDampingLimited (boolean[] value) {
DynamicsJNI.btTranslationalLimitMotor2_springDampingLimited_set(swigCPtr, this, value);
}
public boolean[] getSpringDampingLimited () {
return DynamicsJNI.btTranslationalLimitMotor2_springDampingLimited_get(swigCPtr, this);
}
public void setEquilibriumPoint (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_equilibriumPoint_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getEquilibriumPoint () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_equilibriumPoint_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setTargetVelocity (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_targetVelocity_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getTargetVelocity () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_targetVelocity_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setMaxMotorForce (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_maxMotorForce_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getMaxMotorForce () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_maxMotorForce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setCurrentLimitError (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_currentLimitError_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getCurrentLimitError () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_currentLimitError_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setCurrentLimitErrorHi (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_currentLimitErrorHi_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getCurrentLimitErrorHi () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_currentLimitErrorHi_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setCurrentLinearDiff (btVector3 value) {
DynamicsJNI.btTranslationalLimitMotor2_currentLinearDiff_set(swigCPtr, this, btVector3.getCPtr(value), value);
}
public btVector3 getCurrentLinearDiff () {
long cPtr = DynamicsJNI.btTranslationalLimitMotor2_currentLinearDiff_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3(cPtr, false);
}
public void setCurrentLimit (int[] value) {
DynamicsJNI.btTranslationalLimitMotor2_currentLimit_set(swigCPtr, this, value);
}
public int[] getCurrentLimit () {
return DynamicsJNI.btTranslationalLimitMotor2_currentLimit_get(swigCPtr, this);
}
public btTranslationalLimitMotor2 () {
this(DynamicsJNI.new_btTranslationalLimitMotor2__SWIG_0(), true);
}
public btTranslationalLimitMotor2 (btTranslationalLimitMotor2 other) {
this(DynamicsJNI.new_btTranslationalLimitMotor2__SWIG_1(btTranslationalLimitMotor2.getCPtr(other), other), true);
}
public boolean isLimited (int limitIndex) {
return DynamicsJNI.btTranslationalLimitMotor2_isLimited(swigCPtr, this, limitIndex);
}
public void testLimitValue (int limitIndex, float test_value) {
DynamicsJNI.btTranslationalLimitMotor2_testLimitValue(swigCPtr, this, limitIndex, test_value);
}
}
| 0 | 0.723513 | 1 | 0.723513 | game-dev | MEDIA | 0.829429 | game-dev | 0.734425 | 1 | 0.734425 |
ReikaKalseki/ChromatiCraft | 4,641 | Base/TileEntity/TileEntityChromaticBase.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.Base.TileEntity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import Reika.ChromatiCraft.ChromatiCraft;
import Reika.ChromatiCraft.Auxiliary.Interfaces.OwnedTile;
import Reika.ChromatiCraft.Auxiliary.Render.ChromaRenderList;
import Reika.ChromatiCraft.Registry.ChromaItems;
import Reika.ChromatiCraft.Registry.ChromaTiles;
import Reika.DragonAPI.ModList;
import Reika.DragonAPI.ASM.DependentMethodStripper.ModDependent;
import Reika.DragonAPI.Base.TileEntityRegistryBase;
import Reika.DragonAPI.Interfaces.TextureFetcher;
import Reika.DragonAPI.Interfaces.TileEntity.RenderFetcher;
import Reika.DragonAPI.Libraries.ReikaNBTHelper;
import Reika.DragonAPI.Libraries.ReikaNBTHelper.NBTTypes;
import Reika.DragonAPI.Libraries.ReikaPlayerAPI;
import li.cil.oc.api.network.Visibility;
public abstract class TileEntityChromaticBase extends TileEntityRegistryBase<ChromaTiles> implements RenderFetcher {
protected final HashSet<UUID> owners = new HashSet();
public final TextureFetcher getRenderer() {
if (this.getTile().hasRender())
return ChromaRenderList.getRenderForMachine(this.getTile());
else
return null;
}
@Override
protected final void onSetPlacer(EntityPlayer ep) {
this.addOwner(ep);
}
public final void addOwner(EntityPlayer ep) {
owners.add(ep.getUniqueID());
}
@Override
public final boolean allowTickAcceleration() {
return this.getTile().allowsAcceleration();
}
@Override
public final boolean canUpdate() {
return !ChromatiCraft.instance.isLocked();
}
@Override
protected void writeSyncTag(NBTTagCompound NBT) {
super.writeSyncTag(NBT);
}
@Override
protected void readSyncTag(NBTTagCompound NBT) {
super.readSyncTag(NBT);
}
@Override
public void writeToNBT(NBTTagCompound NBT) {
super.writeToNBT(NBT);
NBTTagList li = new NBTTagList();
for (UUID uid : owners) {
li.appendTag(new NBTTagString(uid.toString()));
}
NBT.setTag("owners", li);
}
@Override
public void readFromNBT(NBTTagCompound NBT) {
super.readFromNBT(NBT);
owners.clear();
NBTTagList li = NBT.getTagList("owners", NBTTypes.STRING.ID);
for (Object o : li.tagList) {
NBTTagString tag = (NBTTagString)o;
UUID uid = UUID.fromString(tag.func_150285_a_());
owners.add(uid);
}
}
@Override
public final boolean shouldRenderInPass(int pass) {
ChromaTiles r = this.getTile();
return pass == 0 || (r.renderInPass1() && pass == 1);
}
@Override
public int getRedstoneOverride() {
return 0;
}
@Override
@ModDependent(ModList.OPENCOMPUTERS)
public final Visibility getOCNetworkVisibility() {
return Visibility.Network;//this.getMachine().isPipe() ? Visibility.Neighbors : Visibility.Network;
}
public final boolean isOwnedByPlayer(EntityPlayer ep) {
return this.isOwnedByPlayer(ep.getUniqueID());
}
public final boolean isOwnedByPlayer(UUID id) {
return owners.isEmpty() || owners.contains(id);
}
public final Collection<EntityPlayer> getOwners(boolean allowFake) {
Collection<EntityPlayer> c = new ArrayList();
for (UUID uid : owners) {
EntityPlayer ep = worldObj.func_152378_a(uid);
if (ep != null && (allowFake || !ReikaPlayerAPI.isFake(ep))) {
c.add(ep);
}
}
return c;
}
public boolean onlyAllowOwnersToUse() {
return false;
}
public boolean onlyAllowOwnersToMine() {
return true;
}
public boolean renderModelsInPass1() {
return false;
}
protected final void writeOwnerData(NBTTagCompound NBT) {
if (this instanceof OwnedTile && !owners.isEmpty())
ReikaNBTHelper.writeCollectionToNBT(owners, NBT, "owners", ReikaNBTHelper.UUIDConverter.instance);
}
protected final void readOwnerData(ItemStack is) {
if (ChromaItems.PLACER.matchWith(is)) {
if (is.getItemDamage() == this.getTile().ordinal()) {
if (is.stackTagCompound != null && is.stackTagCompound.hasKey("owners")) {
if (this instanceof OwnedTile) {
ReikaNBTHelper.readCollectionFromNBT(owners, is.stackTagCompound, "owners", ReikaNBTHelper.UUIDConverter.instance);
}
}
}
}
}
}
| 0 | 0.869681 | 1 | 0.869681 | game-dev | MEDIA | 0.985206 | game-dev | 0.934132 | 1 | 0.934132 |
PhysikaTeam/PhysIKA-old | 8,554 | Extern/freeglut-3.2.1/src/mswin/fg_joystick_mswin.c | /*
* fg_joystick_mswin.c
*
* The Windows-specific mouse cursor related stuff.
*
* Copyright (c) 2012 Stephen J. Baker. All Rights Reserved.
* Written by John F. Fay, <fayjf@sourceforge.net>
* Creation date: Sat Jan 28, 2012
*
* 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
* PAWEL W. OLSZTA 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 <GL/freeglut.h>
#include "../fg_internal.h"
#if !defined(_WIN32_WCE)
# include <windows.h>
# include <mmsystem.h>
# include <regstr.h>
void fgPlatformJoystickRawRead( SFG_Joystick* joy, int* buttons, float* axes )
{
MMRESULT status;
status = joyGetPosEx( joy->pJoystick.js_id, &joy->pJoystick.js );
if ( status != JOYERR_NOERROR )
{
joy->error = GL_TRUE;
return;
}
if ( buttons )
*buttons = joy->pJoystick.js.dwButtons;
if ( axes )
{
/*
* WARNING - Fall through case clauses!!
*/
switch ( joy->num_axes )
{
case 8:
/* Generate two POV axes from the POV hat angle.
* Low 16 bits of js.dwPOV gives heading (clockwise from ahead) in
* hundredths of a degree, or 0xFFFF when idle.
*/
if ( ( joy->pJoystick.js.dwPOV & 0xFFFF ) == 0xFFFF )
{
axes [ 6 ] = 0.0;
axes [ 7 ] = 0.0;
}
else
{
/* This is the contentious bit: how to convert angle to X/Y.
* wk: I know of no define for PI that we could use here:
* SG_PI would pull in sg, M_PI is undefined for MSVC
* But the accuracy of the value of PI is very unimportant at
* this point.
*/
float s = (float) sin ( ( joy->pJoystick.js.dwPOV & 0xFFFF ) * ( 0.01 * 3.1415926535f / 180.0f ) );
float c = (float) cos ( ( joy->pJoystick.js.dwPOV & 0xFFFF ) * ( 0.01 * 3.1415926535f / 180.0f ) );
/* Convert to coordinates on a square so that North-East
* is (1,1) not (.7,.7), etc.
* s and c cannot both be zero so we won't divide by zero.
*/
if ( fabs ( s ) < fabs ( c ) )
{
axes [ 6 ] = ( c < 0.0 ) ? -s/c : s/c ;
axes [ 7 ] = ( c < 0.0 ) ? -1.0f : 1.0f;
}
else
{
axes [ 6 ] = ( s < 0.0 ) ? -1.0f : 1.0f;
axes [ 7 ] = ( s < 0.0 ) ? -c/s : c/s ;
}
}
case 6: axes[5] = (float) joy->pJoystick.js.dwVpos;
case 5: axes[4] = (float) joy->pJoystick.js.dwUpos;
case 4: axes[3] = (float) joy->pJoystick.js.dwRpos;
case 3: axes[2] = (float) joy->pJoystick.js.dwZpos;
case 2: axes[1] = (float) joy->pJoystick.js.dwYpos;
case 1: axes[0] = (float) joy->pJoystick.js.dwXpos;
}
}
}
/* Inspired by
http://msdn.microsoft.com/archive/en-us/dnargame/html/msdn_sidewind3d.asp
*/
# if FREEGLUT_LIB_PRAGMAS
# pragma comment (lib, "advapi32.lib")
# endif
static int fghJoystickGetOEMProductName ( SFG_Joystick* joy, char *buf, int buf_sz )
{
char buffer [ 256 ];
char OEMKey [ 256 ];
HKEY hKey;
DWORD dwcb;
LONG lr;
if ( joy->error )
return 0;
/* Open .. MediaResources\CurrentJoystickSettings */
_snprintf ( buffer, sizeof(buffer), "%s\\%s\\%s",
REGSTR_PATH_JOYCONFIG, joy->pJoystick.jsCaps.szRegKey,
REGSTR_KEY_JOYCURR );
lr = RegOpenKeyEx ( HKEY_LOCAL_MACHINE, buffer, 0, KEY_QUERY_VALUE, &hKey);
if ( lr != ERROR_SUCCESS ) return 0;
/* Get OEM Key name */
dwcb = sizeof(OEMKey);
/* JOYSTICKID1-16 is zero-based; registry entries for VJOYD are 1-based. */
_snprintf ( buffer, sizeof(buffer), "Joystick%d%s", joy->pJoystick.js_id + 1, REGSTR_VAL_JOYOEMNAME );
lr = RegQueryValueEx ( hKey, buffer, 0, 0, (LPBYTE) OEMKey, &dwcb);
RegCloseKey ( hKey );
if ( lr != ERROR_SUCCESS ) return 0;
/* Open OEM Key from ...MediaProperties */
_snprintf ( buffer, sizeof(buffer), "%s\\%s", REGSTR_PATH_JOYOEM, OEMKey );
lr = RegOpenKeyEx ( HKEY_LOCAL_MACHINE, buffer, 0, KEY_QUERY_VALUE, &hKey );
if ( lr != ERROR_SUCCESS ) return 0;
/* Get OEM Name */
dwcb = buf_sz;
lr = RegQueryValueEx ( hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, (LPBYTE) buf,
&dwcb );
RegCloseKey ( hKey );
if ( lr != ERROR_SUCCESS ) return 0;
return 1;
}
void fgPlatformJoystickOpen( SFG_Joystick* joy )
{
int i = 0;
joy->pJoystick.js.dwFlags = JOY_RETURNALL;
joy->pJoystick.js.dwSize = sizeof( joy->pJoystick.js );
memset( &joy->pJoystick.jsCaps, 0, sizeof( joy->pJoystick.jsCaps ) );
joy->error =
( joyGetDevCaps( joy->pJoystick.js_id, &joy->pJoystick.jsCaps, sizeof( joy->pJoystick.jsCaps ) ) !=
JOYERR_NOERROR );
if( joy->pJoystick.jsCaps.wNumAxes == 0 )
{
joy->num_axes = 0;
joy->error = GL_TRUE;
}
else
{
/* Device name from jsCaps is often "Microsoft PC-joystick driver",
* at least for USB. Try to get the real name from the registry.
*/
if ( ! fghJoystickGetOEMProductName( joy, joy->name,
sizeof( joy->name ) ) )
{
fgWarning( "JS: Failed to read joystick name from registry" );
strncpy( joy->name, joy->pJoystick.jsCaps.szPname, sizeof( joy->name ) );
}
/* Windows joystick drivers may provide any combination of
* X,Y,Z,R,U,V,POV - not necessarily the first n of these.
*/
if( joy->pJoystick.jsCaps.wCaps & JOYCAPS_HASPOV )
{
joy->num_axes = _JS_MAX_AXES;
joy->min[ 7 ] = -1.0; joy->max[ 7 ] = 1.0; /* POV Y */
joy->min[ 6 ] = -1.0; joy->max[ 6 ] = 1.0; /* POV X */
}
else
joy->num_axes = 6;
joy->min[ 5 ] = ( float )joy->pJoystick.jsCaps.wVmin;
joy->max[ 5 ] = ( float )joy->pJoystick.jsCaps.wVmax;
joy->min[ 4 ] = ( float )joy->pJoystick.jsCaps.wUmin;
joy->max[ 4 ] = ( float )joy->pJoystick.jsCaps.wUmax;
joy->min[ 3 ] = ( float )joy->pJoystick.jsCaps.wRmin;
joy->max[ 3 ] = ( float )joy->pJoystick.jsCaps.wRmax;
joy->min[ 2 ] = ( float )joy->pJoystick.jsCaps.wZmin;
joy->max[ 2 ] = ( float )joy->pJoystick.jsCaps.wZmax;
joy->min[ 1 ] = ( float )joy->pJoystick.jsCaps.wYmin;
joy->max[ 1 ] = ( float )joy->pJoystick.jsCaps.wYmax;
joy->min[ 0 ] = ( float )joy->pJoystick.jsCaps.wXmin;
joy->max[ 0 ] = ( float )joy->pJoystick.jsCaps.wXmax;
}
/* Guess all the rest judging on the axes extremals */
for( i = 0; i < joy->num_axes; i++ )
{
joy->center [ i ] = ( joy->max[ i ] + joy->min[ i ] ) * 0.5f;
joy->dead_band[ i ] = 0.0f;
joy->saturate [ i ] = 1.0f;
}
}
void fgPlatformJoystickInit( SFG_Joystick *fgJoystick[], int ident )
{
switch( ident )
{
case 0:
fgJoystick[ ident ]->pJoystick.js_id = JOYSTICKID1;
fgJoystick[ ident ]->error = GL_FALSE;
break;
case 1:
fgJoystick[ ident ]->pJoystick.js_id = JOYSTICKID2;
fgJoystick[ ident ]->error = GL_FALSE;
break;
default:
fgJoystick[ ident ]->num_axes = 0;
fgJoystick[ ident ]->error = GL_TRUE;
return;
}
}
void fgPlatformJoystickClose ( int ident )
{
/* Do nothing special */
}
#endif
| 0 | 0.686642 | 1 | 0.686642 | game-dev | MEDIA | 0.334239 | game-dev | 0.699587 | 1 | 0.699587 |
DaVikingCode/Citrus-Engine-Examples | 4,508 | src/games/live4sales/assets/Assets.as | package games.live4sales.assets {
import starling.text.BitmapFont;
import starling.text.TextField;
import starling.textures.Texture;
import starling.textures.TextureAtlas;
import flash.display.Bitmap;
import flash.media.Sound;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
public class Assets
{
// If you're developing a game for the Flash Player / browser plugin, you can directly
// embed all textures directly in this class. This demo, however, provides two sets of
// textures for different resolutions. That's useful especially for mobile development,
// where you have to support devices with different resolutions.
//
// For that reason, the actual embed statements are in separate files; one for each
// set of textures. The correct set is chosen depending on the "contentScaleFactor".
// true type fonts
//[Embed(source="../media/fonts/Ubuntu-R.ttf", embedAsCFF="false", fontFamily="Ubuntu")]
//private static const UbuntuRegular:Class;
// sounds
//[Embed(source="../media/audio/click.mp3")]
//private static const Click:Class;
// static members
[Embed(source="/../embed/games/live4sales/background.png")]
public static const BackgroundPng:Class;
private static var sContentScaleFactor:int = 1;
private static var sTextures:Dictionary = new Dictionary();
private static var sSounds:Dictionary = new Dictionary();
private static var sTextureAtlas:TextureAtlas;
private static var sBitmapFontsLoaded:Boolean;
public static function getTexture(name:String):Texture
{
if (sTextures[name] == undefined)
{
var data:Object = create(name);
if (data is Bitmap)
sTextures[name] = Texture.fromBitmap(data as Bitmap, true, false, sContentScaleFactor);
else if (data is ByteArray)
sTextures[name] = Texture.fromAtfData(data as ByteArray, sContentScaleFactor);
}
return sTextures[name];
}
public static function getAtlasTexture(textureName:String, atlasName:String):Texture
{
prepareAtlas(atlasName);
return sTextureAtlas.getTexture(textureName);
}
public static function getAtlasTextures(prefix:String):Vector.<Texture>
{
prepareAtlas();
return sTextureAtlas.getTextures(prefix);
}
public static function getTextureAtlas(name:String):TextureAtlas {
prepareAtlas(name);
return sTextureAtlas;
}
public static function getSound(name:String):Sound
{
var sound:Sound = sSounds[name] as Sound;
if (sound) return sound;
else throw new ArgumentError("Sound not found: " + name);
}
public static function loadBitmapFonts():void
{
if (!sBitmapFontsLoaded)
{
var texture:Texture = getTexture("DesyrelTexture");
var xml:XML = XML(create("DesyrelXml"));
TextField.registerBitmapFont(new BitmapFont(texture, xml));
sBitmapFontsLoaded = true;
}
}
public static function prepareSounds():void
{
// sSounds["Click"] = new Click();
}
private static function prepareAtlas(name:String = ""):void
{
var texture:Texture;
var xml:XML;
texture = getTexture(name + "Png");
xml = XML(create(name + "Config"));
sTextureAtlas = new TextureAtlas(texture, xml);
}
private static function create(name:String):Object
{
var textureClass:Class = sContentScaleFactor == 1 ? AssetEmbeds_1x : AssetEmbeds_2x;
return new textureClass[name];
}
public static function get contentScaleFactor():Number { return sContentScaleFactor; }
public static function set contentScaleFactor(value:Number):void
{
for each (var texture:Texture in sTextures)
texture.dispose();
sTextures = new Dictionary();
sContentScaleFactor = value < 1.5 ? 1 : 2; // assets are available for factor 1 and 2
}
}
}
| 0 | 0.796883 | 1 | 0.796883 | game-dev | MEDIA | 0.686441 | game-dev,graphics-rendering | 0.919889 | 1 | 0.919889 |
Doom2D/Doom2D-Forever | 40,870 | src/game/g_panel.pas | (* Copyright (C) 2016 - The Doom2D.org team & involved community members <http://www.doom2d.org>.
* This file is part of Doom2D Forever.
*
* 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, version 3 of
* the License ONLY.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*)
{$INCLUDE ../shared/a_modes.inc}
{$M+}
unit g_panel;
interface
uses
SysUtils, Classes,
MAPDEF, g_textures, xdynrec;
type
TAddTextureArray = Array of
record
Texture: Cardinal;
Anim: Boolean;
end;
PPanel = ^TPanel;
TPanel = Class (TObject)
private
const
private
mGUID: Integer; // will be assigned in "g_map.pas"
FTextureWidth: Word;
FTextureHeight: Word;
FAlpha: Byte;
FBlending: Boolean;
FTextureIDs: Array of
record
case Anim: Boolean of
False: (Tex: Cardinal);
True: (AnTex: TAnimation);
end;
mMovingSpeed: TDFPoint;
mMovingStart: TDFPoint;
mMovingEnd: TDFPoint;
mMovingActive: Boolean;
mMoveOnce: Boolean;
mOldMovingActive: Boolean;
mSizeSpeed: TDFSize;
mSizeEnd: TDFSize;
mEndPosTrig: Integer;
mEndSizeTrig: Integer;
mNeedSend: Boolean; // for network
private
function getx1 (): Integer; inline;
function gety1 (): Integer; inline;
function getvisvalid (): Boolean; inline;
function getMovingSpeedX (): Integer; inline;
procedure setMovingSpeedX (v: Integer); inline;
function getMovingSpeedY (): Integer; inline;
procedure setMovingSpeedY (v: Integer); inline;
function getMovingStartX (): Integer; inline;
procedure setMovingStartX (v: Integer); inline;
function getMovingStartY (): Integer; inline;
procedure setMovingStartY (v: Integer); inline;
function getMovingEndX (): Integer; inline;
procedure setMovingEndX (v: Integer); inline;
function getMovingEndY (): Integer; inline;
procedure setMovingEndY (v: Integer); inline;
function getSizeSpeedX (): Integer; inline;
procedure setSizeSpeedX (v: Integer); inline;
function getSizeSpeedY (): Integer; inline;
procedure setSizeSpeedY (v: Integer); inline;
function getSizeEndX (): Integer; inline;
procedure setSizeEndX (v: Integer); inline;
function getSizeEndY (): Integer; inline;
procedure setSizeEndY (v: Integer); inline;
public
FCurTexture: Integer; //
FCurFrame: Integer;
FCurFrameCount: Byte;
FX, FY: Integer;
FOldX, FOldY: Integer;
FWidth, FHeight: Word;
FOldW, FOldH: Word;
FPanelType: Word;
FEnabled: Boolean;
FDoor: Boolean;
FLiftType: Byte;
FLastAnimLoop: Byte;
// sorry, there fields are public to allow setting 'em in g_map; this should be fixed later
// for now, PLEASE, don't modify 'em, or all hell will break loose
arrIdx: Integer; // index in one of internal arrays; sorry
tag: Integer; // used in coldets and such; sorry; see g_map.GridTagXXX
proxyId: Integer; // proxy id in map grid (DO NOT USE!)
mapId: AnsiString; // taken directly from map file; dunno why it is here
hasTexTrigger: Boolean; // HACK: true when there's a trigger than can change my texture
constructor Create(PanelRec: TDynRecord;
AddTextures: TAddTextureArray;
CurTex: Integer;
var Textures: TLevelTextureArray; aguid: Integer);
destructor Destroy(); override;
procedure Draw (hasAmbient: Boolean; constref ambColor: TDFColor);
procedure DrawShadowVolume(lightX, lightY, radius: Integer);
procedure Update();
procedure SetFrame(Frame: Integer; Count: Byte);
procedure NextTexture(AnimLoop: Byte = 0);
procedure SetTexture(ID: Integer; AnimLoop: Byte = 0);
function GetTextureID(): Cardinal;
function GetTextureCount(): Integer;
function CanChangeTexture(): Boolean;
procedure SaveState (st: TStream);
procedure LoadState (st: TStream);
procedure positionChanged (); inline;
function getIsGBack (): Boolean; inline; // gRenderBackgrounds
function getIsGStep (): Boolean; inline; // gSteps
function getIsGWall (): Boolean; inline; // gWalls
function getIsGAcid1 (): Boolean; inline; // gAcid1
function getIsGAcid2 (): Boolean; inline; // gAcid2
function getIsGWater (): Boolean; inline; // gWater
function getIsGFore (): Boolean; inline; // gRenderForegrounds
function getIsGLift (): Boolean; inline; // gLifts
function getIsGBlockMon (): Boolean; inline; // gBlockMon
// get-and-clear
function gncNeedSend (): Boolean; inline;
procedure setDirty (); inline; // why `dirty`? 'cause i may introduce property `needSend` later
procedure lerp (t: Single; out tX, tY, tW, tH: Integer);
public
property visvalid: Boolean read getvisvalid; // panel is "visvalid" when it's width and height are positive
published
property guid: Integer read mGUID; // will be assigned in "g_map.pas"
property x0: Integer read FX;
property y0: Integer read FY;
property x1: Integer read getx1; // inclusive!
property y1: Integer read gety1; // inclusive!
property x: Integer read FX write FX;
property y: Integer read FY write FY;
property width: Word read FWidth write FWidth;
property height: Word read FHeight write FHeight;
property panelType: Word read FPanelType write FPanelType;
property enabled: Boolean read FEnabled write FEnabled;
property door: Boolean read FDoor write FDoor;
property liftType: Byte read FLiftType write FLiftType;
property lastAnimLoop: Byte read FLastAnimLoop write FLastAnimLoop;
property movingSpeedX: Integer read getMovingSpeedX write setMovingSpeedX;
property movingSpeedY: Integer read getMovingSpeedY write setMovingSpeedY;
property movingStartX: Integer read getMovingStartX write setMovingStartX;
property movingStartY: Integer read getMovingStartY write setMovingStartY;
property movingEndX: Integer read getMovingEndX write setMovingEndX;
property movingEndY: Integer read getMovingEndY write setMovingEndY;
property movingActive: Boolean read mMovingActive write mMovingActive;
property moveOnce: Boolean read mMoveOnce write mMoveOnce;
property sizeSpeedX: Integer read getSizeSpeedX write setSizeSpeedX;
property sizeSpeedY: Integer read getSizeSpeedY write setSizeSpeedY;
property sizeEndX: Integer read getSizeEndX write setSizeEndX;
property sizeEndY: Integer read getSizeEndY write setSizeEndY;
property isGBack: Boolean read getIsGBack;
property isGStep: Boolean read getIsGStep;
property isGWall: Boolean read getIsGWall;
property isGAcid1: Boolean read getIsGAcid1;
property isGAcid2: Boolean read getIsGAcid2;
property isGWater: Boolean read getIsGWater;
property isGFore: Boolean read getIsGFore;
property isGLift: Boolean read getIsGLift;
property isGBlockMon: Boolean read getIsGBlockMon;
public
property movingSpeed: TDFPoint read mMovingSpeed write mMovingSpeed;
property movingStart: TDFPoint read mMovingStart write mMovingStart;
property movingEnd: TDFPoint read mMovingEnd write mMovingEnd;
property sizeSpeed: TDFSize read mSizeSpeed write mSizeSpeed;
property sizeEnd: TDFSize read mSizeEnd write mSizeEnd;
property endPosTrigId: Integer read mEndPosTrig write mEndPosTrig;
property endSizeTrigId: Integer read mEndSizeTrig write mEndSizeTrig;
end;
TPanelArray = Array of TPanel;
const
LIFTTYPE_UP = 0;
LIFTTYPE_DOWN = 1;
LIFTTYPE_LEFT = 2;
LIFTTYPE_RIGHT = 3;
var
g_dbgpan_mplat_active: Boolean = {$IF DEFINED(D2F_DEBUG)}true{$ELSE}true{$ENDIF};
g_dbgpan_mplat_step: Boolean = false; // one step, and stop
implementation
uses
{$INCLUDE ../nogl/noGLuses.inc}
e_texture, g_basic, g_map, g_game, g_gfx, e_graphics, g_weapons, g_triggers, g_items,
g_console, g_language, g_monsters, g_player, g_grid, e_log, geom, utils, xstreams;
const
PANEL_SIGNATURE = $4C4E4150; // 'PANL'
{ T P a n e l : }
constructor TPanel.Create(PanelRec: TDynRecord;
AddTextures: TAddTextureArray;
CurTex: Integer;
var Textures: TLevelTextureArray; aguid: Integer);
var
i: Integer;
tnum: Integer;
begin
X := PanelRec.X;
Y := PanelRec.Y;
FOldX := X;
FOldY := Y;
Width := PanelRec.Width;
Height := PanelRec.Height;
FOldW := Width;
FOldH := Height;
FAlpha := 0;
FBlending := False;
FCurFrame := 0;
FCurFrameCount := 0;
LastAnimLoop := 0;
mapId := PanelRec.id;
mGUID := aguid;
mMovingSpeed := PanelRec.moveSpeed;
mMovingStart := PanelRec.moveStart;
mMovingEnd := PanelRec.moveEnd;
mMovingActive := PanelRec['move_active'].value;
mOldMovingActive := mMovingActive;
mMoveOnce := PanelRec.moveOnce;
mSizeSpeed := PanelRec.sizeSpeed;
mSizeEnd := PanelRec.sizeEnd;
mEndPosTrig := PanelRec.endPosTrig;
mEndSizeTrig := PanelRec.endSizeTrig;
mNeedSend := false;
// :
PanelType := PanelRec.PanelType;
Enabled := True;
Door := False;
LiftType := LIFTTYPE_UP;
hasTexTrigger := False;
case PanelType of
PANEL_OPENDOOR: begin Enabled := False; Door := True; end;
PANEL_CLOSEDOOR: Door := True;
PANEL_LIFTUP: LiftType := LIFTTYPE_UP; //???
PANEL_LIFTDOWN: LiftType := LIFTTYPE_DOWN;
PANEL_LIFTLEFT: LiftType := LIFTTYPE_LEFT;
PANEL_LIFTRIGHT: LiftType := LIFTTYPE_RIGHT;
end;
// :
if ByteBool(PanelRec.Flags and PANEL_FLAG_HIDE) then
begin
SetLength(FTextureIDs, 0);
FCurTexture := -1;
Exit;
end;
// , :
if ByteBool(PanelType and
(PANEL_LIFTUP or
PANEL_LIFTDOWN or
PANEL_LIFTLEFT or
PANEL_LIFTRIGHT or
PANEL_BLOCKMON)) then
begin
SetLength(FTextureIDs, 0);
FCurTexture := -1;
Exit;
end;
// - :
if WordBool(PanelType and (PANEL_WATER or PANEL_ACID1 or PANEL_ACID2)) and
(not ByteBool(PanelRec.Flags and PANEL_FLAG_WATERTEXTURES)) then
begin
SetLength(FTextureIDs, 1);
FTextureIDs[0].Anim := False;
case PanelRec.PanelType of
PANEL_WATER:
FTextureIDs[0].Tex := LongWord(TEXTURE_SPECIAL_WATER);
PANEL_ACID1:
FTextureIDs[0].Tex := LongWord(TEXTURE_SPECIAL_ACID1);
PANEL_ACID2:
FTextureIDs[0].Tex := LongWord(TEXTURE_SPECIAL_ACID2);
end;
FCurTexture := 0;
Exit;
end;
SetLength(FTextureIDs, Length(AddTextures));
if CurTex < 0 then
FCurTexture := -1
else
if CurTex >= Length(FTextureIDs) then
FCurTexture := Length(FTextureIDs) - 1
else
FCurTexture := CurTex;
for i := 0 to Length(FTextureIDs)-1 do
begin
FTextureIDs[i].Anim := AddTextures[i].Anim;
if FTextureIDs[i].Anim then
begin //
FTextureIDs[i].AnTex :=
TAnimation.Create(Textures[AddTextures[i].Texture].FramesID,
True, Textures[AddTextures[i].Texture].Speed);
FTextureIDs[i].AnTex.Blending := ByteBool(PanelRec.Flags and PANEL_FLAG_BLENDING);
FTextureIDs[i].AnTex.Alpha := PanelRec.Alpha;
end
else
begin //
FTextureIDs[i].Tex := Textures[AddTextures[i].Texture].TextureID;
end;
end;
// - :
//if Length(FTextureIDs) > 1 then SaveIt := True;
if (PanelRec.TextureRec = nil) then tnum := -1 else tnum := PanelRec.tagInt;
if (tnum < 0) then tnum := Length(Textures);
// , :
if ({PanelRec.TextureNum}tnum > High(Textures)) then
begin
e_WriteLog(Format('WTF?! tnum is out of limits! (%d : %d)', [tnum, High(Textures)]), TMsgType.Warning);
FTextureWidth := 2;
FTextureHeight := 2;
FAlpha := 0;
FBlending := ByteBool(0);
end
else if not g_Map_IsSpecialTexture(Textures[{PanelRec.TextureNum}tnum].TextureName) then
begin
FTextureWidth := Textures[{PanelRec.TextureNum}tnum].Width;
FTextureHeight := Textures[{PanelRec.TextureNum}tnum].Height;
FAlpha := PanelRec.Alpha;
FBlending := ByteBool(PanelRec.Flags and PANEL_FLAG_BLENDING);
end;
end;
destructor TPanel.Destroy();
var
i: Integer;
begin
for i := 0 to High(FTextureIDs) do
if FTextureIDs[i].Anim then
FTextureIDs[i].AnTex.Free();
SetLength(FTextureIDs, 0);
Inherited;
end;
procedure TPanel.lerp (t: Single; out tX, tY, tW, tH: Integer);
begin
if mMovingActive then
begin
tX := nlerp(FOldX, FX, t);
tY := nlerp(FOldY, FY, t);
tW := nlerp(FOldW, FWidth, t);
tH := nlerp(FOldH, FHeight, t);
end
else
begin
tX := FX;
tY := FY;
tW := FWidth;
tH := FHeight;
end;
end;
function TPanel.getx1 (): Integer; inline; begin result := X+Width-1; end;
function TPanel.gety1 (): Integer; inline; begin result := Y+Height-1; end;
function TPanel.getvisvalid (): Boolean; inline; begin result := (Width > 0) and (Height > 0); end;
function TPanel.getMovingSpeedX (): Integer; inline; begin result := mMovingSpeed.X; end;
procedure TPanel.setMovingSpeedX (v: Integer); inline; begin mMovingSpeed.X := v; end;
function TPanel.getMovingSpeedY (): Integer; inline; begin result := mMovingSpeed.Y; end;
procedure TPanel.setMovingSpeedY (v: Integer); inline; begin mMovingSpeed.Y := v; end;
function TPanel.getMovingStartX (): Integer; inline; begin result := mMovingStart.X; end;
procedure TPanel.setMovingStartX (v: Integer); inline; begin mMovingStart.X := v; end;
function TPanel.getMovingStartY (): Integer; inline; begin result := mMovingStart.Y; end;
procedure TPanel.setMovingStartY (v: Integer); inline; begin mMovingStart.Y := v; end;
function TPanel.getMovingEndX (): Integer; inline; begin result := mMovingEnd.X; end;
procedure TPanel.setMovingEndX (v: Integer); inline; begin mMovingEnd.X := v; end;
function TPanel.getMovingEndY (): Integer; inline; begin result := mMovingEnd.Y; end;
procedure TPanel.setMovingEndY (v: Integer); inline; begin mMovingEnd.Y := v; end;
function TPanel.getSizeSpeedX (): Integer; inline; begin result := mSizeSpeed.w; end;
procedure TPanel.setSizeSpeedX (v: Integer); inline; begin mSizeSpeed.w := v; end;
function TPanel.getSizeSpeedY (): Integer; inline; begin result := mSizeSpeed.h; end;
procedure TPanel.setSizeSpeedY (v: Integer); inline; begin mSizeSpeed.h := v; end;
function TPanel.getSizeEndX (): Integer; inline; begin result := mSizeEnd.w; end;
procedure TPanel.setSizeEndX (v: Integer); inline; begin mSizeEnd.w := v; end;
function TPanel.getSizeEndY (): Integer; inline; begin result := mSizeEnd.h; end;
procedure TPanel.setSizeEndY (v: Integer); inline; begin mSizeEnd.h := v; end;
function TPanel.getIsGBack (): Boolean; inline; begin result := ((tag and GridTagBack) <> 0); end;
function TPanel.getIsGStep (): Boolean; inline; begin result := ((tag and GridTagStep) <> 0); end;
function TPanel.getIsGWall (): Boolean; inline; begin result := ((tag and (GridTagWall or GridTagDoor)) <> 0); end;
function TPanel.getIsGAcid1 (): Boolean; inline; begin result := ((tag and GridTagAcid1) <> 0); end;
function TPanel.getIsGAcid2 (): Boolean; inline; begin result := ((tag and GridTagAcid2) <> 0); end;
function TPanel.getIsGWater (): Boolean; inline; begin result := ((tag and GridTagWater) <> 0); end;
function TPanel.getIsGFore (): Boolean; inline; begin result := ((tag and GridTagFore) <> 0); end;
function TPanel.getIsGLift (): Boolean; inline; begin result := ((tag and GridTagLift) <> 0); end;
function TPanel.getIsGBlockMon (): Boolean; inline; begin result := ((tag and GridTagBlockMon) <> 0); end;
function TPanel.gncNeedSend (): Boolean; inline; begin result := mNeedSend; mNeedSend := false; end;
procedure TPanel.setDirty (); inline; begin mNeedSend := true; end;
procedure TPanel.Draw (hasAmbient: Boolean; constref ambColor: TDFColor);
var
tx, ty, tw, th: Integer;
xx, yy: Integer;
NoTextureID: DWORD;
NW, NH: Word;
begin
// TODO: Eliminate the remaining checks here? Like, they have to be done beforehand by the entity
// gathering code during preparation for rendering. See g_Map_CollectDrawPanels() for example.
if {Enabled and} (FCurTexture >= 0) and (Width > 0) and (Height > 0) and (FAlpha < 255) {and
g_Collide(X, Y, Width, Height, sX, sY, sWidth, sHeight)} then
begin
lerp(gLerpFactor, tx, ty, tw, th);
if FTextureIDs[FCurTexture].Anim then
begin //
if FTextureIDs[FCurTexture].AnTex = nil then
Exit;
for xx := 0 to (tw div FTextureWidth)-1 do
for yy := 0 to (th div FTextureHeight)-1 do
FTextureIDs[FCurTexture].AnTex.Draw(
tx + xx*FTextureWidth,
ty + yy*FTextureHeight, TMirrorType.None);
end
else
begin //
case FTextureIDs[FCurTexture].Tex of
LongWord(TEXTURE_SPECIAL_WATER): e_DrawFillQuad(tx, ty, tx+tw-1, ty+th-1, 0, 0, 255, 0, TBlending.Filter);
LongWord(TEXTURE_SPECIAL_ACID1): e_DrawFillQuad(tx, ty, tx+tw-1, ty+th-1, 0, 230, 0, 0, TBlending.Filter);
LongWord(TEXTURE_SPECIAL_ACID2): e_DrawFillQuad(tx, ty, tx+tw-1, ty+th-1, 230, 0, 0, 0, TBlending.Filter);
LongWord(TEXTURE_NONE):
if g_Texture_Get('NOTEXTURE', NoTextureID) then
begin
e_GetTextureSize(NoTextureID, @NW, @NH);
e_DrawFill(NoTextureID, tx, ty, tw div NW, th div NH, 0, False, False);
end
else
begin
xx := tx + (tw div 2);
yy := ty + (th div 2);
e_DrawFillQuad(tx, ty, xx, yy, 255, 0, 255, 0);
e_DrawFillQuad(xx, ty, tx+tw-1, yy, 255, 255, 0, 0);
e_DrawFillQuad(tx, yy, xx, ty+th-1, 255, 255, 0, 0);
e_DrawFillQuad(xx, yy, tx+tw-1, ty+th-1, 255, 0, 255, 0);
end;
else
begin
if not mMovingActive then
e_DrawFill(FTextureIDs[FCurTexture].Tex, tx, ty, tw div FTextureWidth, th div FTextureHeight, FAlpha, True, FBlending, hasAmbient)
else
e_DrawFillX(FTextureIDs[FCurTexture].Tex, tx, ty, tw, th, FAlpha, True, FBlending, g_dbg_scale, hasAmbient);
if hasAmbient then e_AmbientQuad(tx, ty, tw, th, ambColor.r, ambColor.g, ambColor.b, ambColor.a);
end;
end;
end;
end;
end;
procedure TPanel.DrawShadowVolume(lightX, lightY, radius: Integer);
var
tx, ty, tw, th: Integer;
procedure extrude (x, y: Integer); inline;
begin
// TODO: 500 here is "infinity" (actually a "large enough" value). The general case would be to
// calculate a value from the light's size, truly sufficient to clip it regardless of radius.
glVertex2i(x+(x-lightX)*500, y+(y-lightY)*500);
//e_WriteLog(Format(' : (%d,%d)', [x+(x-lightX)*300, y+(y-lightY)*300]), MSG_WARNING);
end;
procedure drawLine (x0, y0, x1, y1: Integer); inline;
begin
// Optimization: check if this side of the panel is facing the light. It is enough to extrude
// only such edges, and not the whole panel, in the direction of the light to be trimmed by it.
if (x1-x0)*(lightY-y0)-(lightX-x0)*(y1-y0) >= 0 then Exit;
//e_WriteLog(Format('lightpan: (%d,%d)-(%d,%d)', [x0, y0, x1, y1]), MSG_WARNING);
glVertex2i(x0, y0);
glVertex2i(x1, y1);
extrude(x1, y1);
extrude(x0, y0);
end;
begin
if Enabled and (FCurTexture >= 0) and (Width > 0) and (Height > 0) and (FAlpha < 255) {and
g_Collide(X, Y, tw, th, sX, sY, sWidth, sHeight)} then
begin
lerp(gLerpFactor, tx, ty, tw, th);
if not FTextureIDs[FCurTexture].Anim then
begin
case FTextureIDs[FCurTexture].Tex of
LongWord(TEXTURE_SPECIAL_WATER): Exit;
LongWord(TEXTURE_SPECIAL_ACID1): Exit;
LongWord(TEXTURE_SPECIAL_ACID2): Exit;
LongWord(TEXTURE_NONE): Exit;
end;
end;
if tx+tw < lightX-radius then Exit;
if ty+th < lightY-radius then Exit;
if tx > lightX+radius then Exit;
if ty > lightY+radius then Exit;
//e_DrawFill(FTextureIDs[FCurTexture].Tex, X, Y, tw div FTextureWidth, th div FTextureHeight, FAlpha, True, FBlending);
glBegin(GL_QUADS);
drawLine(tx, ty, tx+tw, ty); // top
drawLine(tx+tw, ty, tx+tw, ty+th); // right
drawLine(tx+tw, ty+th, tx, ty+th); // bottom
drawLine(tx, ty+th, tx, ty); // left
glEnd();
end;
end;
procedure TPanel.positionChanged (); inline;
var
px, py, pw, ph: Integer;
begin
if (proxyId >= 0) then
begin
mapGrid.getBodyDims(proxyId, px, py, pw, ph);
if (px <> x) or (py <> y) or (pw <> Width) or (ph <> Height) then
begin
{
e_LogWritefln('panel moved: arridx=%s; guid=%s; proxyid=%s; old:(%s,%s)-(%sx%s); new:(%s,%s)-(%sx%s)',
[arrIdx, mGUID, proxyId, px, py, pw, ph, x, y, width, height]);
}
g_Mark(px, py, pw, ph, MARK_WALL, false);
if (Width < 1) or (Height < 1) then
begin
mapGrid.proxyEnabled[proxyId] := false;
end
else
begin
mapGrid.proxyEnabled[proxyId] := Enabled;
if (pw <> Width) or (ph <> Height) then
begin
//writeln('panel resize!');
mapGrid.moveResizeBody(proxyId, X, Y, Width, Height)
end
else
begin
mapGrid.moveBody(proxyId, X, Y);
end;
g_Mark(X, Y, Width, Height, MARK_WALL);
end;
end;
end;
end;
var
monCheckList: array of TMonster = nil;
monCheckListUsed: Integer = 0;
procedure TPanel.Update();
var
ox, oy: Integer;
nx, ny, nw, nh: Integer;
ex, ey, nex, ney: Integer;
mpw, mph: Integer;
conveyor: Boolean;
// return `true` if we should move by dx,dy
function tryMPlatMove (px, py, pw, ph: Integer; out dx, dy: Integer; out squash: Boolean; ontop: PBoolean=nil): Boolean;
var
u0: Single;
tex, tey: Integer;
pdx, pdy: Integer;
trtag: Integer;
szdx, szdy: Integer;
begin
squash := false;
tex := px;
tey := py;
pdx := mMovingSpeed.X;
pdy := mMovingSpeed.Y;
// standing on the platform?
if (py+ph = oy) then
begin
if (ontop <> nil) then ontop^ := true;
// yes, move with it; but skip steps (no need to process size change here, 'cause platform top cannot be changed with it)
mapGrid.traceBox(tex, tey, px, py, pw, ph, pdx, pdy, (GridTagWall or GridTagDoor));
end
else
begin
if (ontop <> nil) then ontop^ := false;
// not standing on the platform: trace platform to see if it hits the entity
// first, process size change (as we cannot sweeptest both move and size change)
// but we don't have to check for pushing if the panel is shrinking
szdx := nw-mpw;
szdy := nh-mph;
if (szdx > 0) or (szdy > 0) then
begin
// ignore shrinking dimension
if (szdx < 0) then szdx := 0;
if (szdy < 0) then szdy := 0;
// move platform by szd* back, and check for szd* movement
if sweepAABB(ox-szdx, oy-szdy, nw, nh, szdx, szdy, px, py, pw, ph, u0) then
begin
// yes, platform hits the entity, push the entity in the resizing direction
u0 := 1.0-u0; // how much path left?
szdx := trunc(szdx*u0);
szdy := trunc(szdy*u0);
if (szdx <> 0) or (szdy <> 0) then
begin
// has some path to go, trace the entity
trtag := (GridTagWall or GridTagDoor);
// if we're moving down, consider steps too
if (szdy > 0) then trtag := trtag or GridTagStep;
mapGrid.traceBox(tex, tey, px, py, pw, ph, szdx, szdy, trtag);
end;
end;
end;
// second, process platform movement, using te* as entity starting point
if sweepAABB(ox, oy, nw, nh, pdx, pdy, tex, tey, pw, ph, u0) then
begin
//e_LogWritefln('T: platsweep; u0=%s; u1=%s; hedge=%s; sweepAABB(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', [u0, u1, hedge, ox, oy, mpw, mph, pdx, pdy, px-1, py-1, pw+2, ph+2]);
// yes, platform hits the entity, push the entity in the direction of the platform
u0 := 1.0-u0; // how much path left?
pdx := trunc(pdx*u0);
pdy := trunc(pdy*u0);
//e_LogWritefln(' platsweep; uleft=%s; pd=(%s,%s)', [u0, pdx, pdy]);
if (pdx <> 0) or (pdy <> 0) then
begin
// has some path to go, trace the entity
trtag := (GridTagWall or GridTagDoor);
// if we're moving down, consider steps too
if (pdy > 0) then trtag := trtag or GridTagStep;
mapGrid.traceBox(tex, tey, px, py, pw, ph, pdx, pdy, trtag);
end;
end;
end;
// done with entity movement, new coords are in te*
dx := tex-px;
dy := tey-py;
result := (dx <> 0) or (dy <> 0);
if not conveyor and ((tag and (GridTagWall or GridTagDoor)) <> 0) then
begin
// check for squashing; as entity cannot be pushed into a wall, check only collision with the platform itself
squash := g_Collide(tex, tey, pw, ph, nx, ny, nw, nh); // squash, if still in platform
end;
end;
function monCollect (mon: TMonster): Boolean;
begin
result := false; // don't stop
if (monCheckListUsed >= Length(monCheckList)) then SetLength(monCheckList, monCheckListUsed+128);
monCheckList[monCheckListUsed] := mon;
Inc(monCheckListUsed);
end;
var
cx0, cy0, cx1, cy1, cw, ch: Integer;
f: Integer;
px, py, pw, ph, pdx, pdy: Integer;
squash: Boolean;
plr: TPlayer;
gib: PGib;
cor: TCorpse;
mon: TMonster;
flg: PFlag;
itm: PItem;
mpfrid: LongWord;
ontop: Boolean;
actMoveTrig: Boolean;
actSizeTrig: Boolean;
begin
if (not Enabled) or (Width < 1) or (Height < 1) then exit;
if (FCurTexture >= 0) and
(FTextureIDs[FCurTexture].Anim) and
(FTextureIDs[FCurTexture].AnTex <> nil) and
(FAlpha < 255) then
begin
FTextureIDs[FCurTexture].AnTex.Update();
FCurFrame := FTextureIDs[FCurTexture].AnTex.CurrentFrame;
FCurFrameCount := FTextureIDs[FCurTexture].AnTex.CurrentCounter;
end;
if not g_dbgpan_mplat_active then exit;
if (mOldMovingActive <> mMovingActive) then mNeedSend := true;
mOldMovingActive := mMovingActive;
if not mMovingActive then exit;
if mMovingSpeed.isZero and mSizeSpeed.isZero then exit;
//TODO: write wall size change processing
// moving platform?
begin
(*
* collect all monsters and players (aka entities) along the possible platform path
* if entity is standing on a platform:
* try to move it along the platform path, checking wall collisions
* if entity is NOT standing on a platform, but hit with sweeped platform aabb:
* try to push entity
* if we can't push entity all the way, squash it
*)
ox := X;
oy := Y;
mpw := Width;
mph := Height;
// the mplat acts as a stationary conveyor belt when it's locked within a movement rect of zero area
conveyor := (mMovingEnd.X = mMovingStart.X) and (mMovingEnd.Y = mMovingStart.Y)
and (mMovingEnd.X = X) and (mMovingEnd.Y = Y);
nw := mpw+mSizeSpeed.w;
nh := mph+mSizeSpeed.h;
nx := ox;
ny := oy;
if not conveyor then
begin
nx += mMovingSpeed.X;
ny += mMovingSpeed.Y;
end;
// force network updates only if some sudden change happened
// set the flag here, so we can sync affected monsters
if not mSizeSpeed.isZero and (nw = mSizeEnd.w) and (nh = mSizeEnd.h) then
begin
mNeedSend := true;
end
else if ((mMovingSpeed.X < 0) and (nx <= mMovingStart.X)) or ((mMovingSpeed.X > 0) and (nx >= mMovingEnd.X)) then
begin
mNeedSend := true;
end
else if ((mMovingSpeed.Y < 0) and (ny <= mMovingStart.Y)) or ((mMovingSpeed.Y > 0) and (ny >= mMovingEnd.Y)) then
begin
mNeedSend := true;
end;
// if pannel disappeared, we don't have to do anything
if (nw > 0) and (nh > 0) then
begin
// old rect
ex := ox+mpw-1;
ey := ox+mph-1;
// new rect
nex := nx+nw-1;
ney := ny+nh-1;
// full rect
cx0 := nmin(ox, nx);
cy0 := nmin(oy, ny);
cx1 := nmax(ex, nex);
cy1 := nmax(ey, ney);
// extrude
cx0 -= 1;
cy0 -= 1;
cx1 += 1;
cy1 += 1;
cw := cx1-cx0+1;
ch := cy1-cy0+1;
// process "obstacle" panels
if ((tag and GridTagObstacle) <> 0) then
begin
// temporarily turn off this panel, so it won't interfere with collision checks
mapGrid.proxyEnabled[proxyId] := false;
// process players
for f := 0 to High(gPlayers) do
begin
plr := gPlayers[f];
if (plr = nil) or (not plr.alive) then continue;
plr.getMapBox(px, py, pw, ph);
if not g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then continue;
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash) then
begin
// set new position
plr.moveBy(pdx, pdy); // this will call `positionChanged()` for us
end;
// squash player, if necessary
if not g_Game_IsClient and squash then plr.Damage(15000, 0, 0, 0, HIT_TRAP);
end;
// process gibs
for f := 0 to High(gGibs) do
begin
gib := @gGibs[f];
if not gib.alive then continue;
gib.getMapBox(px, py, pw, ph);
if not g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then continue;
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash, @ontop) then
begin
// set new position
gib.moveBy(pdx, pdy); // this will call `positionChanged()` for us
end;
end;
// move and push corpses
for f := 0 to High(gCorpses) do
begin
cor := gCorpses[f];
if (cor = nil) then continue;
cor.getMapBox(px, py, pw, ph);
if not g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then continue;
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash, @ontop) then
begin
// set new position
cor.moveBy(pdx, pdy); // this will call `positionChanged()` for us
end;
end;
// move and push flags
if gGameSettings.GameMode = GM_CTF then
for f := FLAG_RED to FLAG_BLUE do
begin
flg := @gFlags[f];
if (flg.State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then continue;
px := flg.Obj.X+flg.Obj.Rect.X;
py := flg.Obj.Y+flg.Obj.Rect.Y;
pw := flg.Obj.Rect.Width;
ph := flg.Obj.Rect.Height;
if not g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then continue;
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash, @ontop) then
if (pdx <> 0) or (pdy <> 0) then
begin
flg.Obj.X := flg.Obj.X + pdx;
flg.Obj.Y := flg.Obj.Y + pdy;
flg.NeedSend := true;
end;
end;
// move and push items
itm := g_Items_NextAlive(-1);
while itm <> nil do
begin
if itm.Fall then
begin
itm.getMapBox(px, py, pw, ph);
if g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash, @ontop) then
itm.moveBy(pdx, pdy); // this will call `positionChanged()` for us
end;
itm := g_Items_NextAlive(itm.myId);
end;
// collect monsters
monCheckListUsed := 0;
g_Mons_ForEachAt(cx0, cy0, cw, ch, monCollect);
// process collected monsters
if (monCheckListUsed > 0) then
begin
mpfrid := g_Mons_getNewMPlatFrameId();
for f := 0 to monCheckListUsed do
begin
mon := monCheckList[f];
if (mon = nil) or (not mon.alive) or (mon.mplatCheckFrameId = mpfrid) then continue;
mon.mplatCheckFrameId := mpfrid;
mon.getMapBox(px, py, pw, ph);
//if not g_Collide(px, py, pw, ph, cx0, cy0, cw, ch) then continue;
if tryMPlatMove(px, py, pw, ph, pdx, pdy, squash) then
begin
// set new position
mon.moveBy(pdx, pdy); // this will call `positionChanged()` for us
//???FIXME: do we really need to send monsters over the net?
// i don't think so, as dead reckoning should take care of 'em
// ok, send new monster position only if platform is going to change it's direction
if mNeedSend then mon.setDirty();
end;
// squash monster, if necessary
if not g_Game_IsClient and squash then mon.Damage(15000, 0, 0, 0, HIT_TRAP);
end;
end;
// restore panel state
mapGrid.proxyEnabled[proxyId] := true;
end;
end;
// move panel
FOldX := X;
FOldY := Y;
X := nx;
Y := ny;
FOldW := FWidth;
FOldH := FHeight;
FWidth := nw;
FHeight := nh;
positionChanged();
actMoveTrig := false;
actSizeTrig := false;
// `mNeedSend` was set above
// check "size stop"
if not mSizeSpeed.isZero and (nw = mSizeEnd.w) and (nh = mSizeEnd.h) then
begin
mSizeSpeed.w := 0;
mSizeSpeed.h := 0;
actSizeTrig := true;
if (nw < 1) or (nh < 1) then mMovingActive := false; //HACK!
end;
if not conveyor then
begin
// reverse moving direction, if necessary
if ((mMovingSpeed.X < 0) and (nx <= mMovingStart.X)) or ((mMovingSpeed.X > 0) and (nx >= mMovingEnd.X)) then
begin
if mMoveOnce then mMovingActive := false else mMovingSpeed.X := -mMovingSpeed.X;
actMoveTrig := true;
end;
if ((mMovingSpeed.Y < 0) and (ny <= mMovingStart.Y)) or ((mMovingSpeed.Y > 0) and (ny >= mMovingEnd.Y)) then
begin
if mMoveOnce then mMovingActive := false else mMovingSpeed.Y := -mMovingSpeed.Y;
actMoveTrig := true;
end;
if (mOldMovingActive <> mMovingActive) then mNeedSend := true;
mOldMovingActive := mMovingActive;
end;
if not g_Game_IsClient then
begin
if actMoveTrig then g_Triggers_Press(mEndPosTrig, ACTIVATE_CUSTOM);
if actSizeTrig then g_Triggers_Press(mEndSizeTrig, ACTIVATE_CUSTOM);
end;
// some triggers may activate this, don't delay sending
//TODO: when triggers will be able to control speed and size, check that here too
if (mOldMovingActive <> mMovingActive) then mNeedSend := true;
mOldMovingActive := mMovingActive;
end;
end;
procedure TPanel.SetFrame(Frame: Integer; Count: Byte);
function ClampInt(X, A, B: Integer): Integer;
begin
Result := X;
if X < A then Result := A else if X > B then Result := B;
end;
begin
if Enabled and (FCurTexture >= 0) and
(FTextureIDs[FCurTexture].Anim) and
(FTextureIDs[FCurTexture].AnTex <> nil) and
(Width > 0) and (Height > 0) and (FAlpha < 255) then
begin
FCurFrame := ClampInt(Frame, 0, FTextureIDs[FCurTexture].AnTex.TotalFrames - 1);
FCurFrameCount := Count;
FTextureIDs[FCurTexture].AnTex.CurrentFrame := FCurFrame;
FTextureIDs[FCurTexture].AnTex.CurrentCounter := FCurFrameCount;
end;
end;
procedure TPanel.NextTexture(AnimLoop: Byte = 0);
begin
Assert(FCurTexture >= -1, 'FCurTexture < -1');
// :
if Length(FTextureIDs) = 0 then
FCurTexture := -1
else
// :
if Length(FTextureIDs) = 1 then
begin
if FCurTexture = 0 then
FCurTexture := -1
else
FCurTexture := 0;
end
else
// :
begin
// :
Inc(FCurTexture);
// - :
if FCurTexture >= Length(FTextureIDs) then
FCurTexture := 0;
end;
// . :
if (FCurTexture >= 0) and FTextureIDs[FCurTexture].Anim then
begin
if (FTextureIDs[FCurTexture].AnTex = nil) then
begin
g_FatalError(_lc[I_GAME_ERROR_SWITCH_TEXTURE]);
Exit;
end;
if AnimLoop = 1 then
FTextureIDs[FCurTexture].AnTex.Loop := True
else
if AnimLoop = 2 then
FTextureIDs[FCurTexture].AnTex.Loop := False;
FTextureIDs[FCurTexture].AnTex.Reset();
end;
LastAnimLoop := AnimLoop;
end;
procedure TPanel.SetTexture(ID: Integer; AnimLoop: Byte = 0);
begin
if (ID >= -1) and (ID < Length(FTextureIDs)) then
FCurTexture := ID;
// . :
if (FCurTexture >= 0) and FTextureIDs[FCurTexture].Anim then
begin
if (FTextureIDs[FCurTexture].AnTex = nil) then
begin
g_FatalError(_lc[I_GAME_ERROR_SWITCH_TEXTURE]);
Exit;
end;
if AnimLoop = 1 then
FTextureIDs[FCurTexture].AnTex.Loop := True
else
if AnimLoop = 2 then
FTextureIDs[FCurTexture].AnTex.Loop := False;
FTextureIDs[FCurTexture].AnTex.Reset();
end;
LastAnimLoop := AnimLoop;
end;
function TPanel.GetTextureID(): DWORD;
begin
Result := LongWord(TEXTURE_NONE);
if (FCurTexture >= 0) then
begin
if FTextureIDs[FCurTexture].Anim then
Result := FTextureIDs[FCurTexture].AnTex.FramesID
else
Result := FTextureIDs[FCurTexture].Tex;
end;
end;
function TPanel.GetTextureCount(): Integer;
begin
Result := Length(FTextureIDs);
if Enabled and (FCurTexture >= 0) then
if (FTextureIDs[FCurTexture].Anim) and
(FTextureIDs[FCurTexture].AnTex <> nil) and
(Width > 0) and (Height > 0) and (FAlpha < 255) then
Result := Result + 100;
end;
function TPanel.CanChangeTexture(): Boolean;
begin
Result := (GetTextureCount() > 1) or hasTexTrigger;
end;
const
PAN_SAVE_VERSION = 1;
procedure TPanel.SaveState (st: TStream);
var
anim: Boolean;
begin
if st = nil then Exit;
//
utils.writeSign(st, 'PANL');
st.WriteByte(PAN_SAVE_VERSION);
st.WriteBool(FEnabled); // /,
st.WriteByte(FLiftType); // ,
st.WriteInt32LE(FCurTexture); //
//
st.WriteInt32LE(FX);
st.WriteInt32LE(FY);
st.WriteWordLE(FWidth);
st.WriteWordLE(FHeight);
//
// BEWARE: Short-circuit evaluation matters here!
anim := (FCurTexture >= 0) and (FTextureIDs[FCurTexture].Anim);
if anim then
Assert(FTextureIDs[FCurTexture].AnTex <> nil, 'TPanel.SaveState: Wrong animation state');
st.WriteBool(anim);
// -
if anim then FTextureIDs[FCurTexture].AnTex.SaveState(st);
// moving platform state
st.WriteInt32LE(mMovingSpeed.X);
st.WriteInt32LE(mMovingSpeed.Y);
st.WriteInt32LE(mMovingStart.X);
st.WriteInt32LE(mMovingStart.Y);
st.WriteInt32LE(mMovingEnd.X);
st.WriteInt32LE(mMovingEnd.Y);
st.WriteInt32LE(mSizeSpeed.w);
st.WriteInt32LE(mSizeSpeed.h);
st.WriteInt32LE(mSizeEnd.w);
st.WriteInt32LE(mSizeEnd.h);
st.WriteBool(mMovingActive);
st.WriteBool(mMoveOnce);
st.WriteInt32LE(mEndPosTrig);
st.WriteInt32LE(mEndSizeTrig);
end;
procedure TPanel.LoadState (st: TStream);
begin
if st = nil then Exit;
//
if not utils.checkSign(st, 'PANL') then
Raise XStreamError.create('wrong panel signature');
if st.ReadByte() <> PAN_SAVE_VERSION then
Raise XStreamError.create('wrong panel version');
FEnabled := st.ReadBool(); // /,
FLiftType := st.ReadByte(); // ,
FCurTexture := st.ReadInt32LE(); //
//
FX := st.ReadInt32LE();
FY := st.ReadInt32LE();
FOldX := FX;
FOldY := FY;
FWidth := st.ReadWordLE();
FHeight := st.ReadWordLE();
FOldW := FWidth;
FOldH := FHeight;
//
if st.ReadBool() then
begin
// -
// BEWARE: Short-circuit evaluation matters here!
Assert((FCurTexture >= 0) and (FTextureIDs[FCurTexture].Anim) and
(FTextureIDs[FCurTexture].AnTex <> nil), 'TPanel.LoadState: No animation object');
FTextureIDs[FCurTexture].AnTex.LoadState(st);
end;
// moving platform state
mMovingSpeed.X := st.ReadInt32LE();
mMovingSpeed.Y := st.ReadInt32LE();
mMovingStart.X := st.ReadInt32LE();
mMovingStart.Y := st.ReadInt32LE();
mMovingEnd.X := st.ReadInt32LE();
mMovingEnd.Y := st.ReadInt32LE();
mSizeSpeed.w := st.ReadInt32LE();
mSizeSpeed.h := st.ReadInt32LE();
mSizeEnd.w := st.ReadInt32LE();
mSizeEnd.h := st.ReadInt32LE();
mMovingActive := st.ReadBool();
mMoveOnce := st.ReadBool();
mEndPosTrig := st.ReadInt32LE();
mEndSizeTrig := st.ReadInt32LE();
positionChanged();
//mapGrid.proxyEnabled[proxyId] := FEnabled; // done in g_map.pas
end;
end.
| 0 | 0.962228 | 1 | 0.962228 | game-dev | MEDIA | 0.744413 | game-dev | 0.920919 | 1 | 0.920919 |
aurilisdev/Electrodynamics | 2,175 | src/main/java/electrodynamics/common/item/ItemCeramic.java | package electrodynamics.common.item;
import java.util.ArrayList;
import java.util.List;
import electrodynamics.common.item.subtype.SubtypeCeramic;
import electrodynamics.registers.ElectrodynamicsCreativeTabs;
import electrodynamics.registers.ElectrodynamicsItems;
import electrodynamics.registers.ElectrodynamicsSounds;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import voltaic.common.item.ItemVoltaic;
import voltaic.prefab.utilities.ItemUtils;
import voltaic.registers.VoltaicDataComponentTypes;
public class ItemCeramic extends ItemVoltaic {
public SubtypeCeramic subtype;
public ItemCeramic(SubtypeCeramic subtype) {
super(new Item.Properties().stacksTo(64), ElectrodynamicsCreativeTabs.MAIN);
this.subtype = subtype;
}
@Override
public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
ItemStack handStack = player.getItemInHand(hand);
if (world.isClientSide || !ItemUtils.testItems(handStack.getItem(), ElectrodynamicsItems.ITEMS_CERAMIC.getValue(SubtypeCeramic.plate))) {
return InteractionResultHolder.pass(player.getItemInHand(hand));
}
List<ItemStack> armorPieces = new ArrayList<>();
player.getArmorSlots().forEach(armorPieces::add);
ItemStack chestplate = armorPieces.get(2);
if (chestplate.getItem() == ElectrodynamicsItems.ITEM_COMPOSITECHESTPLATE.get() || chestplate.getItem() == ElectrodynamicsItems.ITEM_COMBATCHESTPLATE.get()) {
int stored = chestplate.getOrDefault(VoltaicDataComponentTypes.PLATES, 0);
if (stored < 2) {
world.playSound(null, player.getOnPos(), ElectrodynamicsSounds.SOUND_CERAMICPLATEADDED.get(), SoundSource.PLAYERS, 1.0F, 1.0F);
chestplate.set(VoltaicDataComponentTypes.PLATES, stored + 1);
if (!player.isCreative()) {
handStack.shrink(1);
player.setItemInHand(hand, handStack);
}
}
}
return InteractionResultHolder.pass(player.getItemInHand(hand));
}
}
| 0 | 0.851797 | 1 | 0.851797 | game-dev | MEDIA | 0.969188 | game-dev | 0.878742 | 1 | 0.878742 |
Ellpeck/ActuallyAdditions | 2,388 | src/main/java/de/ellpeck/actuallyadditions/mod/jei/crusher/CrusherCategory.java | package de.ellpeck.actuallyadditions.mod.jei.crusher;
import de.ellpeck.actuallyadditions.mod.crafting.CrushingRecipe;
import de.ellpeck.actuallyadditions.mod.jei.JEIActuallyAdditionsPlugin;
import de.ellpeck.actuallyadditions.mod.util.AssetUtil;
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder;
import mezz.jei.api.gui.drawable.IDrawable;
import mezz.jei.api.gui.drawable.IDrawableStatic;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.api.recipe.IFocusGroup;
import mezz.jei.api.recipe.RecipeIngredientRole;
import mezz.jei.api.recipe.RecipeType;
import mezz.jei.api.recipe.category.IRecipeCategory;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
public class CrusherCategory implements IRecipeCategory<CrushingRecipe> {
private final IDrawableStatic background;
public CrusherCategory(IGuiHelper helper) {
this.background = helper.drawableBuilder(AssetUtil.getGuiLocation("gui_grinder"), 60, 13, 56, 79).build();
}
@Override
public RecipeType<CrushingRecipe> getRecipeType() {
return JEIActuallyAdditionsPlugin.CRUSHING;
}
@Override
public Component getTitle() {
return Component.translatable("container.actuallyadditions.crusher");
}
@Override
public int getWidth() {
return 56;
}
@Override
public int getHeight() {
return 79;
}
@Override
public IDrawable getIcon() {
return null;
}
@Override
public void setRecipe(IRecipeLayoutBuilder builder, CrushingRecipe recipe, IFocusGroup focuses) {
builder.addSlot(RecipeIngredientRole.INPUT, 20, 8).addIngredients(recipe.getInput());
builder.addSlot(RecipeIngredientRole.OUTPUT, 8, 56).addItemStack(recipe.getOutputOne());
if (!recipe.getOutputTwo().isEmpty()) {
builder.addSlot(RecipeIngredientRole.OUTPUT, 32, 56).addItemStack(recipe.getOutputTwo());
}
}
@Override
public void draw(CrushingRecipe recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics guiGraphics, double mouseX, double mouseY) {
this.background.draw(guiGraphics);
IRecipeCategory.super.draw(recipe, recipeSlotsView, guiGraphics, mouseX, mouseY);
Minecraft mc = Minecraft.getInstance();
if (!recipe.getOutputTwo().isEmpty()) {
guiGraphics.drawString(mc.font, (int)(recipe.getSecondChance() * 100) + "%", 60, 60, 4210752, false);
}
}
}
| 0 | 0.86833 | 1 | 0.86833 | game-dev | MEDIA | 0.961939 | game-dev | 0.936659 | 1 | 0.936659 |
DougGregor/swift-concurrency-objc | 2,783 | tvOS/CoreText/CTFontManager.swift |
@available(tvOS 10.0, *)
func CTFontManagerCopyAvailablePostScriptNames() -> CFArray
@available(tvOS 10.0, *)
func CTFontManagerCopyAvailableFontFamilyNames() -> CFArray
@available(tvOS 9.0, *)
func CTFontManagerCreateFontDescriptorsFromURL(_ fileURL: CFURL) -> CFArray?
@available(tvOS 9.0, *)
func CTFontManagerCreateFontDescriptorFromData(_ data: CFData) -> CTFontDescriptor?
@available(tvOS 11.0, *)
func CTFontManagerCreateFontDescriptorsFromData(_ data: CFData) -> CFArray
enum CTFontManagerScope : UInt32 {
init?(rawValue: UInt32)
var rawValue: UInt32 { get }
case none
case process
@available(tvOS 13.0, *)
case persistent
static var user: CTFontManagerScope { get }
}
@available(tvOS 9.0, *)
func CTFontManagerRegisterFontsForURL(_ fontURL: CFURL, _ scope: CTFontManagerScope, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool
@available(tvOS 9.0, *)
func CTFontManagerUnregisterFontsForURL(_ fontURL: CFURL, _ scope: CTFontManagerScope, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool
@available(tvOS 9.0, *)
func CTFontManagerRegisterGraphicsFont(_ font: CGFont, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool
@available(tvOS 9.0, *)
func CTFontManagerUnregisterGraphicsFont(_ font: CGFont, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> Bool
@available(tvOS, introduced: 9.0, deprecated: 13.0, renamed: "CTFontManagerRegisterFontURLs(_:_:_:_:)")
func CTFontManagerRegisterFontsForURLs(_ fontURLs: CFArray, _ scope: CTFontManagerScope, _ errors: UnsafeMutablePointer<Unmanaged<CFArray>?>?) -> Bool
@available(tvOS, introduced: 9.0, deprecated: 13.0, renamed: "CTFontManagerUnregisterFontURLs(_:_:_:)")
func CTFontManagerUnregisterFontsForURLs(_ fontURLs: CFArray, _ scope: CTFontManagerScope, _ errors: UnsafeMutablePointer<Unmanaged<CFArray>?>?) -> Bool
@available(tvOS 13.0, *)
func CTFontManagerRegisterFontURLs(_ fontURLs: CFArray, _ scope: CTFontManagerScope, _ enabled: Bool, _ registrationHandler: ((CFArray, Bool) -> Bool)?)
@available(tvOS 13.0, *)
func CTFontManagerUnregisterFontURLs(_ fontURLs: CFArray, _ scope: CTFontManagerScope, _ registrationHandler: ((CFArray, Bool) -> Bool)?)
@available(tvOS 13.0, *)
func CTFontManagerRegisterFontDescriptors(_ fontDescriptors: CFArray, _ scope: CTFontManagerScope, _ enabled: Bool, _ registrationHandler: ((CFArray, Bool) -> Bool)?)
@available(tvOS 13.0, *)
func CTFontManagerUnregisterFontDescriptors(_ fontDescriptors: CFArray, _ scope: CTFontManagerScope, _ registrationHandler: ((CFArray, Bool) -> Bool)?)
enum CTFontManagerAutoActivationSetting : UInt32 {
init?(rawValue: UInt32)
var rawValue: UInt32 { get }
case `default`
case disabled
case enabled
}
@available(tvOS 9.0, *)
let kCTFontManagerRegisteredFontsChangedNotification: CFString
| 0 | 0.509011 | 1 | 0.509011 | game-dev | MEDIA | 0.298197 | game-dev | 0.709366 | 1 | 0.709366 |
sillsdev/FieldWorks | 10,522 | Src/Common/Controls/XMLViews/NeededPropertyInfo.cs | // Copyright (c) 2003-2013 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
// --------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.FieldWorks.Common.ViewsInterfaces;
namespace SIL.FieldWorks.Common.Controls
{
/// <summary>
/// This class stores (a) a list of flids of atomic non-object properties that we need
/// to know about;
/// (b) a list of object properties, for each of which, we need to know the
/// contents of the property, and then we need to recursively load info about
/// the objects in that property. This includes both atomic object properties, where a single
/// query can be used for both the main and related objects, and sequence properties where
/// a distinct query is used for each sequence.
/// We reuse this class for info about the child objects, so it also stores
/// a flid for obtaining child objects. This is also set for the root
/// NeededPropertyInfo, since sometimes knowing what to add depends on
/// the signature of the sequence property.
/// </summary>
public class NeededPropertyInfo
{
/// <summary>
/// the class of objects at this property info level (destination of m_flidSource).
/// </summary>
protected int m_targetClass = 0;
// the property from which the objects whose properties we want come.
private int m_flidSource;
private List<PropWs> m_atomicFlids = new List<PropWs>(); // atomic properties of target objects
private List<NeededPropertyInfo> m_sequenceInfo = new List<NeededPropertyInfo>();
private NeededPropertyInfo m_parent; // if it is in a list of child properties, note of which object.
private bool m_fSeq; // whether m_flidSource is a sequence property.
/// ------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="T:NeededPropertyInfo"/> class.
/// </summary>
/// <param name="listItemsClass">the class of objects at the root parent of the NeedPropertyInfo tree.
/// Typically the destination class of flidSource</param>
/// ------------------------------------------------------------------------------------
public NeededPropertyInfo(int listItemsClass)
{
m_targetClass = listItemsClass;
m_flidSource = 0; // don't really how we got to the root parent class.
m_parent = null;
m_fSeq = true;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="T:NeededPropertyInfo"/> class.
/// </summary>
/// <param name="flidSource">The flid source.</param>
/// <param name="parent">The parent.</param>
/// <param name="fSeq">if set to <c>true</c> [f seq].</param>
/// ------------------------------------------------------------------------------------
protected NeededPropertyInfo(int flidSource, NeededPropertyInfo parent, bool fSeq)
{
m_flidSource = flidSource;
m_parent = parent;
m_fSeq = fSeq;
}
/// <summary>
/// The source property containing the objects about which we want info.
/// </summary>
public int Source
{
get { return m_flidSource; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether this instance has atomic fields.
/// </summary>
/// <value>
/// <c>true</c> if this instance has atomic fields; otherwise, <c>false</c>.
/// </value>
/// ------------------------------------------------------------------------------------
public bool HasAtomicFields
{
get
{
if (m_atomicFlids.Count > 0)
return true;
foreach (NeededPropertyInfo info in m_sequenceInfo)
if (!info.m_fSeq)
return true;
return false;
}
}
/// <summary>
/// Answer the class of objects for which we are collecting fields.
/// By default this is the destination class of the field that contains them.
/// We override this in a subclass for certain virtual and phony properties.
/// </summary>
/// <param name="vc"></param>
/// <returns></returns>
internal int TargetClass(XmlVc vc)
{
return TargetClass(vc.DataAccess);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Answer the class of objects for which we are collecting fields.
/// By default this is the destination class of the field that contains them.
/// If needed, override this in a subclass for certain virtual and phony properties.
/// </summary>
/// ------------------------------------------------------------------------------------
public virtual int TargetClass(ISilDataAccess sda)
{
if (m_targetClass == 0 && Source != 0)
m_targetClass = sda.MetaDataCache.GetDstClsId(this.Source);
return m_targetClass;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether this instance is sequence.
/// </summary>
/// <value>
/// <c>true</c> if this instance is sequence; otherwise, <c>false</c>.
/// </value>
/// ------------------------------------------------------------------------------------
public bool IsSequence
{
get { return m_fSeq; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the parent.
/// </summary>
/// <value>The parent.</value>
/// ------------------------------------------------------------------------------------
public NeededPropertyInfo Parent
{
get { return m_parent; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the seq depth.
/// </summary>
/// <value>The seq depth.</value>
/// ------------------------------------------------------------------------------------
public int SeqDepth
{
get
{
int depth = 0;
NeededPropertyInfo info = this;
while (info != null)
{
if (info.m_fSeq)
depth++;
info = info.Parent;
}
return depth;
}
}
/// <summary>
/// The number of layers of parent (not counting this)
/// </summary>
public int Depth
{
get
{
int depth = 0;
NeededPropertyInfo info = m_parent;
while (info != null)
{
depth++;
info = info.Parent;
}
return depth;
}
}
/// <summary>
/// Atomic properties of objects that can occur in the source field.
/// </summary>
public List<PropWs> AtomicFields
{
get { return m_atomicFlids; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Add an atomic flid.
/// </summary>
/// <param name="flid">The flid.</param>
/// <param name="ws">The ws.</param>
/// ------------------------------------------------------------------------------------
public void AddAtomicField(int flid, int ws)
{
PropWs pw = new PropWs(flid, ws);
if (m_atomicFlids.Contains(pw))
return;
m_atomicFlids.Add(pw);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sequence properties of objects that can occur in the source field.
/// </summary>
/// <value>The seq fields.</value>
/// ------------------------------------------------------------------------------------
public List<NeededPropertyInfo> SeqFields
{
get { return m_sequenceInfo; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Add (or retrieve) info about a object (atomic or seq) flid. May include virtuals.
/// </summary>
/// <param name="flid">The flid.</param>
/// <param name="fSeq">if set to <c>true</c> [f seq].</param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public NeededPropertyInfo AddObjField(int flid, bool fSeq)
{
NeededPropertyInfo info =
m_sequenceInfo.Find(delegate(NeededPropertyInfo item)
{ return item.Source == flid; });
if (info == null)
{
info = new NeededPropertyInfo(flid, this, fSeq);
m_sequenceInfo.Add(info);
}
return info;
}
/// <summary>
/// Add (or retrieve) info about a virtual object flid.
/// </summary>
/// <param name="flid"></param>
/// <param name="fSeq"></param>
/// <param name="dstClass"></param>
/// <returns></returns>
public NeededPropertyInfo AddVirtualObjField(int flid, bool fSeq, int dstClass)
{
VirtualNeededPropertyInfo info =
m_sequenceInfo.Find(delegate(NeededPropertyInfo item)
{ return item.Source == flid; }) as VirtualNeededPropertyInfo;
if (info == null)
{
info = new VirtualNeededPropertyInfo(flid, this, fSeq, dstClass);
m_sequenceInfo.Add(info);
}
return info;
}
internal void DumpFieldInfo(IFwMetaDataCache mdc)
{
if (this.Depth == 0)
Debug.WriteLine("");
for (int i = 0; i < this.Depth; ++i)
Debug.Write(" ");
if (Source != 0)
{
Debug.WriteLine("[" + this.Depth + "]info.Source = " + this.Source + " = " +
GetFancyFieldName(this.Source, mdc));
}
else
{
Debug.WriteLine("Root (target) class: " + mdc.GetClassName(m_targetClass));
}
for (int i = 0; i < this.AtomicFields.Count; ++i)
{
for (int j = 0; j < this.Depth; ++j)
Debug.Write(" ");
Debug.WriteLine(" Atomic[" + i + "] flid = " + this.AtomicFields[i].flid + "(" +
GetFancyFieldName(this.AtomicFields[i].flid, mdc) + "); ws = " + this.AtomicFields[i].ws);
}
for (int i = 0; i < this.SeqFields.Count; ++i)
this.SeqFields[i].DumpFieldInfo(mdc);
}
private string GetFancyFieldName(int flid, IFwMetaDataCache mdc)
{
string f = mdc.GetFieldName(flid);
string c = mdc.GetOwnClsName(flid);
return c + '_' + f;
}
}
internal class VirtualNeededPropertyInfo : NeededPropertyInfo
{
public VirtualNeededPropertyInfo(int flidSource, NeededPropertyInfo parent, bool fSeq, int dstClsId)
: base(flidSource, parent, fSeq)
{
m_targetClass = dstClsId;
}
/// <summary>
/// Override: this class knows the appropriate destination class.
/// </summary>
public override int TargetClass(ISilDataAccess sda)
{
return m_targetClass;
}
}
}
| 0 | 0.802506 | 1 | 0.802506 | game-dev | MEDIA | 0.363146 | game-dev | 0.973802 | 1 | 0.973802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.