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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
andrianfaa/Bedah-APK-Undangan | 22,532 | decompiled classes.dex/sources/androidx/recyclerview/widget/DiffUtil.java | package androidx.recyclerview.widget;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import mt.Log1F380D;
public class DiffUtil {
private static final Comparator<Snake> SNAKE_COMPARATOR = new Comparator<Snake>() {
public int compare(Snake o1, Snake o2) {
int i = o1.x - o2.x;
return i == 0 ? o1.y - o2.y : i;
}
};
public static abstract class Callback {
public abstract boolean areContentsTheSame(int i, int i2);
public abstract boolean areItemsTheSame(int i, int i2);
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
return null;
}
public abstract int getNewListSize();
public abstract int getOldListSize();
}
/* compiled from: 008C */
public static class DiffResult {
private static final int FLAG_CHANGED = 2;
private static final int FLAG_IGNORE = 16;
private static final int FLAG_MASK = 31;
private static final int FLAG_MOVED_CHANGED = 4;
private static final int FLAG_MOVED_NOT_CHANGED = 8;
private static final int FLAG_NOT_CHANGED = 1;
private static final int FLAG_OFFSET = 5;
public static final int NO_POSITION = -1;
private final Callback mCallback;
private final boolean mDetectMoves;
private final int[] mNewItemStatuses;
private final int mNewListSize;
private final int[] mOldItemStatuses;
private final int mOldListSize;
private final List<Snake> mSnakes;
DiffResult(Callback callback, List<Snake> list, int[] oldItemStatuses, int[] newItemStatuses, boolean detectMoves) {
this.mSnakes = list;
this.mOldItemStatuses = oldItemStatuses;
this.mNewItemStatuses = newItemStatuses;
Arrays.fill(oldItemStatuses, 0);
Arrays.fill(newItemStatuses, 0);
this.mCallback = callback;
this.mOldListSize = callback.getOldListSize();
this.mNewListSize = callback.getNewListSize();
this.mDetectMoves = detectMoves;
addRootSnake();
findMatchingItems();
}
private void addRootSnake() {
Snake snake = this.mSnakes.isEmpty() ? null : this.mSnakes.get(0);
if (snake == null || snake.x != 0 || snake.y != 0) {
Snake snake2 = new Snake();
snake2.x = 0;
snake2.y = 0;
snake2.removal = false;
snake2.size = 0;
snake2.reverse = false;
this.mSnakes.add(0, snake2);
}
}
private void dispatchAdditions(List<PostponedUpdate> list, ListUpdateCallback updateCallback, int start, int count, int globalIndex) {
if (!this.mDetectMoves) {
updateCallback.onInserted(start, count);
return;
}
for (int i = count - 1; i >= 0; i--) {
int[] iArr = this.mNewItemStatuses;
int i2 = iArr[globalIndex + i] & 31;
switch (i2) {
case 0:
updateCallback.onInserted(start, 1);
for (PostponedUpdate postponedUpdate : list) {
postponedUpdate.currentPos++;
}
break;
case 4:
case 8:
int i3 = iArr[globalIndex + i] >> 5;
updateCallback.onMoved(removePostponedUpdate(list, i3, true).currentPos, start);
if (i2 != 4) {
break;
} else {
updateCallback.onChanged(start, 1, this.mCallback.getChangePayload(i3, globalIndex + i));
break;
}
case 16:
list.add(new PostponedUpdate(globalIndex + i, start, false));
break;
default:
StringBuilder append = new StringBuilder().append("unknown flag for pos ").append(globalIndex + i).append(" ");
String binaryString = Long.toBinaryString((long) i2);
Log1F380D.a((Object) binaryString);
throw new IllegalStateException(append.append(binaryString).toString());
}
}
}
private void findAddition(int x, int y, int snakeIndex) {
if (this.mOldItemStatuses[x - 1] == 0) {
findMatchingItem(x, y, snakeIndex, false);
}
}
private boolean findMatchingItem(int x, int y, int snakeIndex, boolean removal) {
int i;
int i2;
int i3;
if (removal) {
i3 = y - 1;
i2 = x;
i = y - 1;
} else {
i3 = x - 1;
i2 = x - 1;
i = y;
}
for (int i4 = snakeIndex; i4 >= 0; i4--) {
Snake snake = this.mSnakes.get(i4);
int i5 = snake.x + snake.size;
int i6 = snake.y + snake.size;
int i7 = 8;
if (removal) {
for (int i8 = i2 - 1; i8 >= i5; i8--) {
if (this.mCallback.areItemsTheSame(i8, i3)) {
if (!this.mCallback.areContentsTheSame(i8, i3)) {
i7 = 4;
}
this.mNewItemStatuses[i3] = (i8 << 5) | 16;
this.mOldItemStatuses[i8] = (i3 << 5) | i7;
return true;
}
}
continue;
} else {
for (int i9 = i - 1; i9 >= i6; i9--) {
if (this.mCallback.areItemsTheSame(i3, i9)) {
if (!this.mCallback.areContentsTheSame(i3, i9)) {
i7 = 4;
}
this.mOldItemStatuses[x - 1] = (i9 << 5) | 16;
this.mNewItemStatuses[i9] = ((x - 1) << 5) | i7;
return true;
}
}
continue;
}
i2 = snake.x;
i = snake.y;
}
return false;
}
private void findMatchingItems() {
int i = this.mOldListSize;
int i2 = this.mNewListSize;
for (int size = this.mSnakes.size() - 1; size >= 0; size--) {
Snake snake = this.mSnakes.get(size);
int i3 = snake.x + snake.size;
int i4 = snake.y + snake.size;
if (this.mDetectMoves) {
while (i > i3) {
findAddition(i, i2, size);
i--;
}
while (i2 > i4) {
findRemoval(i, i2, size);
i2--;
}
}
for (int i5 = 0; i5 < snake.size; i5++) {
int i6 = snake.x + i5;
int i7 = snake.y + i5;
int i8 = this.mCallback.areContentsTheSame(i6, i7) ? 1 : 2;
this.mOldItemStatuses[i6] = (i7 << 5) | i8;
this.mNewItemStatuses[i7] = (i6 << 5) | i8;
}
i = snake.x;
i2 = snake.y;
}
}
private void findRemoval(int x, int y, int snakeIndex) {
if (this.mNewItemStatuses[y - 1] == 0) {
findMatchingItem(x, y, snakeIndex, true);
}
}
private static PostponedUpdate removePostponedUpdate(List<PostponedUpdate> list, int pos, boolean removal) {
for (int size = list.size() - 1; size >= 0; size--) {
PostponedUpdate postponedUpdate = list.get(size);
if (postponedUpdate.posInOwnerList == pos && postponedUpdate.removal == removal) {
list.remove(size);
for (int i = size; i < list.size(); i++) {
list.get(i).currentPos += removal ? 1 : -1;
}
return postponedUpdate;
}
}
return null;
}
public int convertNewPositionToOld(int newListPosition) {
if (newListPosition < 0 || newListPosition >= this.mNewListSize) {
throw new IndexOutOfBoundsException("Index out of bounds - passed position = " + newListPosition + ", new list size = " + this.mNewListSize);
}
int i = this.mNewItemStatuses[newListPosition];
if ((i & 31) == 0) {
return -1;
}
return i >> 5;
}
public int convertOldPositionToNew(int oldListPosition) {
if (oldListPosition < 0 || oldListPosition >= this.mOldListSize) {
throw new IndexOutOfBoundsException("Index out of bounds - passed position = " + oldListPosition + ", old list size = " + this.mOldListSize);
}
int i = this.mOldItemStatuses[oldListPosition];
if ((i & 31) == 0) {
return -1;
}
return i >> 5;
}
public void dispatchUpdatesTo(ListUpdateCallback updateCallback) {
BatchingListUpdateCallback batchingListUpdateCallback;
int i;
int i2;
ListUpdateCallback listUpdateCallback = updateCallback;
if (listUpdateCallback instanceof BatchingListUpdateCallback) {
ListUpdateCallback listUpdateCallback2 = listUpdateCallback;
batchingListUpdateCallback = (BatchingListUpdateCallback) listUpdateCallback;
} else {
BatchingListUpdateCallback batchingListUpdateCallback2 = new BatchingListUpdateCallback(listUpdateCallback);
BatchingListUpdateCallback batchingListUpdateCallback3 = batchingListUpdateCallback2;
batchingListUpdateCallback = batchingListUpdateCallback2;
}
ArrayList arrayList = new ArrayList();
int i3 = this.mOldListSize;
int i4 = this.mNewListSize;
for (int size = this.mSnakes.size() - 1; size >= 0; size--) {
Snake snake = this.mSnakes.get(size);
int i5 = snake.size;
int i6 = snake.x + i5;
int i7 = snake.y + i5;
if (i6 < i3) {
i = i7;
dispatchRemovals(arrayList, batchingListUpdateCallback, i6, i3 - i6, i6);
} else {
i = i7;
}
if (i < i4) {
int i8 = i6;
i2 = i5;
dispatchAdditions(arrayList, batchingListUpdateCallback, i6, i4 - i, i);
} else {
int i9 = i6;
i2 = i5;
}
for (int i10 = i2 - 1; i10 >= 0; i10--) {
if ((this.mOldItemStatuses[snake.x + i10] & 31) == 2) {
batchingListUpdateCallback.onChanged(snake.x + i10, 1, this.mCallback.getChangePayload(snake.x + i10, snake.y + i10));
}
}
i3 = snake.x;
i4 = snake.y;
}
batchingListUpdateCallback.dispatchLastEvent();
}
public void dispatchUpdatesTo(RecyclerView.Adapter adapter) {
dispatchUpdatesTo((ListUpdateCallback) new AdapterListUpdateCallback(adapter));
}
/* access modifiers changed from: package-private */
public List<Snake> getSnakes() {
return this.mSnakes;
}
private void dispatchRemovals(List<PostponedUpdate> list, ListUpdateCallback updateCallback, int start, int count, int globalIndex) {
if (!this.mDetectMoves) {
updateCallback.onRemoved(start, count);
return;
}
for (int i = count - 1; i >= 0; i--) {
int[] iArr = this.mOldItemStatuses;
int i2 = iArr[globalIndex + i] & 31;
switch (i2) {
case 0:
updateCallback.onRemoved(start + i, 1);
for (PostponedUpdate postponedUpdate : list) {
postponedUpdate.currentPos--;
}
break;
case 4:
case 8:
int i3 = iArr[globalIndex + i] >> 5;
PostponedUpdate removePostponedUpdate = removePostponedUpdate(list, i3, false);
updateCallback.onMoved(start + i, removePostponedUpdate.currentPos - 1);
if (i2 != 4) {
break;
} else {
updateCallback.onChanged(removePostponedUpdate.currentPos - 1, 1, this.mCallback.getChangePayload(globalIndex + i, i3));
break;
}
case 16:
list.add(new PostponedUpdate(globalIndex + i, start + i, true));
break;
default:
StringBuilder append = new StringBuilder().append("unknown flag for pos ").append(globalIndex + i).append(" ");
String binaryString = Long.toBinaryString((long) i2);
Log1F380D.a((Object) binaryString);
throw new IllegalStateException(append.append(binaryString).toString());
}
}
}
}
public static abstract class ItemCallback<T> {
public abstract boolean areContentsTheSame(T t, T t2);
public abstract boolean areItemsTheSame(T t, T t2);
public Object getChangePayload(T t, T t2) {
return null;
}
}
private static class PostponedUpdate {
int currentPos;
int posInOwnerList;
boolean removal;
public PostponedUpdate(int posInOwnerList2, int currentPos2, boolean removal2) {
this.posInOwnerList = posInOwnerList2;
this.currentPos = currentPos2;
this.removal = removal2;
}
}
static class Range {
int newListEnd;
int newListStart;
int oldListEnd;
int oldListStart;
public Range() {
}
public Range(int oldListStart2, int oldListEnd2, int newListStart2, int newListEnd2) {
this.oldListStart = oldListStart2;
this.oldListEnd = oldListEnd2;
this.newListStart = newListStart2;
this.newListEnd = newListEnd2;
}
}
static class Snake {
boolean removal;
boolean reverse;
int size;
int x;
int y;
Snake() {
}
}
private DiffUtil() {
}
public static DiffResult calculateDiff(Callback cb) {
return calculateDiff(cb, true);
}
public static DiffResult calculateDiff(Callback cb, boolean detectMoves) {
int oldListSize = cb.getOldListSize();
int newListSize = cb.getNewListSize();
ArrayList arrayList = new ArrayList();
ArrayList arrayList2 = new ArrayList();
arrayList2.add(new Range(0, oldListSize, 0, newListSize));
int abs = oldListSize + newListSize + Math.abs(oldListSize - newListSize);
int[] iArr = new int[(abs * 2)];
int[] iArr2 = new int[(abs * 2)];
ArrayList arrayList3 = new ArrayList();
while (!arrayList2.isEmpty()) {
Range range = (Range) arrayList2.remove(arrayList2.size() - 1);
Snake diffPartial = diffPartial(cb, range.oldListStart, range.oldListEnd, range.newListStart, range.newListEnd, iArr, iArr2, abs);
if (diffPartial != null) {
if (diffPartial.size > 0) {
arrayList.add(diffPartial);
}
diffPartial.x += range.oldListStart;
diffPartial.y += range.newListStart;
Range range2 = arrayList3.isEmpty() ? new Range() : (Range) arrayList3.remove(arrayList3.size() - 1);
range2.oldListStart = range.oldListStart;
range2.newListStart = range.newListStart;
if (diffPartial.reverse) {
range2.oldListEnd = diffPartial.x;
range2.newListEnd = diffPartial.y;
} else if (diffPartial.removal) {
range2.oldListEnd = diffPartial.x - 1;
range2.newListEnd = diffPartial.y;
} else {
range2.oldListEnd = diffPartial.x;
range2.newListEnd = diffPartial.y - 1;
}
arrayList2.add(range2);
Range range3 = range;
if (!diffPartial.reverse) {
range3.oldListStart = diffPartial.x + diffPartial.size;
range3.newListStart = diffPartial.y + diffPartial.size;
} else if (diffPartial.removal) {
range3.oldListStart = diffPartial.x + diffPartial.size + 1;
range3.newListStart = diffPartial.y + diffPartial.size;
} else {
range3.oldListStart = diffPartial.x + diffPartial.size;
range3.newListStart = diffPartial.y + diffPartial.size + 1;
}
arrayList2.add(range3);
} else {
arrayList3.add(range);
}
}
Collections.sort(arrayList, SNAKE_COMPARATOR);
ArrayList arrayList4 = arrayList3;
int[] iArr3 = iArr2;
int[] iArr4 = iArr;
return new DiffResult(cb, arrayList, iArr, iArr2, detectMoves);
}
private static Snake diffPartial(Callback cb, int startOld, int endOld, int startNew, int endNew, int[] forward, int[] backward, int kOffset) {
boolean z;
int i;
int i2;
boolean z2;
int i3;
Callback callback = cb;
int[] iArr = forward;
int[] iArr2 = backward;
int i4 = endOld - startOld;
int i5 = endNew - startNew;
if (endOld - startOld < 1) {
int i6 = i4;
return null;
} else if (endNew - startNew < 1) {
int i7 = i4;
return null;
} else {
int i8 = i4 - i5;
int i9 = ((i4 + i5) + 1) / 2;
Arrays.fill(iArr, (kOffset - i9) - 1, kOffset + i9 + 1, 0);
Arrays.fill(iArr2, ((kOffset - i9) - 1) + i8, kOffset + i9 + 1 + i8, i4);
boolean z3 = i8 % 2 != 0;
for (int i10 = 0; i10 <= i9; i10++) {
int i11 = -i10;
while (i11 <= i10) {
if (i11 == (-i10) || (i11 != i10 && iArr[(kOffset + i11) - 1] < iArr[kOffset + i11 + 1])) {
i3 = iArr[kOffset + i11 + 1];
z2 = false;
} else {
i3 = iArr[(kOffset + i11) - 1] + 1;
z2 = true;
}
int i12 = i3 - i11;
while (i3 < i4 && i12 < i5 && callback.areItemsTheSame(startOld + i3, startNew + i12)) {
i3++;
i12++;
}
iArr[kOffset + i11] = i3;
if (!z3 || i11 < (i8 - i10) + 1 || i11 > (i8 + i10) - 1 || iArr[kOffset + i11] < iArr2[kOffset + i11]) {
i11 += 2;
} else {
Snake snake = new Snake();
snake.x = iArr2[kOffset + i11];
snake.y = snake.x - i11;
snake.size = iArr[kOffset + i11] - iArr2[kOffset + i11];
snake.removal = z2;
snake.reverse = false;
return snake;
}
}
int i13 = -i10;
while (i13 <= i10) {
int i14 = i13 + i8;
if (i14 == i10 + i8 || (i14 != (-i10) + i8 && iArr2[(kOffset + i14) - 1] < iArr2[kOffset + i14 + 1])) {
i = iArr2[(kOffset + i14) - 1];
z = false;
} else {
i = iArr2[(kOffset + i14) + 1] - 1;
z = true;
}
int i15 = i - i14;
while (true) {
if (i > 0 && i15 > 0) {
i2 = i4;
if (!callback.areItemsTheSame((startOld + i) - 1, (startNew + i15) - 1)) {
break;
}
i--;
i15--;
i4 = i2;
} else {
i2 = i4;
}
}
i2 = i4;
iArr2[kOffset + i14] = i;
if (z3 || i13 + i8 < (-i10) || i13 + i8 > i10 || iArr[kOffset + i14] < iArr2[kOffset + i14]) {
i13 += 2;
i4 = i2;
} else {
Snake snake2 = new Snake();
snake2.x = iArr2[kOffset + i14];
snake2.y = snake2.x - i14;
snake2.size = iArr[kOffset + i14] - iArr2[kOffset + i14];
snake2.removal = z;
snake2.reverse = true;
return snake2;
}
}
int i16 = i4;
}
int i17 = i4;
throw new IllegalStateException("DiffUtil hit an unexpected case while trying to calculate the optimal path. Please make sure your data is not changing during the diff calculation.");
}
}
}
| 412 | 0.801987 | 1 | 0.801987 | game-dev | MEDIA | 0.565052 | game-dev | 0.973025 | 1 | 0.973025 |
DM3213/Dm-storage | 12,878 | dm-storage/client/object.lua | local TARGET = (Config.DetectTarget and Config.DetectTarget()) or 'none'
---@type table<integer, any>
ObjectList = {}
local CurrentModel, CurrentObject, CurrentObjectKey, CurrentObjectName, CurrentSpawnRange, CurrentCoords = nil, nil, nil, nil, nil, nil
local function resolveModel(m)
local orig = m
if type(m) == 'string' and tonumber(m) then m = tonumber(m) end
if type(m) == 'string' then m = joaat(m) end
if type(m) ~= 'number' then
if lib and lib.print and lib.print.error then lib.print.error(('model not number: %s (%s)'):format(tostring(orig), type(orig))) end
return nil
end
return m
end
local function RequestSpawnObject(model)
local hash = resolveModel(model); if not hash then return false end
RequestModel(hash)
local waited = 0
while not HasModelLoaded(hash) do
Wait(50); waited = waited + 50
if waited > 10000 then
if lib and lib.print and lib.print.error then lib.print.error(('Timeout loading model: %s'):format(tostring(model))) end
return false
end
end
return hash
end
local function CancelPlacement()
if DoesEntityExist(CurrentObject) then DeleteObject(CurrentObject) end
CurrentModel, CurrentObject, CurrentObjectKey, CurrentObjectName, CurrentSpawnRange, CurrentCoords = nil, nil, nil, nil, nil, nil
end
local function refreshObjects()
local ok, inc = pcall(function()
return lib.callback.await('dm-storage:server:RequestObjects', false)
end)
ObjectList = (ok and inc) or {}
end
AddEventHandler('onResourceStart', function(res) if GetCurrentResourceName() == res then refreshObjects() end end)
AddEventHandler('onResourceStop', function(res)
if GetCurrentResourceName() ~= res then return end
for _, v in pairs(ObjectList) do
if v.IsRendered then
if v.targetHandle then
if TARGET == 'ox_target' then pcall(function() exports.ox_target:removeLocalEntity(v.object) end)
elseif TARGET == 'qb-target' then pcall(function() exports['qb-target']:RemoveTargetEntity(v.object) end) end
v.targetHandle = nil
end
if DoesEntityExist(v.object) then DeleteObject(v.object) end
end
end
end)
local fw = Config.DetectFramework()
if fw == 'Qbox' then RegisterNetEvent('QBCore:Client:OnPlayerLoaded', refreshObjects)
elseif fw == 'QBCore' then RegisterNetEvent('QBCore:Client:OnPlayerLoaded', refreshObjects)
else AddEventHandler('esx:onPlayerSpawn', refreshObjects) end
local function StartMoveObject(v)
if not v or not v.id then return end
local cfg = Config.Objects[v.type] or {}
local model = v.model or cfg.model
local hash = RequestSpawnObject(model); if not hash then return end
local ox, oy, oz, oh
if v.IsRendered and v.object and DoesEntityExist(v.object) then
local oc = GetEntityCoords(v.object)
ox, oy, oz = oc.x, oc.y, oc.z
oh = GetEntityHeading(v.object)
DeleteObject(v.object)
v.object = nil
v.IsRendered = nil
else
local c = v.coords or vector4(0.0,0.0,0.0,0.0)
ox, oy, oz, oh = c.x or 0.0, c.y or 0.0, c.z or 0.0, c.w or 0.0
end
local ghost = CreateObject(hash, ox, oy, oz, false, false, false)
SetEntityHeading(ghost, oh or 0.0)
if not DoesEntityExist(ghost) then if lib and lib.notify then lib.notify({type='error', description='Failed to create preview object'}) end; return end
SetEntityAlpha(ghost, 150, false)
SetEntityCollision(ghost, false, false)
SetModelAsNoLongerNeeded(hash)
if GetResourceState('object_gizmo') == 'started' then
exports.object_gizmo:useGizmo(ghost)
if lib and lib.notify then lib.notify({type='inform', description='Press [E] to confirm position, [Backspace] to cancel'}) end
while true do
if IsControlJustPressed(0, 38) or IsDisabledControlJustPressed(0, 38) then break end -- E
if IsControlJustPressed(0, 177) or IsControlJustPressed(0, 202) then DeleteObject(ghost); return end -- Backspace/Esc
Wait(0)
end
else
PlaceObjectOnGroundProperly(ghost)
FreezeEntityPosition(ghost, true)
end
local c = GetEntityCoords(ghost)
local h = GetEntityHeading(ghost)
DeleteObject(ghost)
v.coords = vector4(c.x, c.y, c.z, h or 0.0)
TriggerServerEvent('dm-storage:server:MoveObject', v.id, v.coords)
end
local function StartPackObject(v)
if not v or not v.id then return end
TriggerServerEvent('dm-storage:server:PackUpObject', v.id)
end
local function OpenStorage(v)
if not v or not v.id then return end
TriggerServerEvent('dm-storage:server:OpenStorage', v.id)
end
local function attachTargets(object, v)
if TARGET == 'ox_target' then
exports.ox_target:addLocalEntity(object, {
{ label = 'Open Storage', icon = 'fa-solid fa-box-archive', onSelect = function() OpenStorage(v) end },
{ label = 'Manage Access', icon = 'fa-solid fa-user-group', onSelect = function() TriggerEvent('dm-storage:client:OpenAccessUI', v.id) end },
{ label = 'Move', icon = 'fa-solid fa-up-down-left-right', onSelect = function() StartMoveObject(v) end },
{ label = 'Pack Up', icon = 'fa-solid fa-box', onSelect = function() StartPackObject(v) end },
})
v.targetHandle = true
elseif TARGET == 'qb-target' then
exports['qb-target']:AddTargetEntity(object, { options = {
{ label = 'Open Storage', icon = 'fa-solid fa-box-archive', action = function() OpenStorage(v) end },
{ label = 'Manage Access', icon = 'fa-solid fa-user-group', action = function() TriggerEvent('dm-storage:client:OpenAccessUI', v.id) end },
{ label = 'Move', icon = 'fa-solid fa-up-down-left-right', action = function() StartMoveObject(v) end },
{ label = 'Pack Up', icon = 'fa-solid fa-box', action = function() StartPackObject(v) end },
}, distance = 2.5 })
v.targetHandle = true
end
end
CreateThread(function()
while true do
local ped = PlayerPedId()
local playerCoords = GetEntityCoords(ped)
for _, v in pairs(ObjectList) do
local objCoords = v.coords
local cfg = Config.Objects[v.type] or {}
local spawnRange = tonumber(cfg.spawnRange or 50) or 50.0
local dist = #(playerCoords - vector3(objCoords.x, objCoords.y, objCoords.z))
if dist < spawnRange and not v.IsRendered then
local hash = RequestSpawnObject(v.model or cfg.model)
if hash then
local object = CreateObject(hash, objCoords.x, objCoords.y, objCoords.z, false, false, false)
SetEntityHeading(object, objCoords.w or 0.0)
SetEntityAlpha(object, 0, false)
PlaceObjectOnGroundProperly(object)
FreezeEntityPosition(object, true)
v.IsRendered = true
v.object = object
for i = 0, 255, 51 do Wait(50) SetEntityAlpha(object, i, false) end
attachTargets(object, v)
end
elseif dist >= spawnRange and v.IsRendered then
if v.targetHandle then
if TARGET == 'ox_target' then
pcall(function() exports.ox_target:removeLocalEntity(v.object) end)
elseif TARGET == 'qb-target' then
pcall(function() exports['qb-target']:RemoveTargetEntity(v.object) end)
end
v.targetHandle = nil
end
if DoesEntityExist(v.object) then
for i = 255, 0, -51 do Wait(50) SetEntityAlpha(v.object, i, false) end
DeleteObject(v.object)
end
v.object, v.IsRendered = nil, nil
end
end
Wait(1000)
end
end)
RegisterNetEvent('dm-storage:client:OpenAccessUI', function(objectId)
local data = lib.callback.await('dm-storage:server:GetAccess', false, objectId)
if not data then return end
SetNuiFocus(true, true)
SendNUIMessage({ action = 'access:open', payload = { objectId = objectId, owner = data.owner, list = data.list } })
end)
RegisterNUICallback('storage:access:get', function(data, cb)
local objectId = data and data.objectId
local res = lib.callback.await('dm-storage:server:GetAccess', false, objectId)
cb(res or { owner = '', list = {} })
end)
RegisterNUICallback('storage:access:add', function(data, cb)
local objectId, target = data and data.objectId, data and data.target
if not objectId or not target then return cb(0) end
TriggerServerEvent('dm-storage:server:AddAccess', objectId, target)
SetTimeout(150, function()
local res = lib.callback.await('dm-storage:server:GetAccess', false, objectId)
SendNUIMessage({ action = 'access:update', payload = res })
end)
cb(1)
end)
RegisterNUICallback('storage:access:remove', function(data, cb)
local objectId, cid = data and data.objectId, data and data.cid
if not objectId or not cid then return cb(0) end
TriggerServerEvent('dm-storage:server:RemoveAccess', objectId, cid)
SetTimeout(150, function()
local res = lib.callback.await('dm-storage:server:GetAccess', false, objectId)
SendNUIMessage({ action = 'access:update', payload = res })
end)
cb(1)
end)
RegisterNUICallback('storage:access:close', function(_, cb)
SetNuiFocus(false, false)
cb(1)
end)
RegisterNetEvent('dm-storage:client:FullSync', function(objects)
ObjectList = objects or {}
end)
RegisterNetEvent('dm-storage:client:AddObject', function(object)
if object and object.id then ObjectList[object.id] = object end
end)
RegisterNetEvent('dm-storage:client:receiveObjectDelete', function(id)
local v = ObjectList[id]; if not v then return end
if v.IsRendered then
if v.targetHandle then
if TARGET == 'ox_target' then pcall(function() exports.ox_target:removeLocalEntity(v.object) end)
elseif TARGET == 'qb-target' then pcall(function() exports['qb-target']:RemoveTargetEntity(v.object) end) end
v.targetHandle = nil
end
if DoesEntityExist(v.object) then
for i = 255, 0, -51 do Wait(50) SetEntityAlpha(v.object, i, false) end
DeleteObject(v.object)
end
end
ObjectList[id] = nil
end)
RegisterNetEvent('dm-storage:client:ObjectMoved', function(id, coords)
local v = ObjectList and ObjectList[id]
if not v then return end
v.coords = coords
if v.IsRendered and v.object and DoesEntityExist(v.object) then
FreezeEntityPosition(v.object, false)
SetEntityCoordsNoOffset(v.object, coords.x, coords.y, coords.z, false, false, false)
SetEntityHeading(v.object, coords.w or 0.0)
PlaceObjectOnGroundProperly(v.object)
FreezeEntityPosition(v.object, true)
end
end)
RegisterNetEvent('dm-storage:client:PlaceObject', function(objectKey)
local cfg = Config.Objects[objectKey]
if not cfg then if lib and lib.notify then lib.notify({type='error', description='Invalid storage type'}) end; return end
local model = cfg.model
local hash = RequestSpawnObject(model); if not hash then return end
CurrentModel, CurrentObjectKey, CurrentObjectName, CurrentSpawnRange = model, objectKey, (cfg.label or objectKey), cfg.spawnRange
local ped = PlayerPedId()
local offset = GetEntityCoords(ped) + GetEntityForwardVector(ped) * 3.0
CurrentObject = CreateObject(hash, offset.x, offset.y, offset.z, false, false, false)
if not DoesEntityExist(CurrentObject) then
if lib and lib.notify then lib.notify({type='error', description='Failed to create preview object'}) end
if CurrentObjectKey then TriggerServerEvent('dm-storage:server:RefundPlacementItem', CurrentObjectKey) end
return CancelPlacement()
end
SetEntityAlpha(CurrentObject, 150, false)
SetEntityCollision(CurrentObject, false, false)
SetModelAsNoLongerNeeded(hash)
if GetResourceState('object_gizmo') == 'started' then
exports.object_gizmo:useGizmo(CurrentObject)
if lib and lib.notify then lib.notify({type='inform', description='Press [E] to confirm position, [Backspace] to cancel'}) end
while true do
if IsControlJustPressed(0, 38) or IsDisabledControlJustPressed(0, 38) then break end -- E
if IsControlJustPressed(0, 177) or IsControlJustPressed(0, 202) then
DeleteObject(CurrentObject)
if CurrentObjectKey then TriggerServerEvent('dm-storage:server:RefundPlacementItem', CurrentObjectKey) end
return CancelPlacement()
end
Wait(0)
end
CurrentCoords = GetEntityCoords(CurrentObject)
local heading = GetEntityHeading(CurrentObject)
DeleteObject(CurrentObject)
TriggerServerEvent('dm-storage:server:CreateNewObject', CurrentModel, vector4(CurrentCoords.x, CurrentCoords.y, CurrentCoords.z, heading or 0.0), CurrentObjectKey, { SpawnRange = CurrentSpawnRange }, CurrentObjectName)
CancelPlacement()
else
PlaceObjectOnGroundProperly(CurrentObject)
FreezeEntityPosition(CurrentObject, true)
CurrentCoords = GetEntityCoords(CurrentObject)
local heading = GetEntityHeading(CurrentObject)
DeleteObject(CurrentObject)
TriggerServerEvent('dm-storage:server:CreateNewObject', CurrentModel, vector4(CurrentCoords.x, CurrentCoords.y, CurrentCoords.z, heading or 0.0), CurrentObjectKey, { SpawnRange = CurrentSpawnRange }, CurrentObjectName)
CancelPlacement()
end
end)
| 412 | 0.905187 | 1 | 0.905187 | game-dev | MEDIA | 0.741556 | game-dev | 0.948134 | 1 | 0.948134 |
bibendovsky/bstone | 4,133 | src/lib/sdl2/src/src/joystick/controller_type.c | /*
Copyright (C) Valve Corporation
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 "../SDL_internal.h"
#include "SDL_hints.h"
#include "SDL_gamecontroller.h"
#include "controller_type.h"
#include "controller_list.h"
static const char *GetControllerTypeOverride( int nVID, int nPID )
{
const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERTYPE);
if (hint) {
char key[32];
const char *spot = NULL;
SDL_snprintf(key, sizeof(key), "0x%.4x/0x%.4x=", nVID, nPID);
spot = SDL_strstr(hint, key);
if (!spot) {
SDL_snprintf(key, sizeof(key), "0x%.4X/0x%.4X=", nVID, nPID);
spot = SDL_strstr(hint, key);
}
if (spot) {
spot += SDL_strlen(key);
if (SDL_strncmp(spot, "k_eControllerType_", 18) == 0) {
spot += 18;
}
return spot;
}
}
return NULL;
}
EControllerType GuessControllerType( int nVID, int nPID )
{
#if 0//def _DEBUG
// Verify that there are no duplicates in the controller list
// If the list were sorted, we could do this much more efficiently, as well as improve lookup speed.
static bool s_bCheckedForDuplicates;
if ( !s_bCheckedForDuplicates )
{
s_bCheckedForDuplicates = true;
int i, j;
for ( i = 0; i < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++i )
{
for ( j = i + 1; j < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++j )
{
if ( arrControllers[ i ].m_unDeviceID == arrControllers[ j ].m_unDeviceID )
{
Log( "Duplicate controller entry found for VID 0x%.4x PID 0x%.4x\n", ( arrControllers[ i ].m_unDeviceID >> 16 ), arrControllers[ i ].m_unDeviceID & 0xFFFF );
}
}
}
}
#endif // _DEBUG
unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID );
int iIndex;
const char *pszOverride = GetControllerTypeOverride( nVID, nPID );
if ( pszOverride )
{
if ( SDL_strncasecmp( pszOverride, "Xbox360", 7 ) == 0 )
{
return k_eControllerType_XBox360Controller;
}
if ( SDL_strncasecmp( pszOverride, "XboxOne", 7 ) == 0 )
{
return k_eControllerType_XBoxOneController;
}
if ( SDL_strncasecmp( pszOverride, "PS3", 3 ) == 0 )
{
return k_eControllerType_PS3Controller;
}
if ( SDL_strncasecmp( pszOverride, "PS4", 3 ) == 0 )
{
return k_eControllerType_PS4Controller;
}
if ( SDL_strncasecmp( pszOverride, "PS5", 3 ) == 0 )
{
return k_eControllerType_PS5Controller;
}
if ( SDL_strncasecmp( pszOverride, "SwitchPro", 9 ) == 0 )
{
return k_eControllerType_SwitchProController;
}
if ( SDL_strncasecmp( pszOverride, "Steam", 5 ) == 0 )
{
return k_eControllerType_SteamController;
}
return k_eControllerType_UnknownNonSteamController;
}
for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex )
{
if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID )
{
return arrControllers[ iIndex ].m_eControllerType;
}
}
return k_eControllerType_UnknownNonSteamController;
}
const char *GuessControllerName( int nVID, int nPID )
{
unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID );
int iIndex;
for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex )
{
if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID )
{
return arrControllers[ iIndex ].m_pszName;
}
}
return NULL;
}
#undef MAKE_CONTROLLER_ID
/* vi: set ts=4 sw=4 noexpandtab: */
| 412 | 0.901218 | 1 | 0.901218 | game-dev | MEDIA | 0.851459 | game-dev | 0.94809 | 1 | 0.94809 |
Silverlan/pragma | 14,475 | core/shared/include/pragma/physics/collision_object.hpp | // SPDX-FileCopyrightText: (c) 2019 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#ifndef __PHYS_COLLISION_OBJECT_HPP__
#define __PHYS_COLLISION_OBJECT_HPP__
#include "pragma/networkdefinitions.h"
#include <memory>
#include <sharedutils/def_handle.h>
#include <mathutil/glmutil.h>
#include <mathutil/uquat.h>
#include <mathutil/transform.hpp>
#include "pragma/physics/base.hpp"
#include "pragma/lua/baseluaobj.h"
#include "pragma/physics/collisionmasks.h"
#include "pragma/networking/nwm_velocity_correction.hpp"
#include <vector>
#if 0
#include "pragma/physics/physmotionstate.h"
#endif
class ModelSubMesh;
namespace pragma::physics {
class IShape;
class IRigidBody;
class ISoftBody;
class IGhostObject;
struct ContactInfo;
class DLLNETWORK ICollisionObject : public IBase, public IWorldObject {
public:
enum class ActivationState : uint32_t {
Active = 0,
AlwaysActive,
AlwaysInactive,
Asleep,
WaitForDeactivation,
Count
};
enum class StateFlags : uint32_t {
None = 0u,
HasOrigin = 1u,
CustomSurfaceMaterial = HasOrigin << 1u,
CCDEnabled = CustomSurfaceMaterial << 1u,
UpdateAABB = CCDEnabled << 1u,
ContactReportEnabled = UpdateAABB << 1u,
AlwaysAwake = ContactReportEnabled << 1u,
Awake = AlwaysAwake << 1u
};
virtual void OnRemove() override;
int GetSurfaceMaterial() const;
void SetSurfaceMaterial(int id);
void SetOrigin(const Vector3 &origin);
const Vector3 &GetOrigin() const;
Bool HasOrigin() const;
Vector3 GetGravity() const;
UInt32 GetBoneID() const;
void SetBoneID(UInt32 id);
void SetCollisionShape(pragma::physics::IShape *shape);
const pragma::physics::IShape *GetCollisionShape() const;
pragma::physics::IShape *GetCollisionShape();
virtual bool IsRigid() const;
virtual bool IsGhost() const;
virtual bool IsSoftBody() const;
virtual void InitializeLuaObject(lua_State *lua) override;
virtual void SetTrigger(bool bTrigger) = 0;
virtual bool IsTrigger() const = 0;
virtual void TransformLocalPose(const umath::Transform &t) = 0;
virtual void SetActivationState(ActivationState state) = 0;
virtual ActivationState GetActivationState() const = 0;
virtual void SetContactProcessingThreshold(float threshold) = 0;
virtual bool IsStatic() const = 0;
virtual void SetStatic(bool b) = 0;
virtual void SetCCDEnabled(bool b) = 0;
virtual void GetAABB(Vector3 &min, Vector3 &max) const = 0;
virtual Vector3 GetPos() const = 0;
virtual void SetPos(const Vector3 &pos) = 0;
virtual Quat GetRotation() const = 0;
virtual void SetRotation(const Quat &rot) = 0;
virtual umath::Transform GetBaseTransform() = 0;
virtual void SetBaseTransform(const umath::Transform &t) = 0;
virtual umath::Transform GetWorldTransform() = 0;
virtual void SetWorldTransform(const umath::Transform &t) = 0;
virtual void WakeUp(bool forceActivation = false) = 0;
virtual void PutToSleep() = 0;
bool IsAsleep() const;
bool IsAwake() const;
virtual void SetSimulationEnabled(bool b) = 0;
void DisableSimulation();
void EnableSimulation();
virtual bool IsSimulationEnabled() const = 0;
virtual void SetCollisionsEnabled(bool enabled) = 0;
void SetCollisionFilterGroup(CollisionMask group);
CollisionMask GetCollisionFilterGroup() const;
void SetCollisionFilterMask(CollisionMask mask);
CollisionMask GetCollisionFilterMask() const;
virtual void SetSleepReportEnabled(bool reportEnabled) = 0;
virtual bool IsSleepReportEnabled() const = 0;
void SetContactReportEnabled(bool reportEnabled);
bool IsContactReportEnabled() const;
virtual void PreSimulate();
virtual void PostSimulate();
void OnContact(const ContactInfo &contactInfo);
void OnStartTouch(ICollisionObject &other);
void OnEndTouch(ICollisionObject &other);
void OnWake();
void OnSleep();
void SetAlwaysAwake(bool alwaysAwake);
bool IsAlwaysAwake() const;
void UpdateAABB();
bool ShouldUpdateAABB() const;
void ResetUpdateAABBFlag();
virtual IRigidBody *GetRigidBody();
const IRigidBody *GetRigidBody() const;
virtual ISoftBody *GetSoftBody();
const ISoftBody *GetSoftBody() const;
virtual IGhostObject *GetGhostObject();
const IGhostObject *GetGhostObject() const;
virtual void InitializeLuaHandle(const util::TWeakSharedHandle<IBase> &handle) override;
protected:
ICollisionObject(pragma::physics::IEnvironment &env, pragma::physics::IShape &shape);
virtual void ApplyCollisionShape(pragma::physics::IShape *optShape) = 0;
virtual void DoSetCollisionFilterGroup(CollisionMask group) = 0;
virtual void DoSetCollisionFilterMask(CollisionMask mask) = 0;
virtual void DoSpawn() override;
std::shared_ptr<pragma::physics::IShape> m_shape;
UInt32 m_boneId = 0u;
Vector3 m_origin = {};
StateFlags m_stateFlags = StateFlags::CCDEnabled;
int m_surfaceMaterial = 0u;
CollisionMask m_collisionFilterGroup = CollisionMask::Default;
CollisionMask m_collisionFilterMask = CollisionMask::Default;
void UpdateSurfaceMaterial();
};
class DLLNETWORK IGhostObject : virtual public ICollisionObject {
public:
virtual bool IsGhost() const override;
virtual IGhostObject *GetGhostObject() override;
virtual void InitializeLuaObject(lua_State *lua) override;
protected:
using ICollisionObject::ICollisionObject;
};
class DLLNETWORK IRigidBody : virtual public ICollisionObject {
public:
virtual void InitializeLuaObject(lua_State *lua) override;
virtual bool IsRigid() const override;
virtual IRigidBody *GetRigidBody() override;
virtual void ApplyForce(const Vector3 &force, bool autoWake = true) = 0;
virtual void ApplyForce(const Vector3 &force, const Vector3 &relPos, bool autoWake = true) = 0;
virtual void ApplyImpulse(const Vector3 &impulse, bool autoWake = true) = 0;
virtual void ApplyImpulse(const Vector3 &impulse, const Vector3 &relPos, bool autoWake = true) = 0;
virtual void ApplyTorque(const Vector3 &torque, bool autoWake = true) = 0;
virtual void ApplyTorqueImpulse(const Vector3 &torque, bool autoWake = true) = 0;
virtual void ClearForces() = 0;
virtual Vector3 GetTotalForce() const = 0;
virtual Vector3 GetTotalTorque() const = 0;
virtual void SetMassProps(float mass, const Vector3 &inertia) = 0;
virtual float GetMass() const = 0;
virtual void SetMass(float mass) = 0;
virtual void SetMassAndUpdateInertia(float mass) = 0;
virtual Vector3 GetCenterOfMass() const = 0;
virtual Vector3 GetInertia() = 0;
virtual Mat3 GetInvInertiaTensorWorld() const = 0;
virtual void SetInertia(const Vector3 &inertia) = 0;
virtual Vector3 GetLinearVelocity() const = 0;
virtual Vector3 GetAngularVelocity() const = 0;
virtual void SetLinearVelocity(const Vector3 &vel, bool autoWake = true) = 0;
virtual void SetAngularVelocity(const Vector3 &vel, bool autoWake = true) = 0;
virtual void SetLinearFactor(const Vector3 &factor) = 0;
virtual void SetAngularFactor(const Vector3 &factor) = 0;
virtual Vector3 GetLinearFactor() const = 0;
virtual Vector3 GetAngularFactor() const = 0;
void SetDamping(float linDamping, float angDamping);
virtual void SetLinearDamping(float damping) = 0;
virtual void SetAngularDamping(float damping) = 0;
virtual float GetLinearDamping() const = 0;
virtual float GetAngularDamping() const = 0;
virtual void SetLinearSleepingThreshold(float threshold) = 0;
virtual void SetAngularSleepingThreshold(float threshold) = 0;
void SetSleepingThresholds(float linear, float angular);
virtual float GetLinearSleepingThreshold() const = 0;
virtual float GetAngularSleepingThreshold() const = 0;
std::pair<float, float> GetSleepingThreshold() const;
virtual void SetCenterOfMassOffset(const Vector3 &offset) = 0;
virtual Vector3 GetCenterOfMassOffset() const = 0;
virtual void SetKinematic(bool bKinematic) = 0;
virtual bool IsKinematic() const = 0;
protected:
IRigidBody(IEnvironment &env, pragma::physics::IShape &shape);
};
class DLLNETWORK ISoftBody : virtual public ICollisionObject {
public:
virtual void InitializeLuaObject(lua_State *lua) override;
virtual bool IsSoftBody() const override;
virtual ISoftBody *GetSoftBody() override;
virtual void AddVelocity(const Vector3 &vel) = 0;
virtual const std::vector<uint16_t> &GetMeshVertexIndicesToLocalIndices() const = 0;
virtual const std::vector<uint16_t> &GetLocalVertexIndicesToNodeIndices() const = 0;
virtual const std::vector<uint16_t> &GetLocalVertexIndicesToMeshVertexIndices() const = 0;
virtual const std::vector<uint16_t> &GetNodeIndicesToLocalVertexIndices() const = 0;
virtual bool MeshVertexIndexToLocalVertexIndex(uint16_t meshVertexIndex, uint16_t &localIndex) const = 0;
virtual bool LocalVertexIndexToMeshVertexIndex(uint16_t localIndex, uint16_t &meshVertexIndex) const = 0;
virtual bool LocalVertexIndexToNodeIndex(uint16_t localVertexIndex, uint16_t &nodeIndex) const = 0;
virtual bool NodeIndexToLocalVertexIndex(uint16_t nodeIndex, uint16_t &localVertexIndex) const = 0;
virtual bool MeshVertexIndexToNodeIndex(uint16_t meshVertexIndex, uint16_t &nodeIndex) const = 0;
virtual bool NodeIndexToMeshVertexIndex(uint16_t nodeIndex, uint16_t &meshVertexIndex) const = 0;
virtual void SetSubMesh(const ModelSubMesh &subMesh, const std::vector<uint16_t> &meshVertexIndicesToLocalVertexIndices) = 0;
ModelSubMesh *GetSubMesh() const;
virtual void UpdateLinearVelocity() = 0;
virtual void AppendAnchor(uint32_t nodeId, IRigidBody &body, const Vector3 &localPivot, bool bDisableCollision = false, float influence = 1.f) = 0;
virtual void AppendAnchor(uint32_t nodeId, IRigidBody &body, bool bDisableCollision = false, float influence = 1.f) = 0;
virtual uint32_t GetNodeCount() const = 0;
virtual const Vector3 &GetLinearVelocity() const = 0;
virtual void AddAeroForceToNode(int32_t node, const Vector3 &force) = 0;
virtual void AddAeroForceToFace(int32_t face, const Vector3 &force) = 0;
virtual void AddForce(const Vector3 &force) = 0;
virtual void AddForce(uint32_t node, const Vector3 &force) = 0;
virtual void AddLinearVelocity(const Vector3 &vel) = 0;
virtual void AddLinearVelocity(uint32_t node, const Vector3 &vel) = 0;
virtual float GetFriction() const = 0;
virtual float GetHitFraction() const = 0;
virtual float GetRollingFriction() const = 0;
virtual Vector3 GetAnisotropicFriction() const = 0;
virtual void SetFriction(float friction) = 0;
virtual void SetHitFraction(float fraction) = 0;
virtual void SetRollingFriction(float friction) = 0;
virtual void SetAnisotropicFriction(const Vector3 &friction) = 0;
virtual float GetMass(int32_t node) const = 0;
virtual float GetMass() const = 0;
virtual float GetRestitution() const = 0;
virtual float GetRestLengthScale() const = 0;
virtual Vector3 GetWindVelocity() const = 0;
virtual void SetMass(int32_t node, float mass) = 0;
virtual void SetMass(float mass) = 0;
virtual void SetRestitution(float rest) = 0;
virtual void SetRestLengthScale(float scale) = 0;
virtual void SetWindVelocity(const Vector3 &vel) = 0;
virtual void SetLinearVelocity(const Vector3 &vel) = 0;
virtual void SetVolumeDensity(float density) = 0;
virtual void SetVolumeMass(float mass) = 0;
virtual float GetVolume() const = 0;
virtual void SetDensity(float density) = 0;
virtual void SetAnchorsHardness(float val) = 0;
virtual void SetRigidContactsHardness(float val) = 0;
virtual void SetDynamicFrictionCoefficient(float val) = 0;
virtual void SetDragCoefficient(float val) = 0;
virtual void SetDampingCoefficient(float val) = 0;
virtual void SetKineticContactsHardness(float val) = 0;
virtual void SetLiftCoefficient(float val) = 0;
virtual void SetPoseMatchingCoefficient(float val) = 0;
virtual void SetPressureCoefficient(float val) = 0;
virtual void SetSoftContactsHardness(float val) = 0;
virtual void SetSoftVsKineticHardness(float val) = 0;
virtual void SetSoftVsRigidImpulseSplitK(float val) = 0;
virtual void SetSoftVsRigidHardness(float val) = 0;
virtual void SetSoftVsRigidImpulseSplitR(float val) = 0;
virtual void SetSoftVsSoftHardness(float val) = 0;
virtual void SetSoftVsRigidImpulseSplitS(float val) = 0;
virtual void SetVolumeConversationCoefficient(float val) = 0;
virtual void SetVelocitiesCorrectionFactor(float val) = 0;
virtual float GetAnchorsHardness() const = 0;
virtual float GetRigidContactsHardness() const = 0;
virtual float GetDynamicFrictionCoefficient() const = 0;
virtual float GetDragCoefficient() const = 0;
virtual float GetDampingCoefficient() const = 0;
virtual float GetKineticContactsHardness() const = 0;
virtual float GetLiftCoefficient() const = 0;
virtual float GetPoseMatchingCoefficient() const = 0;
virtual float GetPressureCoefficient() const = 0;
virtual float GetSoftContactsHardness() const = 0;
virtual float GetSoftVsKineticHardness() const = 0;
virtual float GetSoftVsRigidImpulseSplitK() const = 0;
virtual float GetSoftVsRigidHardness() const = 0;
virtual float GetSoftVsRigidImpulseSplitR() const = 0;
virtual float GetSoftVsSoftHardness() const = 0;
virtual float GetSoftVsRigidImpulseSplitS() const = 0;
virtual float GetVolumeConversationCoefficient() const = 0;
virtual float GetVelocitiesCorrectionFactor() const = 0;
virtual void SetMaterialAngularStiffnessCoefficient(uint32_t matId, float val) = 0;
virtual void SetMaterialLinearStiffnessCoefficient(uint32_t matId, float val) = 0;
virtual void SetMaterialVolumeStiffnessCoefficient(uint32_t matId, float val) = 0;
virtual float GetMaterialAngularStiffnessCoefficient(uint32_t matId) const = 0;
virtual float GetMaterialLinearStiffnessCoefficient(uint32_t matId) const = 0;
virtual float GetMaterialVolumeStiffnessCoefficient(uint32_t matId) const = 0;
protected:
ISoftBody(IEnvironment &env, pragma::physics::IShape &shape, const std::vector<uint16_t> &meshVertIndicesToPhysIndices);
std::weak_ptr<ModelSubMesh> m_subMesh = {};
};
};
REGISTER_BASIC_BITWISE_OPERATORS(pragma::physics::ICollisionObject::StateFlags)
DLLNETWORK std::ostream &operator<<(std::ostream &out, const pragma::physics::ICollisionObject &o);
DLLNETWORK std::ostream &operator<<(std::ostream &out, const pragma::physics::IGhostObject &o);
DLLNETWORK std::ostream &operator<<(std::ostream &out, const pragma::physics::IRigidBody &o);
DLLNETWORK std::ostream &operator<<(std::ostream &out, const pragma::physics::ISoftBody &o);
#endif
| 412 | 0.80735 | 1 | 0.80735 | game-dev | MEDIA | 0.819089 | game-dev | 0.556174 | 1 | 0.556174 |
tyfon7/UIFixes | 7,858 | src/Patches/TagPatches.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using EFT.InventoryLogic;
using EFT.UI;
using EFT.UI.DragAndDrop;
using HarmonyLib;
using SPT.Reflection.Patching;
using SPT.Reflection.Utils;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace UIFixes;
public static class TagPatches
{
public static void Enable()
{
new OnEnterPatch().Enable();
new TagsOverCaptionsPatch().Enable();
new AddTagNewItemPatch().Enable();
new AddTagParsedItemPatch().Enable();
new TagAdditionalTypePatch().Enable();
new KeepTagsLocalPatch().Enable();
}
// Save the tag when enter is pressed
public class OnEnterPatch : ModulePatch
{
protected override MethodBase GetTargetMethod()
{
return AccessTools.DeclaredMethod(typeof(EditTagWindow), nameof(EditTagWindow.Show));
}
[PatchPostfix]
public static void Postfix(EditTagWindow __instance, ValidationInputField ____tagInput)
{
____tagInput.onSubmit.AddListener(value => __instance.method_4());
____tagInput.ActivateInputField();
____tagInput.Select();
}
}
// On narrow items, prioritize the tag over the caption
public class TagsOverCaptionsPatch : ModulePatch
{
protected override MethodBase GetTargetMethod()
{
return AccessTools.Method(typeof(GridItemView), nameof(GridItemView.method_22));
}
[PatchPostfix]
public static async void Postfix(GridItemView __instance, TextMeshProUGUI ___TagName, TextMeshProUGUI ___Caption, Image ____tagColor, Image ___MainImage, Task __result)
{
await __result;
// Rerun logic with preferred priority. Running again rather than prefix overwrite because this also fixes the existing race condition
___TagName.gameObject.SetActive(false);
___Caption.gameObject.SetActive(true);
await Task.Yield();
RectTransform tagTransform = ____tagColor.rectTransform;
float tagSpace = __instance.RectTransform.rect.width - ___Caption.renderedWidth - 2f;
if (tagSpace < 40f)
{
tagTransform.sizeDelta = new Vector2(__instance.RectTransform.sizeDelta.x, tagTransform.sizeDelta.y);
if (Settings.TagsOverCaptions.Value)
{
___TagName.gameObject.SetActive(true);
float tagSize = Mathf.Clamp(___TagName.preferredWidth + 12f, 40f, __instance.RectTransform.sizeDelta.x - 2f);
tagTransform.sizeDelta = new Vector2(tagSize, ____tagColor.rectTransform.sizeDelta.y);
___Caption.gameObject.SetActive(false);
}
}
else
{
___TagName.gameObject.SetActive(true);
float tagSize = Mathf.Clamp(___TagName.preferredWidth + 12f, 40f, tagSpace);
tagTransform.sizeDelta = new Vector2(tagSize, ____tagColor.rectTransform.sizeDelta.y);
}
// Make sure it's on top of the image
if (____tagColor.transform.GetSiblingIndex() < ___MainImage.transform.GetSiblingIndex())
{
____tagColor.transform.SetSiblingIndex(___MainImage.transform.GetSiblingIndex() + 1);
}
}
}
public class TagAdditionalTypePatch : ModulePatch
{
protected override MethodBase GetTargetMethod()
{
return AccessTools.DeclaredProperty(typeof(Item), nameof(Item.ItemInteractionButtons)).GetMethod;
}
[PatchPostfix]
public static IEnumerable<EItemInfoButton> Postfix(IEnumerable<EItemInfoButton> values, Item __instance)
{
foreach (var value in values)
{
yield return value;
}
if (!IsTaggingEnabled(__instance))
{
yield break;
}
// Ensure this item has a tag component
TagComponent tag = __instance.GetItemComponent<TagComponent>();
if (tag == null)
{
yield break;
}
yield return EItemInfoButton.Tag;
if (!string.IsNullOrEmpty(tag.Name))
{
yield return EItemInfoButton.ResetTag;
}
yield break;
}
}
// Adds a TagComponent to types when they are constructed completely new
public class AddTagNewItemPatch : ModulePatch
{
private static FieldInfo ComponentsField;
protected override MethodBase GetTargetMethod()
{
ComponentsField = AccessTools.Field(typeof(Item), "Components");
return AccessTools.Method(typeof(ItemFactoryClass), nameof(ItemFactoryClass.CreateItem));
}
[PatchPostfix]
public static void Postfix(Item __result, object itemDiff)
{
// If itemDiff is null, there's no deserialization, so just create the component
if (itemDiff == null && IsTaggingEnabled(__result))
{
var components = (List<IItemComponent>)ComponentsField.GetValue(__result);
components.Add(new TagComponent(__result));
}
}
}
// Adds a TagComponent to types when they are deserialized from json
// Also populate it; BSG does some insane manual reflection here for deserialization and looks for the literal Tag property (which it won't find)
public class AddTagParsedItemPatch : ModulePatch
{
protected override MethodBase GetTargetMethod()
{
Type type = PatchConstants.EftTypes.Single(t => t.GetMethod("CreateItem", BindingFlags.Public | BindingFlags.Static) != null); // GClass1682
return AccessTools.Method(type, "CreateItem");
}
[PatchPostfix]
public static void Postfix(Item item, ItemProperties properties)
{
if (IsTaggingEnabled(item))
{
TagComponent tagComponent = new(item);
item.Components.Add(tagComponent);
var propDictionary = properties.JToken.ToObject<Dictionary<string, ItemProperties>>();
if (propDictionary.TryGetValue("Tag", out ItemProperties tagProperty))
{
tagProperty.ParseJsonTo(tagComponent.GetType(), tagComponent);
}
}
}
}
// For Fika compat: When items are serialized and set to other clients, lots of (normally safe) assumptions are made, like what components items have
// If the other client does not have UIFixes, it will puke trying to deserialize a tag component on an item type that doesn't normally have them
// So don't serialize the tag. It's no big loss anyway.
public class KeepTagsLocalPatch : ModulePatch
{
protected override MethodBase GetTargetMethod()
{
return AccessTools.Method(typeof(EFTItemSerializerClass), nameof(EFTItemSerializerClass.smethod_2));
}
[PatchPrefix]
public static bool Prefix(IItemComponent component, ref object __result)
{
if (component is TagComponent tagComponent)
{
if (tagComponent.Item is BackpackItemClass or VestItemClass)
{
__result = null;
return false;
}
}
return true;
}
}
private static bool IsTaggingEnabled<T>(T instance)
{
return instance switch
{
BackpackItemClass => Settings.TagBackpacks.Value,
VestItemClass => Settings.TagVests.Value,
_ => false
};
}
} | 412 | 0.861168 | 1 | 0.861168 | game-dev | MEDIA | 0.728049 | game-dev | 0.942827 | 1 | 0.942827 |
OSRSB/OsrsBot | 1,412 | src/main/java/net/runelite/rsb/event/impl/DrawGround.java | package net.runelite.rsb.event.impl;
import net.runelite.api.Point;
import net.runelite.rsb.botLauncher.BotLite;
import net.runelite.rsb.event.listener.PaintListener;
import net.runelite.rsb.methods.MethodContext;
import net.runelite.rsb.wrappers.RSGroundItem;
import net.runelite.rsb.wrappers.RSPlayer;
import net.runelite.rsb.wrappers.RSTile;
import java.awt.*;
public class DrawGround implements PaintListener {
private final MethodContext ctx;
public DrawGround(BotLite bot) {
this.ctx = bot.getMethodContext();
}
public void onRepaint(final Graphics render) {
if (!ctx.game.isLoggedIn()) {
return;
}
final RSPlayer player = ctx.players.getMyPlayer();
if (player == null) {
return;
}
render.setColor(Color.WHITE);
final RSTile location = player.getLocation();
for (int x = location.getWorldLocation().getX() - 25; x < location.getWorldLocation().getX() + 25; x++) {
for (int y = location.getWorldLocation().getY() - 25; y < location.getWorldLocation().getY() + 25; y++) {
final RSGroundItem[] item = ctx.groundItems.getAllAt(x, y);
if ((item == null) || (item.length == 0)) {
continue;
}
final Point screen = ctx.calc.tileToScreen(item[0].getLocation());
if (ctx.calc.pointOnScreen(screen)) {
render.drawString("" + item[0].getItem().getID(), location.getWorldLocation().getX() - 10, location.getWorldLocation().getY());
}
}
}
}
}
| 412 | 0.909881 | 1 | 0.909881 | game-dev | MEDIA | 0.848775 | game-dev | 0.867765 | 1 | 0.867765 |
intel/fpga-partial-reconfig | 1,853 | ref_designs/a10_pcie_devkit_cvp_hpr/verif/design_top_sim/persona_base_sequence_lib.sv | `ifndef INC_PERSONA_BASE_SEQUENCE_LIB_SV
`define INC_PERSONA_BASE_SEQUENCE_LIB_SV
`include "uvm_macros.svh"
import uvm_pkg::*;
class persona_base_seq_c extends bar4_avmm_pkg::bar4_avmm_base_seq_c;
`uvm_object_utils(persona_base_seq_c)
function new(string name = "[name]");
super.new(name);
endfunction
task read_persona_id_block_until_response(string description, logic [design_top_sim_cfg_pkg::DESIGN_TOP_BAR4_BFM_AV_ADDRESS_W-1:0] address);
create_simple_read_transaction_block_until_response(description, address);
endtask
task read_persona_id(string description, logic [design_top_sim_cfg_pkg::DESIGN_TOP_BAR4_BFM_AV_ADDRESS_W-1:0] address);
create_simple_read_transaction(description, address);
endtask
endclass
class read_persona_id_seq_c extends persona_base_seq_c;
`uvm_object_utils(read_persona_id_seq_c)
function new(string name = "[name]");
super.new(name);
endfunction
task body();
read_persona_id_block_until_response(description, PR_REGION_0_PERSONA_ID_ADDRESS);
endtask
endclass
class read_parent_persona_child_0_persona_id_seq_c extends persona_base_seq_c;
`uvm_object_utils(read_parent_persona_child_0_persona_id_seq_c)
function new(string name = "[name]");
super.new(name);
endfunction
task body();
read_persona_id_block_until_response(description, PARENT_PERSONA_PR_REGION_0_PERSONA_ID_ADDRESS);
endtask
endclass
class read_parent_persona_child_1_persona_id_seq_c extends persona_base_seq_c;
`uvm_object_utils(read_parent_persona_child_1_persona_id_seq_c)
function new(string name = "[name]");
super.new(name);
endfunction
task body();
read_persona_id_block_until_response(description, PARENT_PERSONA_PR_REGION_1_PERSONA_ID_ADDRESS);
endtask
endclass
`endif //INC_PERSONA_BASE_SEQUENCE_LIB_SV
| 412 | 0.797633 | 1 | 0.797633 | game-dev | MEDIA | 0.299088 | game-dev | 0.718377 | 1 | 0.718377 |
omnifaces/omnifaces | 8,503 | src/main/java/org/omnifaces/model/tree/AbstractTreeModel.java | /*
* Copyright OmniFaces
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.omnifaces.model.tree;
import static org.omnifaces.util.Reflection.instance;
import static org.omnifaces.util.Utils.executeAtomically;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
/**
* A base implementation of {@link TreeModel}. Implementors basically only need to implement {@link #createChildren()}
* wherein a concrete instance of the desired underlying {@link Collection} is returned.
*
* @author Bauke Scholtz
* @param <T> The type of the wrapped data of the tree node.
* @since 1.7
* @see ListTreeModel
* @see SortedTreeModel
*/
public abstract class AbstractTreeModel<T> implements TreeModel<T> {
// Constants ------------------------------------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// Properties -----------------------------------------------------------------------------------------------------
private T data;
private AbstractTreeModel<T> parent;
private Collection<TreeModel<T>> children;
private List<TreeModel<T>> unmodifiableChildren = Collections.emptyList();
private int index;
private final ReentrantLock lock = new ReentrantLock();
// Actions --------------------------------------------------------------------------------------------------------
/**
* Returns a concrete (and usually empty) {@link Collection} instance which should hold the tree's children.
* @return A concrete (and usually empty) {@link Collection} instance which should hold the tree's children.
*/
protected abstract Collection<TreeModel<T>> createChildren();
// Mutators -------------------------------------------------------------------------------------------------------
@Override
public void setData(T data) {
this.data = data;
}
@Override
@SuppressWarnings("unchecked")
public TreeModel<T> addChild(T data) {
var child = instance(getClass());
child.data = data;
return addChildNode(child);
}
@Override
public TreeModel<T> addChildNode(TreeModel<T> child) {
if (child == null || child.getClass() != getClass()) {
throw new IllegalArgumentException();
}
if (children == null) {
children = createChildren();
}
((AbstractTreeModel<T>) child).parent = this;
((AbstractTreeModel<T>) child).index = children.size();
children.add(child);
return child;
}
@Override
public TreeModel<T> remove() {
if (!isRoot()) {
executeAtomically(lock, () -> {
parent.children.remove(this);
// Fix the indexes of the children (that's why it needs to be synchronized).
var newIndex = 0;
for (var child : parent.children) {
((AbstractTreeModel<T>) child).index = newIndex;
newIndex++;
}
});
}
return parent;
}
// Accessors ------------------------------------------------------------------------------------------------------
@Override
public T getData() {
return data;
}
@Override
public TreeModel<T> getParent() {
return parent;
}
@Override
public TreeModel<T> getNextSibling() {
return getNextSibling(parent, index + 1);
}
/**
* Recursive helper method for {@link #getNextSibling()}.
*/
private TreeModel<T> getNextSibling(TreeModel<T> parent, int index) {
if (parent == null) {
return null;
}
else if (index < parent.getChildCount()) {
return parent.getChildren().get(index);
}
else {
var nextParent = parent.getNextSibling();
return getNextSibling(nextParent, 0);
}
}
@Override
public TreeModel<T> getPreviousSibling() {
return getPreviousSibling(parent, index - 1);
}
/**
* Recursive helper method for {@link #getPreviousSibling()}.
*/
private TreeModel<T> getPreviousSibling(TreeModel<T> parent, int index) {
if (parent == null) {
return null;
}
else if (index >= 0) {
return parent.getChildren().get(index);
}
else {
var previousParent = parent.getPreviousSibling();
return getPreviousSibling(previousParent, (previousParent != null ? previousParent.getChildCount() : 0) - 1);
}
}
@Override
public int getChildCount() {
return children == null ? 0 : children.size();
}
@Override
public List<TreeModel<T>> getChildren() {
if (unmodifiableChildren.size() != getChildCount()) {
unmodifiableChildren = Collections.unmodifiableList(children instanceof List
? (List<TreeModel<T>>) children : new ArrayList<>(children));
}
return unmodifiableChildren;
}
@Override
public Iterator<TreeModel<T>> iterator() {
return getChildren().iterator();
}
@Override
public int getLevel() {
return isRoot() ? 0 : parent.getLevel() + 1;
}
@Override
public String getIndex() {
return isRoot() ? null : parent.getParentIndex() + index;
}
private String getParentIndex() {
return isRoot() ? "" : getIndex() + "_";
}
// Checkers -------------------------------------------------------------------------------------------------------
@Override
public boolean isRoot() {
return parent == null;
}
@Override
public boolean isLeaf() {
return getChildCount() == 0;
}
@Override
public boolean isFirst() {
return !isRoot() && index == 0;
}
@Override
public boolean isLast() {
return !isRoot() && index + 1 == parent.getChildCount();
}
// Object overrides -----------------------------------------------------------------------------------------------
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object == null || object.getClass() != getClass()) {
return false;
}
return equals(this, (AbstractTreeModel<?>) object, false) && equals(getRoot(this), getRoot((AbstractTreeModel<?>) object), true);
}
private static AbstractTreeModel<?> getRoot(AbstractTreeModel<?> node) {
TreeModel<?> root = node;
while (root.getParent() != null) {
root = root.getParent();
}
return (AbstractTreeModel<?>) root;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean equals(AbstractTreeModel thiz, AbstractTreeModel other, boolean recurse) {
if (thiz == other) {
return true;
}
if (!Objects.equals(thiz.data, other.data)) {
return false;
}
if (recurse && thiz.children != null) {
if (thiz.getChildCount() != other.getChildCount()) {
return false;
}
Iterator<AbstractTreeModel> thisChildren = thiz.children.iterator();
Iterator<AbstractTreeModel> otherChildren = other.children.iterator();
while (thisChildren.hasNext() && otherChildren.hasNext()) {
if (!equals(thisChildren.next(), otherChildren.next(), true)) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(data, children);
}
@Override
public String toString() {
return (data == null ? "" : data) + "" + (children == null ? "" : children);
}
} | 412 | 0.953089 | 1 | 0.953089 | game-dev | MEDIA | 0.130362 | game-dev | 0.995003 | 1 | 0.995003 |
jdolan/quake2 | 15,160 | src/game/m_flyer.c | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
==============================================================================
flyer
==============================================================================
*/
#include "g_local.h"
#include "m_flyer.h"
qboolean visible (edict_t *self, edict_t *other);
static int nextmove; // Used for start/stop frames
static int sound_sight;
static int sound_idle;
static int sound_pain1;
static int sound_pain2;
static int sound_slash;
static int sound_sproing;
static int sound_die;
void flyer_check_melee(edict_t *self);
void flyer_loop_melee (edict_t *self);
void flyer_melee (edict_t *self);
void flyer_setstart (edict_t *self);
void flyer_stand (edict_t *self);
void flyer_nextmove (edict_t *self);
void flyer_sight (edict_t *self, edict_t *other)
{
gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
}
void flyer_idle (edict_t *self)
{
gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
}
void flyer_pop_blades (edict_t *self)
{
gi.sound (self, CHAN_VOICE, sound_sproing, 1, ATTN_NORM, 0);
}
mframe_t flyer_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},
{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},
{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},
{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},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL},
{ai_stand, 0, NULL}
};
mmove_t flyer_move_stand = {FRAME_stand01, FRAME_stand45, flyer_frames_stand, NULL};
mframe_t flyer_frames_walk [] =
{
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL},
{ai_walk, 5, NULL}
};
mmove_t flyer_move_walk = {FRAME_stand01, FRAME_stand45, flyer_frames_walk, NULL};
mframe_t flyer_frames_run [] =
{
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL},
{ai_run, 10, NULL}
};
mmove_t flyer_move_run = {FRAME_stand01, FRAME_stand45, flyer_frames_run, NULL};
void flyer_run (edict_t *self)
{
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
self->monsterinfo.currentmove = &flyer_move_stand;
else
self->monsterinfo.currentmove = &flyer_move_run;
}
void flyer_walk (edict_t *self)
{
self->monsterinfo.currentmove = &flyer_move_walk;
}
void flyer_stand (edict_t *self)
{
self->monsterinfo.currentmove = &flyer_move_stand;
}
mframe_t flyer_frames_start [] =
{
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, flyer_nextmove}
};
mmove_t flyer_move_start = {FRAME_start01, FRAME_start06, flyer_frames_start, NULL};
mframe_t flyer_frames_stop [] =
{
{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, flyer_nextmove}
};
mmove_t flyer_move_stop = {FRAME_stop01, FRAME_stop07, flyer_frames_stop, NULL};
void flyer_stop (edict_t *self)
{
self->monsterinfo.currentmove = &flyer_move_stop;
}
void flyer_start (edict_t *self)
{
self->monsterinfo.currentmove = &flyer_move_start;
}
mframe_t flyer_frames_rollright [] =
{
{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 flyer_move_rollright = {FRAME_rollr01, FRAME_rollr09, flyer_frames_rollright, NULL};
mframe_t flyer_frames_rollleft [] =
{
{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 flyer_move_rollleft = {FRAME_rollf01, FRAME_rollf09, flyer_frames_rollleft, NULL};
mframe_t flyer_frames_pain3 [] =
{
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t flyer_move_pain3 = {FRAME_pain301, FRAME_pain304, flyer_frames_pain3, flyer_run};
mframe_t flyer_frames_pain2 [] =
{
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t flyer_move_pain2 = {FRAME_pain201, FRAME_pain204, flyer_frames_pain2, flyer_run};
mframe_t flyer_frames_pain1 [] =
{
{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 flyer_move_pain1 = {FRAME_pain101, FRAME_pain109, flyer_frames_pain1, flyer_run};
mframe_t flyer_frames_defense [] =
{
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}, // Hold this frame
{ai_move, 0, NULL},
{ai_move, 0, NULL},
{ai_move, 0, NULL}
};
mmove_t flyer_move_defense = {FRAME_defens01, FRAME_defens06, flyer_frames_defense, NULL};
mframe_t flyer_frames_bankright [] =
{
{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 flyer_move_bankright = {FRAME_bankr01, FRAME_bankr07, flyer_frames_bankright, NULL};
mframe_t flyer_frames_bankleft [] =
{
{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 flyer_move_bankleft = {FRAME_bankl01, FRAME_bankl07, flyer_frames_bankleft, NULL};
void flyer_fire (edict_t *self, int flash_number)
{
vec3_t start;
vec3_t forward, right;
vec3_t end;
vec3_t dir;
int effect;
if ((self->s.frame == FRAME_attak204) || (self->s.frame == FRAME_attak207) || (self->s.frame == FRAME_attak210))
effect = EF_HYPERBLASTER;
else
effect = 0;
AngleVectors (self->s.angles, forward, right, NULL);
G_ProjectSource (self->s.origin, monster_flash_offset[flash_number], forward, right, start);
VectorCopy (self->enemy->s.origin, end);
end[2] += self->enemy->viewheight;
VectorSubtract (end, start, dir);
monster_fire_blaster (self, start, dir, 1, 1000, flash_number, effect);
}
void flyer_fireleft (edict_t *self)
{
flyer_fire (self, MZ2_FLYER_BLASTER_1);
}
void flyer_fireright (edict_t *self)
{
flyer_fire (self, MZ2_FLYER_BLASTER_2);
}
mframe_t flyer_frames_attack2 [] =
{
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, -10, flyer_fireleft}, // left gun
{ai_charge, -10, flyer_fireright}, // right gun
{ai_charge, -10, flyer_fireleft}, // left gun
{ai_charge, -10, flyer_fireright}, // right gun
{ai_charge, -10, flyer_fireleft}, // left gun
{ai_charge, -10, flyer_fireright}, // right gun
{ai_charge, -10, flyer_fireleft}, // left gun
{ai_charge, -10, flyer_fireright}, // right gun
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}
};
mmove_t flyer_move_attack2 = {FRAME_attak201, FRAME_attak217, flyer_frames_attack2, flyer_run};
void flyer_slash_left (edict_t *self)
{
vec3_t aim;
VectorSet (aim, MELEE_DISTANCE, self->mins[0], 0);
fire_hit (self, aim, 5, 0);
gi.sound (self, CHAN_WEAPON, sound_slash, 1, ATTN_NORM, 0);
}
void flyer_slash_right (edict_t *self)
{
vec3_t aim;
VectorSet (aim, MELEE_DISTANCE, self->maxs[0], 0);
fire_hit (self, aim, 5, 0);
gi.sound (self, CHAN_WEAPON, sound_slash, 1, ATTN_NORM, 0);
}
mframe_t flyer_frames_start_melee [] =
{
{ai_charge, 0, flyer_pop_blades},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}
};
mmove_t flyer_move_start_melee = {FRAME_attak101, FRAME_attak106, flyer_frames_start_melee, flyer_loop_melee};
mframe_t flyer_frames_end_melee [] =
{
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL}
};
mmove_t flyer_move_end_melee = {FRAME_attak119, FRAME_attak121, flyer_frames_end_melee, flyer_run};
mframe_t flyer_frames_loop_melee [] =
{
{ai_charge, 0, NULL}, // Loop Start
{ai_charge, 0, NULL},
{ai_charge, 0, flyer_slash_left}, // Left Wing Strike
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, flyer_slash_right}, // Right Wing Strike
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL},
{ai_charge, 0, NULL} // Loop Ends
};
mmove_t flyer_move_loop_melee = {FRAME_attak107, FRAME_attak118, flyer_frames_loop_melee, flyer_check_melee};
void flyer_loop_melee (edict_t *self)
{
/* if (random() <= 0.5)
self->monsterinfo.currentmove = &flyer_move_attack1;
else */
self->monsterinfo.currentmove = &flyer_move_loop_melee;
}
void flyer_attack (edict_t *self)
{
/* if (random() <= 0.5)
self->monsterinfo.currentmove = &flyer_move_attack1;
else */
self->monsterinfo.currentmove = &flyer_move_attack2;
}
void flyer_setstart (edict_t *self)
{
nextmove = ACTION_run;
self->monsterinfo.currentmove = &flyer_move_start;
}
void flyer_nextmove (edict_t *self)
{
if (nextmove == ACTION_attack1)
self->monsterinfo.currentmove = &flyer_move_start_melee;
else if (nextmove == ACTION_attack2)
self->monsterinfo.currentmove = &flyer_move_attack2;
else if (nextmove == ACTION_run)
self->monsterinfo.currentmove = &flyer_move_run;
}
void flyer_melee (edict_t *self)
{
// flyer.nextmove = ACTION_attack1;
// self->monsterinfo.currentmove = &flyer_move_stop;
self->monsterinfo.currentmove = &flyer_move_start_melee;
}
void flyer_check_melee(edict_t *self)
{
if (range (self, self->enemy) == RANGE_MELEE)
if (random() <= 0.8)
self->monsterinfo.currentmove = &flyer_move_loop_melee;
else
self->monsterinfo.currentmove = &flyer_move_end_melee;
else
self->monsterinfo.currentmove = &flyer_move_end_melee;
}
void flyer_pain (edict_t *self, edict_t *other, float kick, int damage)
{
int n;
if (self->health < (self->max_health / 2))
self->s.skinnum = 1;
if (level.time < self->pain_debounce_time)
return;
self->pain_debounce_time = level.time + 3;
if (skill->value == 3)
return; // no pain anims in nightmare
n = rand() % 3;
if (n == 0)
{
gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
self->monsterinfo.currentmove = &flyer_move_pain1;
}
else if (n == 1)
{
gi.sound (self, CHAN_VOICE, sound_pain2, 1, ATTN_NORM, 0);
self->monsterinfo.currentmove = &flyer_move_pain2;
}
else
{
gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
self->monsterinfo.currentmove = &flyer_move_pain3;
}
}
void flyer_die(edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
gi.sound (self, CHAN_VOICE, sound_die, 1, ATTN_NORM, 0);
BecomeExplosion1(self);
}
/*QUAKED monster_flyer (1 .5 0) (-16 -16 -24) (16 16 32) Ambush Trigger_Spawn Sight
*/
void SP_monster_flyer (edict_t *self)
{
if (deathmatch->value)
{
G_FreeEdict (self);
return;
}
// fix a map bug in jail5.bsp
if (!Q_stricmp(level.mapname, "jail5") && (self->s.origin[2] == -104))
{
self->targetname = self->target;
self->target = NULL;
}
sound_sight = gi.soundindex ("flyer/flysght1.wav");
sound_idle = gi.soundindex ("flyer/flysrch1.wav");
sound_pain1 = gi.soundindex ("flyer/flypain1.wav");
sound_pain2 = gi.soundindex ("flyer/flypain2.wav");
sound_slash = gi.soundindex ("flyer/flyatck2.wav");
sound_sproing = gi.soundindex ("flyer/flyatck1.wav");
sound_die = gi.soundindex ("flyer/flydeth1.wav");
gi.soundindex ("flyer/flyatck3.wav");
self->s.modelindex = gi.modelindex ("models/monsters/flyer/tris.md2");
VectorSet (self->mins, -16, -16, -24);
VectorSet (self->maxs, 16, 16, 32);
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
self->s.sound = gi.soundindex ("flyer/flyidle1.wav");
self->health = 50;
self->mass = 50;
self->pain = flyer_pain;
self->die = flyer_die;
self->monsterinfo.stand = flyer_stand;
self->monsterinfo.walk = flyer_walk;
self->monsterinfo.run = flyer_run;
self->monsterinfo.attack = flyer_attack;
self->monsterinfo.melee = flyer_melee;
self->monsterinfo.sight = flyer_sight;
self->monsterinfo.idle = flyer_idle;
gi.linkentity (self);
self->monsterinfo.currentmove = &flyer_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
flymonster_start (self);
}
| 412 | 0.796965 | 1 | 0.796965 | game-dev | MEDIA | 0.68327 | game-dev | 0.736626 | 1 | 0.736626 |
R2NorthstarTools/VTOL | 2,046 | VTOL_2.0.0/Scripts/Titanfall2_Requisite/PilotData/Normal Pilot/AWall/AWall.cs | using System;
namespace Titanfall2_SkinTool.Titanfall2.PilotData.Normal_Pilot.AWall
{
class AWall
{
//A盾铁驭
public string Seek { get; private set; }
public string Length { get; private set; }
public string SeekLength { get; private set; }
public AWall(String PilotPart, int imagecheck)
{
String str = PilotPart.Substring(1, PilotPart.Length - 5);
if (str.Contains("fbody"))
{
Part.fbody fb = new Part.fbody(str, imagecheck);
Seek = fb.Seek;
Length = fb.Length;
SeekLength = fb.SeekLength;
}
else if (str.Contains("gauntlet"))
{
Part.gauntlet ga = new Part.gauntlet(str, imagecheck);
Seek = ga.Seek;
Length = ga.Length;
SeekLength = ga.SeekLength;
}
else if (str.Contains("mbody"))
{
Part.mbody mb = new Part.mbody(str, imagecheck);
Seek = mb.Seek;
Length = mb.Length;
SeekLength = mb.SeekLength;
}
else if (str.Contains("gear"))
{
Part.gear g = new Part.gear(str, imagecheck);
Seek = g.Seek;
Length = g.Length;
SeekLength = g.SeekLength;
}
else if (str.Contains("jumpkit"))
{
Part.jumpkit j = new Part.jumpkit(str, imagecheck);
Seek = j.Seek;
Length = j.Length;
SeekLength = j.SeekLength;
}
else if (str.Contains("helmet"))
{
Part.helmet he = new Part.helmet(str, imagecheck);
Seek = he.Seek;
Length = he.Length;
SeekLength = he.SeekLength;
}
else
{
throw new Exception("BUG!" + "\n" + "In Pilot Part.");
}
}
}
}
| 412 | 0.608597 | 1 | 0.608597 | game-dev | MEDIA | 0.602777 | game-dev | 0.739049 | 1 | 0.739049 |
lua9520/source-engine-2018-cstrike15_src | 3,819 | vgui2/dme_controls/AttributeTextPanel.cpp | //====== Copyright 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeTextPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "tier1/KeyValues.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "movieobjects/dmechannel.h"
#include "dme_controls/inotifyui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// CAttributeTextPanel constructor
//-----------------------------------------------------------------------------
CAttributeTextPanel::CAttributeTextPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info ), m_pData( 0 ), m_bShowMemoryUsage( info.m_bShowMemoryUsage )
{
m_pData = new CAttributeTextEntry( this, "AttributeValue" );
m_pData->SetEnabled( !HasFlag( READONLY ) && FindChannelTargetingAttribute( GetAttribute() ) == NULL );
m_pData->AddActionSignalTarget(this);
SetAllowKeyBindingChainToParent( false );
}
void CAttributeTextPanel::SetFont( HFont font )
{
BaseClass::SetFont( font );
m_pData->SetFont( font );
}
//-----------------------------------------------------------------------------
// Returns the text type
//-----------------------------------------------------------------------------
const char *CAttributeTextPanel::GetTextType()
{
// If a specific text type is specified, then filter if it doesn't match
CDmeEditorAttributeInfo *pInfo = GetEditorInfo();
const char *pTextType = pInfo ? pInfo->GetValueString( "texttype" ) : NULL;
return pTextType ? pTextType : "";
}
void CAttributeTextPanel::Apply()
{
char txt[ 256 ];
m_pData->GetText( txt, sizeof( txt ) );
// Apply means we no longer look blue
SetDirty( false );
if ( GetAttributeType( ) == AT_UNKNOWN )
{
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( "" );
return;
}
char curvalue[ 256 ];
GetAttributeValueAsString( curvalue, sizeof( curvalue ) );
// Only if differnt
if ( Q_strcmp( curvalue, txt ) )
{
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValueFromString( txt );
}
}
vgui::Panel *CAttributeTextPanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pData );
}
void CAttributeTextPanel::Refresh()
{
char buf[ 512 ];
if ( IsArrayType( GetAttributeType() ) )
{
int count = GetAttributeArrayCount();
if ( m_bShowMemoryUsage )
{
CDmAttribute *pAttr = GetPanelElement()->GetAttribute( GetAttributeName() );
Q_snprintf( buf, sizeof( buf ), "%d %s (%.3fMB)", count, (count == 1) ? "item" : "items", pAttr->EstimateMemoryUsage( TD_DEEP ) / float( 1 << 20 ) );
}
else
{
Q_snprintf( buf, sizeof( buf ), "%d %s", count, (count == 1) ? "item" : "items" );
}
m_pData->SetText( buf );
m_pData->SetEnabled(false);
}
else if ( GetAttributeType() == AT_ELEMENT )
{
m_pData->SetText( "" );
}
else
{
GetAttributeValueAsString( buf, sizeof( buf ) );
// This is a hack because VMatrix has \n characters in the text and the TextEntry field doesn't show them.
if ( GetAttributeType() == AT_VMATRIX )
{
// Replace \n with ' '
char *p = buf;
while ( *p )
{
if ( *p == '\n' )
*p = ' ';
++p;
}
}
m_pData->SetText( buf );
m_pData->SetEnabled( !HasFlag( READONLY ) && FindChannelTargetingAttribute( GetAttribute() ) == NULL );
}
}
void CAttributeTextPanel::PostConstructor()
{
Refresh();
}
| 412 | 0.973896 | 1 | 0.973896 | game-dev | MEDIA | 0.462734 | game-dev,desktop-app | 0.969389 | 1 | 0.969389 |
markostanimirovic/juliette | 1,951 | projects/juliette/src/lib/store.ts | import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import { Handler, Selector } from './models';
import { log } from './log';
import { deepFreeze } from './helpers';
export class Store<T> {
private readonly state: BehaviorSubject<T>;
private readonly handlers = new Subject<Handler<any, any>>();
readonly state$: Observable<T>;
readonly handlers$ = this.handlers.asObservable();
constructor(initialState: T, private readonly devMode: boolean) {
if (devMode) deepFreeze(initialState);
this.state = new BehaviorSubject(initialState);
this.state$ = this.state.asObservable();
}
dispatch(handler: Handler<any, any>): void {
if (handler.reducer && handler.featureKey) {
const currentState = this.state.value[handler.featureKey as keyof T];
if (this.devMode) deepFreeze(currentState);
this.state.next({
...this.state.value,
[handler.featureKey]: handler.reducer(currentState, handler.payload),
});
}
this.handlers.next(handler);
}
select<K extends keyof T>(key: K): Observable<T[K]>;
select<R>(selector: Selector<T, R>): Observable<R>;
select<K extends keyof T, R>(keyOrSelector: K | Selector<T, R>): Observable<T[K] | R>;
select<K extends keyof T, R>(keyOrSelector: K | Selector<T, R>): Observable<T[K] | R> {
const mapFn =
typeof keyOrSelector === 'function' ? keyOrSelector : (state: T) => state[keyOrSelector];
return this.state$.pipe(map<T, T[K] | R>(mapFn), distinctUntilChanged());
}
addFeatureState(featureKey: keyof T, initialState: T[keyof T]): void {
if (this.devMode) deepFreeze(initialState);
this.state.next({ ...this.state.value, [featureKey]: initialState });
}
}
export const createStore = <T>(initialState: T, devMode = false): Store<T> => {
const store = new Store(initialState, devMode);
if (devMode) log(store);
return store;
};
| 412 | 0.932362 | 1 | 0.932362 | game-dev | MEDIA | 0.536571 | game-dev | 0.904764 | 1 | 0.904764 |
Citadel-Station-13/Citadel-Station-13 | 6,833 | code/modules/surgery/robot_healing.dm | //Almost copypaste of tend wounds, with some changes
/datum/surgery/robot_healing
name = "Repair Robotic Limbs"
desc = "A surgical procedure that provides repairs and maintenance to robotic limbs. Is slightly more efficient when the patient is severely damaged."
replaced_by = /datum/surgery
steps = list(/datum/surgery_step/mechanic_open,
/datum/surgery_step/pry_off_plating,
/datum/surgery_step/cut_wires,
/datum/surgery_step/robot_heal,
/datum/surgery_step/mechanic_close)
target_mobtypes = list(/mob/living/carbon/human, /mob/living/carbon/monkey)
possible_locs = list(BODY_ZONE_CHEST)
requires_bodypart_type = 0 //You can do this on anyone, but it won't really be useful on people without augments.
ignore_clothes = TRUE
var/healing_step_type
var/antispam = FALSE
/datum/surgery/robot_healing/basic
name = "Repair Robotic Limbs (Basic)"
replaced_by = /datum/surgery/robot_healing/upgraded
healing_step_type = /datum/surgery_step/robot_heal/basic
desc = "A surgical procedure that provides basic repairs and maintenance to a patient's robotic limbs. Heals slightly more when the patient is severely injured."
/datum/surgery/robot_healing/upgraded
name = "Repair Robotic Limbs (Adv.)"
requires_tech = TRUE
replaced_by = /datum/surgery/robot_healing/upgraded/femto
healing_step_type = /datum/surgery_step/robot_heal/upgraded
desc = "A surgical procedure that provides advanced repairs and maintenance to a patient's robotic limbs. Heals more when the patient is severely injured."
/datum/surgery/robot_healing/upgraded/femto
name = "Repair Robotic Limbs (Exp.)"
requires_tech = TRUE
replaced_by = null // as good as it gets
healing_step_type = /datum/surgery_step/robot_heal/upgraded/femto
desc = "A surgical procedure that provides experimental repairs and maintenance to a patient's robotic limbs. Heals considerably more when the patient is severely injured."
/datum/surgery/robot_healing/New(surgery_target, surgery_location, surgery_bodypart)
..()
if(healing_step_type)
steps = list(/datum/surgery_step/mechanic_open,
/datum/surgery_step/pry_off_plating,
/datum/surgery_step/cut_wires,
healing_step_type,
/datum/surgery_step/mechanic_close)
/datum/surgery_step/robot_heal
name = "repair body (welder/cable)"
implements = list(TOOL_WELDER = 100, /obj/item/stack/cable_coil = 100)
repeatable = TRUE
time = 15
var/healsbrute = FALSE
var/healsburn = FALSE
var/brutehealing = 0
var/burnhealing = 0
var/missinghpbonus = 0 //heals an extra point of damage per X missing damage of type (burn damage for burn healing, brute for brute). Smaller Number = More Healing!
/datum/surgery_step/robot_heal/tool_check(mob/user, obj/item/tool)
if(implement_type == TOOL_WELDER && !tool.tool_use_check(user, 1))
return FALSE
return TRUE
/datum/surgery/robot_healing/can_start(mob/user, mob/living/carbon/target, obj/item/tool) // hey delta? why is the check for this all the way down here
for(var/obj/item/bodypart/B in target.bodyparts)
if(B.is_robotic_limb())
return ..()
/datum/surgery_step/robot_heal/preop(mob/user, mob/living/carbon/target, target_zone, obj/item/tool, datum/surgery/surgery)
var/woundtype
if(implement_type == TOOL_WELDER)
healsbrute = TRUE
healsburn = FALSE
woundtype = "dents"
else
healsbrute = FALSE
healsburn = TRUE
woundtype = "wiring"
if(istype(surgery,/datum/surgery/robot_healing))
var/datum/surgery/robot_healing/the_surgery = surgery
if(!the_surgery.antispam)
display_results(user, target, "<span class='notice'>You attempt to fix some of [target]'s [woundtype].</span>",
"<span class='notice'>[user] attempts to fix some of [target]'s [woundtype].</span>",
"<span class='notice'>[user] attempts to fix some of [target]'s [woundtype].</span>")
/datum/surgery_step/robot_heal/initiate(mob/user, mob/living/carbon/target, target_zone, obj/item/tool, datum/surgery/surgery, try_to_fail = FALSE)
if(..())
while((healsbrute && target.getBruteLoss() && tool.tool_use_check(user,1)) || (healsburn && target.getFireLoss() && tool))
if(!..())
break
/datum/surgery_step/robot_heal/success(mob/user, mob/living/carbon/target, target_zone, obj/item/tool, datum/surgery/surgery)
var/umsg = "You succeed in fixing some of [target]'s damage" //no period, add initial space to "addons"
var/tmsg = "[user] fixes some of [target]'s damage" //see above
var/urhealedamt_brute = 0
if(healsbrute)
urhealedamt_brute = brutehealing
tool.use_tool(target, user, 0, volume=50, amount=1)
var/urhealedamt_burn = 0
if(healsburn)
urhealedamt_burn = burnhealing
if(tool)
tool.use(1)
if(missinghpbonus)
if(target.stat != DEAD)
urhealedamt_brute += round((target.getBruteLoss()/ missinghpbonus),0.1)
urhealedamt_burn += round((target.getFireLoss()/ missinghpbonus),0.1)
else //less healing bonus for the dead since they're expected to have lots of damage to begin with (to make TW into defib not TOO simple)
urhealedamt_brute += round((target.getBruteLoss()/ (missinghpbonus*5)),0.1)
urhealedamt_burn += round((target.getFireLoss()/ (missinghpbonus*5)),0.1)
if(!get_location_accessible(target, target_zone))
urhealedamt_brute *= 0.55
urhealedamt_burn *= 0.55
umsg += " as best as you can while they have clothing on"
tmsg += " as best as they can while [target] has clothing on"
target.heal_bodypart_damage(urhealedamt_brute,urhealedamt_burn, only_organic = FALSE, only_robotic = TRUE)
display_results(user, target, "<span class='notice'>[umsg].</span>",
"[tmsg].",
"[tmsg].")
if(istype(surgery, /datum/surgery/robot_healing))
var/datum/surgery/robot_healing/the_surgery = surgery
the_surgery.antispam = TRUE
return TRUE
/datum/surgery_step/robot_heal/failure(mob/user, mob/living/carbon/target, target_zone, obj/item/tool, datum/surgery/surgery)
display_results(user, target, "<span class='warning'>You screwed up!</span>",
"<span class='warning'>[user] screws up!</span>",
"<span class='notice'>[user] fixes some of [target]'s damage.</span>", TRUE)
var/urdamageamt_brute = 0
if(healsbrute)
urdamageamt_brute = brutehealing * 0.8
var/urdamageamt_burn = 0
if(healsburn)
urdamageamt_burn = burnhealing * 0.8
if(missinghpbonus)
urdamageamt_brute += round((target.getBruteLoss()/ (missinghpbonus*2)),0.1)
urdamageamt_burn += round((target.getFireLoss()/ (missinghpbonus*2)),0.1)
target.take_bodypart_damage(urdamageamt_brute, urdamageamt_burn)
return FALSE
/***************************STEPS***************************/
/datum/surgery_step/robot_heal/basic
name = "repair damage"
brutehealing = 10
burnhealing = 10
missinghpbonus = 15
/datum/surgery_step/robot_heal/upgraded
brutehealing = 10
burnhealing = 10
missinghpbonus = 10
/datum/surgery_step/robot_heal/upgraded/femto
brutehealing = 10
burnhealing = 10
missinghpbonus = 5
| 412 | 0.511144 | 1 | 0.511144 | game-dev | MEDIA | 0.700962 | game-dev | 0.730828 | 1 | 0.730828 |
MassiveHeights/Black | 1,069 | src/assets/XMLAsset.js | import { Asset } from "./Asset";
import { XHRAssetLoader } from "./loaders/XHRAssetLoader";
import { AssetType } from "./AssetType";
import { LoaderType } from "./LoaderType";
/**
* Single JSON file asset class responsible for loading json file.
*
* @cat assets
* @extends Asset
*/
export class XMLAsset extends Asset {
/**
* Creates new JSONAsset instance.
*
* @param {string} name The name of asset.
* @param {string} url URL to the json file.
* @return {void}
*/
constructor(name, url) {
super(AssetType.XML, name);
/**
* @private
* @type {string}
*/
this.mUrl = url;
/**
* @private
* @type {XHRAssetLoader|null}
*/
this.mXHR = null;
}
/**
* @inheritDoc
*/
onLoaderRequested(factory) {
this.mXHR = factory.get(LoaderType.XHR, this.mUrl);
this.mXHR.mimeType = 'text/xml';
this.addLoader(this.mXHR);
}
/**
* @inheritDoc
*/
onAllLoaded() {
super.ready(new DOMParser().parseFromString(/** @type {string} */(this.mXHR.data), 'text/xml'));
}
}
| 412 | 0.825311 | 1 | 0.825311 | game-dev | MEDIA | 0.224421 | game-dev | 0.708154 | 1 | 0.708154 |
pixelcmtd/CXClient | 4,673 | src/minecraft/net/minecraft/world/WorldManager.java | package net.minecraft.world;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S25PacketBlockBreakAnim;
import net.minecraft.network.play.server.S28PacketEffect;
import net.minecraft.network.play.server.S29PacketSoundEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
public class WorldManager implements IWorldAccess
{
/** Reference to the MinecraftServer object. */
private MinecraftServer mcServer;
/** The WorldServer object. */
private WorldServer theWorldServer;
public WorldManager(MinecraftServer p_i1517_1_, WorldServer p_i1517_2_)
{
this.mcServer = p_i1517_1_;
this.theWorldServer = p_i1517_2_;
}
public void spawnParticle(int particleID, boolean ignoreRange, double xCoord, double yCoord, double zCoord, double xOffset, double yOffset, double zOffset, int... p_180442_15_)
{
}
/**
* Called on all IWorldAccesses when an entity is created or loaded. On client worlds, starts downloading any
* necessary textures. On server worlds, adds the entity to the entity tracker.
*/
public void onEntityAdded(Entity entityIn)
{
this.theWorldServer.getEntityTracker().trackEntity(entityIn);
}
/**
* Called on all IWorldAccesses when an entity is unloaded or destroyed. On client worlds, releases any downloaded
* textures. On server worlds, removes the entity from the entity tracker.
*/
public void onEntityRemoved(Entity entityIn)
{
this.theWorldServer.getEntityTracker().untrackEntity(entityIn);
this.theWorldServer.getScoreboard().func_181140_a(entityIn);
}
/**
* Plays the specified sound. Arg: soundName, x, y, z, volume, pitch
*/
public void playSound(String soundName, double x, double y, double z, float volume, float pitch)
{
this.mcServer.getConfigurationManager().sendToAllNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(soundName, x, y, z, volume, pitch));
}
/**
* Plays sound to all near players except the player reference given
*/
public void playSoundToNearExcept(EntityPlayer except, String soundName, double x, double y, double z, float volume, float pitch)
{
this.mcServer.getConfigurationManager().sendToAllNearExcept(except, x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(soundName, x, y, z, volume, pitch));
}
/**
* On the client, re-renders all blocks in this range, inclusive. On the server, does nothing. Args: min x, min y,
* min z, max x, max y, max z
*/
public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2)
{
}
public void markBlockForUpdate(BlockPos pos)
{
this.theWorldServer.getPlayerManager().markBlockForUpdate(pos);
}
public void notifyLightSet(BlockPos pos)
{
}
public void playRecord(String recordName, BlockPos blockPosIn)
{
}
public void playAuxSFX(EntityPlayer player, int sfxType, BlockPos blockPosIn, int p_180439_4_)
{
this.mcServer.getConfigurationManager().sendToAllNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.theWorldServer.provider.getDimensionId(), new S28PacketEffect(sfxType, blockPosIn, p_180439_4_, false));
}
public void broadcastSound(int p_180440_1_, BlockPos p_180440_2_, int p_180440_3_)
{
this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S28PacketEffect(p_180440_1_, p_180440_2_, p_180440_3_, true));
}
public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress)
{
for (EntityPlayerMP entityplayermp : this.mcServer.getConfigurationManager().func_181057_v())
{
if (entityplayermp != null && entityplayermp.worldObj == this.theWorldServer && entityplayermp.getEntityId() != breakerId)
{
double d0 = (double)pos.getX() - entityplayermp.posX;
double d1 = (double)pos.getY() - entityplayermp.posY;
double d2 = (double)pos.getZ() - entityplayermp.posZ;
if (d0 * d0 + d1 * d1 + d2 * d2 < 1024.0D)
{
entityplayermp.playerNetServerHandler.sendPacket(new S25PacketBlockBreakAnim(breakerId, pos, progress));
}
}
}
}
}
| 412 | 0.911141 | 1 | 0.911141 | game-dev | MEDIA | 0.922843 | game-dev | 0.838857 | 1 | 0.838857 |
anotak/doombuilderx | 2,209 | Source/Core/Config/SectorEffectInfo.cs |
#region ================== Copyright (c) 2007 Pascal vd Heiden
/*
* Copyright (c) 2007 Pascal vd Heiden, www.codeimp.com
* This program is released under GNU General Public License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#endregion
#region ================== Namespaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using CodeImp.DoomBuilder.IO;
using CodeImp.DoomBuilder.Data;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using CodeImp.DoomBuilder.Map;
#endregion
namespace CodeImp.DoomBuilder.Config
{
public class SectorEffectInfo : INumberedTitle, IComparable<SectorEffectInfo>
{
#region ================== Constants
#endregion
#region ================== Variables
// Properties
private int index;
private string title;
private bool isknown;
private bool isgeneralized;
#endregion
#region ================== Properties
public int Index { get { return index; } }
public string Title { get { return title; } }
public bool IsGeneralized { get { return isgeneralized; } }
public bool IsKnown { get { return isknown; } }
public bool IsNull { get { return (index == 0); } }
#endregion
#region ================== Constructor / Disposer
// Constructor
internal SectorEffectInfo(int index, string title, bool isknown, bool isgeneralized)
{
// Initialize
this.index = index;
this.title = title;
this.isknown = isknown;
this.isgeneralized = isgeneralized;
// We have no destructor
GC.SuppressFinalize(this);
}
#endregion
#region ================== Methods
// This presents the item as string
public override string ToString()
{
return index + " - " + title;
}
// This compares against another action info
public int CompareTo(SectorEffectInfo other)
{
if(this.index < other.index) return -1;
else if(this.index > other.index) return 1;
else return 0;
}
#endregion
}
}
| 412 | 0.821177 | 1 | 0.821177 | game-dev | MEDIA | 0.602357 | game-dev | 0.588028 | 1 | 0.588028 |
moai/moai-dev | 2,141 | src/moai-box2d/MOAIBox2DArbiter.h | // Copyright (c) 2010-2017 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#ifndef MOAIBOX2DARBITER_H
#define MOAIBOX2DARBITER_H
#include <Box2D/Box2D.h>
// Forward declaration
class MOAIBox2DWorld;
//================================================================//
// MOAIBox2DArbiter
//================================================================//
/** @lua MOAIBox2DArbiter
@text Box2D Arbiter.
@flag BEGIN
@flag END
@flag POST_SOLVE
@flag PRE_SOLVE
@flag ALL
*/
class MOAIBox2DArbiter :
public virtual MOAILuaObject,
public b2ContactListener {
private:
b2Contact* mContact;
const b2ContactImpulse* mImpulse;
b2Vec2 mContactNormal;
b2Vec2 mContactPoints [ 2 ];
u32 mTotalPoints;
float mNormalImpulse;
float mTangentImpulse;
bool mContactDirty;
/* For reference to get the unitsToMeters value */
const MOAIBox2DWorld* mWorld;
//----------------------------------------------------------------//
static int _getContactNormal ( lua_State* L );
static int _getContactPoints ( lua_State* L );
static int _getNormalImpulse ( lua_State* L );
static int _getTangentImpulse ( lua_State* L );
static int _setContactEnabled ( lua_State* L );
//----------------------------------------------------------------//
void AffirmContactData ();
void BeginContact ( b2Contact* contact );
void EndContact ( b2Contact* contact );
void PostSolve ( b2Contact* contact, const b2ContactImpulse* impulse );
void PreSolve ( b2Contact* contact, const b2Manifold* oldManifold );
//----------------------------------------------------------------//
float GetUnitsToMeters ( ) const;
public:
DECL_LUA_FACTORY ( MOAIBox2DArbiter )
enum {
BEGIN = 0x00000001,
END = 0x00000002,
POST_SOLVE = 0x00000004,
PRE_SOLVE = 0x00000008,
ALL = 0x0000000f,
};
//----------------------------------------------------------------//
MOAIBox2DArbiter ();
MOAIBox2DArbiter ( const MOAIBox2DWorld &world );
~MOAIBox2DArbiter ();
void RegisterLuaClass ( MOAILuaState& state );
void RegisterLuaFuncs ( MOAILuaState& state );
};
#endif
| 412 | 0.879214 | 1 | 0.879214 | game-dev | MEDIA | 0.899139 | game-dev | 0.95446 | 1 | 0.95446 |
amethyst/rustrogueliketutorial | 1,600 | chapter-73-systems/src/systems/ai/flee_ai_system.rs | use specs::prelude::*;
use crate::{MyTurn, WantsToFlee, Position, Map, ApplyMove};
pub struct FleeAI {}
impl<'a> System<'a> for FleeAI {
#[allow(clippy::type_complexity)]
type SystemData = (
WriteStorage<'a, MyTurn>,
WriteStorage<'a, WantsToFlee>,
WriteStorage<'a, Position>,
WriteExpect<'a, Map>,
Entities<'a>,
WriteStorage<'a, ApplyMove>
);
fn run(&mut self, data : Self::SystemData) {
let (mut turns, mut want_flee, positions, mut map,
entities, mut apply_move) = data;
let mut turn_done : Vec<Entity> = Vec::new();
for (entity, pos, flee, _myturn) in
(&entities, &positions, &want_flee, &turns).join()
{
turn_done.push(entity);
let my_idx = map.xy_idx(pos.x, pos.y);
map.populate_blocked();
let flee_map = rltk::DijkstraMap::new(map.width as usize, map.height as usize, &flee.indices, &*map, 100.0);
let flee_target = rltk::DijkstraMap::find_highest_exit(&flee_map, my_idx, &*map);
if let Some(flee_target) = flee_target {
if !crate::spatial::is_blocked(flee_target as usize) {
apply_move.insert(entity, ApplyMove{ dest_idx : flee_target }).expect("Unable to insert");
turn_done.push(entity);
}
}
}
want_flee.clear();
// Remove turn marker for those that are done
for done in turn_done.iter() {
turns.remove(*done);
}
}
}
| 412 | 0.787057 | 1 | 0.787057 | game-dev | MEDIA | 0.666562 | game-dev | 0.982986 | 1 | 0.982986 |
IppClub/Dora-SSR | 11,660 | Source/3rdParty/playrho/d2/Body.cpp | /*
* Original work Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
* Modified work Copyright (c) 2023 Louis Langholtz https://github.com/louis-langholtz/PlayRho
*
* 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 <algorithm> // for std::find
#include <cassert> // for assert
#include "playrho/Math.hpp" // for Cross, etc
#include "playrho/Templates.hpp"
#include "playrho/d2/Body.hpp"
namespace playrho::d2 {
Body::FlagsType Body::GetFlags(BodyType type) noexcept
{
auto flags = FlagsType{0};
switch (type) {
case BodyType::Dynamic:
flags |= (e_velocityFlag | e_accelerationFlag);
break;
case BodyType::Kinematic:
flags |= (e_impenetrableFlag | e_velocityFlag);
break;
case BodyType::Static:
flags |= (e_impenetrableFlag);
break;
}
return flags;
}
Body::FlagsType Body::GetFlags(const BodyConf& bd) noexcept
{
// @invariant Only bodies that allow sleeping, can be put to sleep.
// @invariant Only "speedable" bodies can be awake.
// @invariant Only "speedable" bodies can have non-zero velocities.
// @invariant Only "accelerable" bodies can have non-zero accelerations.
// @invariant Only "accelerable" bodies can have non-zero "under-active" times.
auto flags = GetFlags(bd.type);
if (bd.bullet) {
flags |= e_impenetrableFlag;
}
if (bd.fixedRotation) {
flags |= e_fixedRotationFlag;
}
if (bd.allowSleep) {
flags |= e_autoSleepFlag;
}
if (bd.awake) {
if ((flags & e_velocityFlag) != 0) {
flags |= e_awakeFlag;
}
}
else {
if (!bd.allowSleep && ((flags & e_velocityFlag) != 0)) {
flags |= e_awakeFlag;
}
}
if (bd.enabled) {
flags |= e_enabledFlag;
}
if (bd.massDataDirty &&
(!bd.shapes.empty() ||
(bd.invMass != BodyConf::DefaultInvMass) ||
(bd.invRotI != BodyConf::DefaultInvRotI))) {
flags |= e_massDataDirtyFlag;
}
return flags;
}
Body::Body(const BodyConf& bd)
: m_xf{GetTransform1(bd.sweep)},
m_sweep{bd.sweep},
m_flags{GetFlags(bd)},
m_invMass{(bd.type == playrho::BodyType::Dynamic)
? bd.invMass : NonNegative<InvMass>{}},
m_invRotI{(bd.type == playrho::BodyType::Dynamic)
? bd.invRotI : NonNegative<InvRotInertia>{}},
m_linearDamping{bd.linearDamping},
m_angularDamping{bd.angularDamping},
m_shapes(bd.shapes.begin(), bd.shapes.end())
{
assert(IsValid(bd.sweep));
assert(IsValid(bd.linearVelocity));
assert(IsValid(bd.angularVelocity));
assert(IsValid(m_xf));
SetVelocity(Velocity{bd.linearVelocity, bd.angularVelocity});
SetAcceleration(bd.linearAcceleration, bd.angularAcceleration);
SetUnderActiveTime(bd.underActiveTime);
}
BodyType Body::GetType() const noexcept
{
switch (m_flags & (e_accelerationFlag | e_velocityFlag)) {
case e_velocityFlag | e_accelerationFlag:
return BodyType::Dynamic;
case e_velocityFlag:
return BodyType::Kinematic;
default:
break; // handle case 0 this way so compiler doesn't warn of no default handling.
}
return BodyType::Static;
}
void Body::SetType(BodyType value) noexcept
{
m_flags &= ~(e_impenetrableFlag | e_velocityFlag | e_accelerationFlag);
m_flags |= GetFlags(value);
switch (value) {
case BodyType::Dynamic: // IsSpeedable() && IsAccelerable()
SetAwakeFlag();
break;
case BodyType::Kinematic: // IsSpeedable() && !IsAccelerable()
SetAwakeFlag();
m_linearAcceleration = LinearAcceleration2{};
m_angularAcceleration = AngularAcceleration{};
SetInvMassData(InvMass{}, InvRotInertia{});
break;
case BodyType::Static: // !IsSpeedable() && !IsAccelerable()
UnsetAwakeFlag();
m_linearVelocity = LinearVelocity2{};
m_angularVelocity = 0_rpm;
m_sweep.pos0 = m_sweep.pos1;
m_linearAcceleration = LinearAcceleration2{};
m_angularAcceleration = AngularAcceleration{};
SetInvMassData(InvMass{}, InvRotInertia{});
break;
}
m_underActiveTime = 0_s;
}
void Body::SetSleepingAllowed(bool flag) noexcept
{
if (flag) {
m_flags |= e_autoSleepFlag;
}
else if ((m_flags & Body::e_velocityFlag) != 0) {
m_flags &= ~e_autoSleepFlag;
SetAwakeFlag();
m_underActiveTime = 0_s;
}
}
void Body::SetAwake() noexcept
{
// Ignore this request unless this body is speedable so as to maintain the body's invariant
// that only "speedable" bodies can be awake.
if ((m_flags & Body::e_velocityFlag) != 0) {
SetAwakeFlag();
m_underActiveTime = 0_s;
}
}
void Body::UnsetAwake() noexcept
{
if (((m_flags & Body::e_velocityFlag) == 0) ||
((m_flags & Body::e_autoSleepFlag) != 0)) {
UnsetAwakeFlag();
m_underActiveTime = 0_s;
m_linearVelocity = LinearVelocity2{};
m_angularVelocity = 0_rpm;
}
}
void Body::SetVelocity(const Velocity& value) noexcept
{
if (value != Velocity{}) {
if ((m_flags & Body::e_velocityFlag) == 0) {
return;
}
SetAwakeFlag();
m_underActiveTime = 0_s;
}
JustSetVelocity(value);
}
void Body::JustSetVelocity(const Velocity& value) noexcept
{
assert(((m_flags & Body::e_velocityFlag) != 0) || (value == Velocity{}));
m_linearVelocity = value.linear;
m_angularVelocity = value.angular;
}
void Body::SetAcceleration(const LinearAcceleration2& linear, AngularAcceleration angular) noexcept
{
assert(IsValid(linear));
assert(IsValid(angular));
if ((m_linearAcceleration == linear) && (m_angularAcceleration == angular)) {
// no change, bail...
return;
}
if ((m_flags & Body::e_accelerationFlag) == 0) {
if ((linear != LinearAcceleration2{}) || (angular != AngularAcceleration{})) {
// non-accelerable bodies can only be set to zero acceleration, bail...
return;
}
}
else {
// If the new linear or angular accelerations are higher, or the linear acceleration
// changes direction, or the sign of the new angular acceleration is different, then
// also set the awake flag and reset the under active time.
if ((m_angularAcceleration < angular) ||
(GetMagnitudeSquared(m_linearAcceleration) < GetMagnitudeSquared(linear)) ||
(playrho::GetAngle(m_linearAcceleration) != playrho::GetAngle(linear)) ||
(signbit(m_angularAcceleration) != signbit(angular))) {
// Increasing accel or changing direction of accel, awake & reset time.
SetAwakeFlag();
m_underActiveTime = 0_s;
}
}
m_linearAcceleration = linear;
m_angularAcceleration = angular;
}
void Body::SetFixedRotation(bool flag)
{
if (flag) {
m_flags |= e_fixedRotationFlag;
}
else {
m_flags &= ~e_fixedRotationFlag;
}
m_angularVelocity = 0_rpm;
}
Body& Body::Attach(ShapeID shapeId)
{
assert(shapeId != InvalidShapeID);
m_shapes.push_back(shapeId);
m_flags |= e_massDataDirtyFlag;
return *this;
}
bool Body::Detach(ShapeID shapeId)
{
const auto endIt = end(m_shapes);
const auto it = find(begin(m_shapes), endIt, shapeId);
if (it != endIt) {
m_shapes.erase(it);
m_flags |= e_massDataDirtyFlag;
return true;
}
return false;
}
// Free functions...
void SetTransformation(Body& body, const Transformation& value) noexcept
{
SetSweep(body, Sweep{Position{value.p, GetAngle(value.q)}, GetSweep(body).localCenter});
}
void SetLocation(Body& body, const Length2& value)
{
SetTransformation(body, Transformation{value, GetTransformation(body).q});
}
Angle GetAngle(const Body& body) noexcept
{
return GetSweep(body).pos1.angular;
}
void SetAngle(Body& body, Angle value)
{
SetSweep(body, Sweep{Position{GetSweep(body).pos1.linear, value}, GetLocalCenter(body)});
}
Velocity GetVelocity(const Body& body, Time h) noexcept
{
// Integrate velocity and apply damping.
auto velocity = body.GetVelocity();
if (IsAccelerable(body)) {
// Integrate velocities.
velocity.linear += h * body.GetLinearAcceleration();
velocity.angular += h * body.GetAngularAcceleration();
// Apply damping.
// Ordinary differential equation: dv/dt + c * v = 0
// Solution: v(t) = v0 * exp(-c * t)
// Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v *
// exp(-c * dt) v2 = exp(-c * dt) * v1 Pade approximation (see
// https://en.wikipedia.org/wiki/Pad%C3%A9_approximant ): v2 = v1 * 1 / (1 + c * dt)
velocity.linear /= Real{1 + h * body.GetLinearDamping()};
velocity.angular /= Real{1 + h * body.GetAngularDamping()};
}
return velocity;
}
void ApplyLinearImpulse(Body& body, const Momentum2& impulse, const Length2& point) noexcept
{
auto velocity = body.GetVelocity();
velocity.linear += body.GetInvMass() * impulse;
const auto invRotI = body.GetInvRotInertia();
const auto dp = point - GetWorldCenter(body);
velocity.angular += AngularVelocity{invRotI * Cross(dp, impulse) / Radian};
body.SetVelocity(velocity);
}
void ApplyAngularImpulse(Body& body, AngularMomentum impulse) noexcept
{
auto velocity = body.GetVelocity();
const auto invRotI = body.GetInvRotInertia();
velocity.angular += AngularVelocity{invRotI * impulse};
body.SetVelocity(velocity);
}
bool operator==(const Body& lhs, const Body& rhs)
{
return GetTransformation(lhs) == GetTransformation(rhs) && //
GetSweep(lhs) == GetSweep(rhs) && //
IsDestroyed(lhs) == IsDestroyed(rhs) && //
IsAwake(lhs) == IsAwake(rhs) && //
IsSleepingAllowed(lhs) == IsSleepingAllowed(rhs) && //
IsImpenetrable(lhs) == IsImpenetrable(rhs) && //
IsFixedRotation(lhs) == IsFixedRotation(rhs) && //
IsEnabled(lhs) == IsEnabled(rhs) && //
IsSpeedable(lhs) == IsSpeedable(rhs) && //
IsAccelerable(lhs) == IsAccelerable(rhs) && //
IsMassDataDirty(lhs) == IsMassDataDirty(rhs) && //
GetVelocity(lhs) == GetVelocity(rhs) && //
GetAcceleration(lhs) == GetAcceleration(rhs) && //
GetInvMass(lhs) == GetInvMass(rhs) && //
GetInvRotInertia(lhs) == GetInvRotInertia(rhs) && //
GetLinearDamping(lhs) == GetLinearDamping(rhs) && //
GetAngularDamping(lhs) == GetAngularDamping(rhs) && //
GetUnderActiveTime(lhs) == GetUnderActiveTime(rhs) && //
GetShapes(lhs) == GetShapes(rhs);
}
} // namespace playrho::d2
| 412 | 0.823801 | 1 | 0.823801 | game-dev | MEDIA | 0.955474 | game-dev | 0.850573 | 1 | 0.850573 |
Linaro/vixl | 61,387 | test/aarch32/traces/assembler-cond-rd-rn-rm-smulwb-a32.h | // Copyright 2015, VIXL authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ARM Limited nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---------------------------------------------------------------------
// This file is auto generated using tools/generate_simulator_traces.py.
//
// PLEASE DO NOT EDIT.
// ---------------------------------------------------------------------
#ifndef VIXL_ASSEMBLER_COND_RD_RN_RM_SMULWB_A32_H_
#define VIXL_ASSEMBLER_COND_RD_RN_RM_SMULWB_A32_H_
const byte kInstruction_smulwb_hi_r1_r9_r5[] = {
0xa9, 0x05, 0x21, 0x81 // smulwb hi r1 r9 r5
};
const byte kInstruction_smulwb_pl_r8_r6_r2[] = {
0xa6, 0x02, 0x28, 0x51 // smulwb pl r8 r6 r2
};
const byte kInstruction_smulwb_hi_r5_r8_r2[] = {
0xa8, 0x02, 0x25, 0x81 // smulwb hi r5 r8 r2
};
const byte kInstruction_smulwb_vc_r9_r2_r7[] = {
0xa2, 0x07, 0x29, 0x71 // smulwb vc r9 r2 r7
};
const byte kInstruction_smulwb_lt_r4_r6_r3[] = {
0xa6, 0x03, 0x24, 0xb1 // smulwb lt r4 r6 r3
};
const byte kInstruction_smulwb_le_r11_r6_r2[] = {
0xa6, 0x02, 0x2b, 0xd1 // smulwb le r11 r6 r2
};
const byte kInstruction_smulwb_cc_r8_r14_r4[] = {
0xae, 0x04, 0x28, 0x31 // smulwb cc r8 r14 r4
};
const byte kInstruction_smulwb_le_r5_r14_r6[] = {
0xae, 0x06, 0x25, 0xd1 // smulwb le r5 r14 r6
};
const byte kInstruction_smulwb_lt_r6_r1_r0[] = {
0xa1, 0x00, 0x26, 0xb1 // smulwb lt r6 r1 r0
};
const byte kInstruction_smulwb_lt_r5_r0_r9[] = {
0xa0, 0x09, 0x25, 0xb1 // smulwb lt r5 r0 r9
};
const byte kInstruction_smulwb_le_r8_r12_r7[] = {
0xac, 0x07, 0x28, 0xd1 // smulwb le r8 r12 r7
};
const byte kInstruction_smulwb_eq_r7_r14_r6[] = {
0xae, 0x06, 0x27, 0x01 // smulwb eq r7 r14 r6
};
const byte kInstruction_smulwb_cs_r7_r4_r6[] = {
0xa4, 0x06, 0x27, 0x21 // smulwb cs r7 r4 r6
};
const byte kInstruction_smulwb_gt_r9_r6_r9[] = {
0xa6, 0x09, 0x29, 0xc1 // smulwb gt r9 r6 r9
};
const byte kInstruction_smulwb_ne_r13_r9_r1[] = {
0xa9, 0x01, 0x2d, 0x11 // smulwb ne r13 r9 r1
};
const byte kInstruction_smulwb_ge_r13_r1_r13[] = {
0xa1, 0x0d, 0x2d, 0xa1 // smulwb ge r13 r1 r13
};
const byte kInstruction_smulwb_ls_r8_r10_r2[] = {
0xaa, 0x02, 0x28, 0x91 // smulwb ls r8 r10 r2
};
const byte kInstruction_smulwb_hi_r0_r13_r5[] = {
0xad, 0x05, 0x20, 0x81 // smulwb hi r0 r13 r5
};
const byte kInstruction_smulwb_pl_r13_r7_r8[] = {
0xa7, 0x08, 0x2d, 0x51 // smulwb pl r13 r7 r8
};
const byte kInstruction_smulwb_ge_r4_r13_r11[] = {
0xad, 0x0b, 0x24, 0xa1 // smulwb ge r4 r13 r11
};
const byte kInstruction_smulwb_cs_r5_r10_r5[] = {
0xaa, 0x05, 0x25, 0x21 // smulwb cs r5 r10 r5
};
const byte kInstruction_smulwb_cs_r5_r4_r3[] = {
0xa4, 0x03, 0x25, 0x21 // smulwb cs r5 r4 r3
};
const byte kInstruction_smulwb_ls_r6_r14_r8[] = {
0xae, 0x08, 0x26, 0x91 // smulwb ls r6 r14 r8
};
const byte kInstruction_smulwb_vs_r3_r8_r6[] = {
0xa8, 0x06, 0x23, 0x61 // smulwb vs r3 r8 r6
};
const byte kInstruction_smulwb_vc_r7_r12_r3[] = {
0xac, 0x03, 0x27, 0x71 // smulwb vc r7 r12 r3
};
const byte kInstruction_smulwb_ge_r1_r4_r1[] = {
0xa4, 0x01, 0x21, 0xa1 // smulwb ge r1 r4 r1
};
const byte kInstruction_smulwb_cc_r4_r7_r10[] = {
0xa7, 0x0a, 0x24, 0x31 // smulwb cc r4 r7 r10
};
const byte kInstruction_smulwb_cc_r2_r0_r13[] = {
0xa0, 0x0d, 0x22, 0x31 // smulwb cc r2 r0 r13
};
const byte kInstruction_smulwb_vs_r9_r6_r8[] = {
0xa6, 0x08, 0x29, 0x61 // smulwb vs r9 r6 r8
};
const byte kInstruction_smulwb_cs_r14_r11_r13[] = {
0xab, 0x0d, 0x2e, 0x21 // smulwb cs r14 r11 r13
};
const byte kInstruction_smulwb_pl_r5_r8_r4[] = {
0xa8, 0x04, 0x25, 0x51 // smulwb pl r5 r8 r4
};
const byte kInstruction_smulwb_pl_r2_r3_r7[] = {
0xa3, 0x07, 0x22, 0x51 // smulwb pl r2 r3 r7
};
const byte kInstruction_smulwb_cs_r7_r12_r14[] = {
0xac, 0x0e, 0x27, 0x21 // smulwb cs r7 r12 r14
};
const byte kInstruction_smulwb_hi_r6_r6_r1[] = {
0xa6, 0x01, 0x26, 0x81 // smulwb hi r6 r6 r1
};
const byte kInstruction_smulwb_cc_r6_r9_r6[] = {
0xa9, 0x06, 0x26, 0x31 // smulwb cc r6 r9 r6
};
const byte kInstruction_smulwb_ne_r12_r12_r0[] = {
0xac, 0x00, 0x2c, 0x11 // smulwb ne r12 r12 r0
};
const byte kInstruction_smulwb_cc_r9_r3_r8[] = {
0xa3, 0x08, 0x29, 0x31 // smulwb cc r9 r3 r8
};
const byte kInstruction_smulwb_mi_r13_r6_r1[] = {
0xa6, 0x01, 0x2d, 0x41 // smulwb mi r13 r6 r1
};
const byte kInstruction_smulwb_lt_r4_r8_r6[] = {
0xa8, 0x06, 0x24, 0xb1 // smulwb lt r4 r8 r6
};
const byte kInstruction_smulwb_hi_r11_r5_r9[] = {
0xa5, 0x09, 0x2b, 0x81 // smulwb hi r11 r5 r9
};
const byte kInstruction_smulwb_cc_r6_r10_r6[] = {
0xaa, 0x06, 0x26, 0x31 // smulwb cc r6 r10 r6
};
const byte kInstruction_smulwb_eq_r10_r10_r5[] = {
0xaa, 0x05, 0x2a, 0x01 // smulwb eq r10 r10 r5
};
const byte kInstruction_smulwb_al_r5_r4_r11[] = {
0xa4, 0x0b, 0x25, 0xe1 // smulwb al r5 r4 r11
};
const byte kInstruction_smulwb_pl_r11_r11_r2[] = {
0xab, 0x02, 0x2b, 0x51 // smulwb pl r11 r11 r2
};
const byte kInstruction_smulwb_ls_r6_r14_r12[] = {
0xae, 0x0c, 0x26, 0x91 // smulwb ls r6 r14 r12
};
const byte kInstruction_smulwb_vc_r7_r7_r2[] = {
0xa7, 0x02, 0x27, 0x71 // smulwb vc r7 r7 r2
};
const byte kInstruction_smulwb_eq_r10_r8_r4[] = {
0xa8, 0x04, 0x2a, 0x01 // smulwb eq r10 r8 r4
};
const byte kInstruction_smulwb_al_r14_r7_r2[] = {
0xa7, 0x02, 0x2e, 0xe1 // smulwb al r14 r7 r2
};
const byte kInstruction_smulwb_cs_r3_r11_r10[] = {
0xab, 0x0a, 0x23, 0x21 // smulwb cs r3 r11 r10
};
const byte kInstruction_smulwb_ls_r11_r4_r0[] = {
0xa4, 0x00, 0x2b, 0x91 // smulwb ls r11 r4 r0
};
const byte kInstruction_smulwb_hi_r11_r8_r9[] = {
0xa8, 0x09, 0x2b, 0x81 // smulwb hi r11 r8 r9
};
const byte kInstruction_smulwb_vs_r2_r14_r13[] = {
0xae, 0x0d, 0x22, 0x61 // smulwb vs r2 r14 r13
};
const byte kInstruction_smulwb_al_r1_r13_r9[] = {
0xad, 0x09, 0x21, 0xe1 // smulwb al r1 r13 r9
};
const byte kInstruction_smulwb_eq_r3_r9_r13[] = {
0xa9, 0x0d, 0x23, 0x01 // smulwb eq r3 r9 r13
};
const byte kInstruction_smulwb_ge_r10_r3_r13[] = {
0xa3, 0x0d, 0x2a, 0xa1 // smulwb ge r10 r3 r13
};
const byte kInstruction_smulwb_pl_r8_r5_r10[] = {
0xa5, 0x0a, 0x28, 0x51 // smulwb pl r8 r5 r10
};
const byte kInstruction_smulwb_vc_r8_r11_r6[] = {
0xab, 0x06, 0x28, 0x71 // smulwb vc r8 r11 r6
};
const byte kInstruction_smulwb_eq_r0_r0_r5[] = {
0xa0, 0x05, 0x20, 0x01 // smulwb eq r0 r0 r5
};
const byte kInstruction_smulwb_ne_r6_r5_r8[] = {
0xa5, 0x08, 0x26, 0x11 // smulwb ne r6 r5 r8
};
const byte kInstruction_smulwb_hi_r5_r13_r3[] = {
0xad, 0x03, 0x25, 0x81 // smulwb hi r5 r13 r3
};
const byte kInstruction_smulwb_ne_r11_r14_r14[] = {
0xae, 0x0e, 0x2b, 0x11 // smulwb ne r11 r14 r14
};
const byte kInstruction_smulwb_mi_r1_r0_r6[] = {
0xa0, 0x06, 0x21, 0x41 // smulwb mi r1 r0 r6
};
const byte kInstruction_smulwb_le_r14_r8_r2[] = {
0xa8, 0x02, 0x2e, 0xd1 // smulwb le r14 r8 r2
};
const byte kInstruction_smulwb_eq_r9_r6_r5[] = {
0xa6, 0x05, 0x29, 0x01 // smulwb eq r9 r6 r5
};
const byte kInstruction_smulwb_eq_r11_r0_r13[] = {
0xa0, 0x0d, 0x2b, 0x01 // smulwb eq r11 r0 r13
};
const byte kInstruction_smulwb_pl_r4_r5_r14[] = {
0xa5, 0x0e, 0x24, 0x51 // smulwb pl r4 r5 r14
};
const byte kInstruction_smulwb_cs_r13_r5_r13[] = {
0xa5, 0x0d, 0x2d, 0x21 // smulwb cs r13 r5 r13
};
const byte kInstruction_smulwb_mi_r0_r13_r8[] = {
0xad, 0x08, 0x20, 0x41 // smulwb mi r0 r13 r8
};
const byte kInstruction_smulwb_lt_r2_r13_r3[] = {
0xad, 0x03, 0x22, 0xb1 // smulwb lt r2 r13 r3
};
const byte kInstruction_smulwb_ls_r8_r1_r11[] = {
0xa1, 0x0b, 0x28, 0x91 // smulwb ls r8 r1 r11
};
const byte kInstruction_smulwb_vc_r14_r11_r8[] = {
0xab, 0x08, 0x2e, 0x71 // smulwb vc r14 r11 r8
};
const byte kInstruction_smulwb_lt_r4_r13_r12[] = {
0xad, 0x0c, 0x24, 0xb1 // smulwb lt r4 r13 r12
};
const byte kInstruction_smulwb_eq_r2_r1_r14[] = {
0xa1, 0x0e, 0x22, 0x01 // smulwb eq r2 r1 r14
};
const byte kInstruction_smulwb_eq_r9_r4_r14[] = {
0xa4, 0x0e, 0x29, 0x01 // smulwb eq r9 r4 r14
};
const byte kInstruction_smulwb_hi_r10_r6_r13[] = {
0xa6, 0x0d, 0x2a, 0x81 // smulwb hi r10 r6 r13
};
const byte kInstruction_smulwb_ge_r12_r9_r4[] = {
0xa9, 0x04, 0x2c, 0xa1 // smulwb ge r12 r9 r4
};
const byte kInstruction_smulwb_le_r9_r11_r14[] = {
0xab, 0x0e, 0x29, 0xd1 // smulwb le r9 r11 r14
};
const byte kInstruction_smulwb_ls_r0_r9_r5[] = {
0xa9, 0x05, 0x20, 0x91 // smulwb ls r0 r9 r5
};
const byte kInstruction_smulwb_mi_r2_r3_r8[] = {
0xa3, 0x08, 0x22, 0x41 // smulwb mi r2 r3 r8
};
const byte kInstruction_smulwb_ne_r14_r10_r14[] = {
0xaa, 0x0e, 0x2e, 0x11 // smulwb ne r14 r10 r14
};
const byte kInstruction_smulwb_eq_r6_r2_r10[] = {
0xa2, 0x0a, 0x26, 0x01 // smulwb eq r6 r2 r10
};
const byte kInstruction_smulwb_lt_r11_r0_r12[] = {
0xa0, 0x0c, 0x2b, 0xb1 // smulwb lt r11 r0 r12
};
const byte kInstruction_smulwb_ne_r1_r12_r10[] = {
0xac, 0x0a, 0x21, 0x11 // smulwb ne r1 r12 r10
};
const byte kInstruction_smulwb_cc_r1_r0_r2[] = {
0xa0, 0x02, 0x21, 0x31 // smulwb cc r1 r0 r2
};
const byte kInstruction_smulwb_al_r5_r5_r7[] = {
0xa5, 0x07, 0x25, 0xe1 // smulwb al r5 r5 r7
};
const byte kInstruction_smulwb_hi_r7_r13_r1[] = {
0xad, 0x01, 0x27, 0x81 // smulwb hi r7 r13 r1
};
const byte kInstruction_smulwb_cs_r4_r4_r9[] = {
0xa4, 0x09, 0x24, 0x21 // smulwb cs r4 r4 r9
};
const byte kInstruction_smulwb_eq_r14_r4_r14[] = {
0xa4, 0x0e, 0x2e, 0x01 // smulwb eq r14 r4 r14
};
const byte kInstruction_smulwb_vs_r10_r5_r14[] = {
0xa5, 0x0e, 0x2a, 0x61 // smulwb vs r10 r5 r14
};
const byte kInstruction_smulwb_gt_r4_r3_r11[] = {
0xa3, 0x0b, 0x24, 0xc1 // smulwb gt r4 r3 r11
};
const byte kInstruction_smulwb_ne_r14_r10_r12[] = {
0xaa, 0x0c, 0x2e, 0x11 // smulwb ne r14 r10 r12
};
const byte kInstruction_smulwb_vs_r2_r11_r0[] = {
0xab, 0x00, 0x22, 0x61 // smulwb vs r2 r11 r0
};
const byte kInstruction_smulwb_ge_r5_r12_r7[] = {
0xac, 0x07, 0x25, 0xa1 // smulwb ge r5 r12 r7
};
const byte kInstruction_smulwb_mi_r7_r14_r6[] = {
0xae, 0x06, 0x27, 0x41 // smulwb mi r7 r14 r6
};
const byte kInstruction_smulwb_gt_r8_r3_r8[] = {
0xa3, 0x08, 0x28, 0xc1 // smulwb gt r8 r3 r8
};
const byte kInstruction_smulwb_hi_r9_r14_r3[] = {
0xae, 0x03, 0x29, 0x81 // smulwb hi r9 r14 r3
};
const byte kInstruction_smulwb_vc_r2_r11_r2[] = {
0xab, 0x02, 0x22, 0x71 // smulwb vc r2 r11 r2
};
const byte kInstruction_smulwb_hi_r11_r7_r12[] = {
0xa7, 0x0c, 0x2b, 0x81 // smulwb hi r11 r7 r12
};
const byte kInstruction_smulwb_cs_r6_r4_r11[] = {
0xa4, 0x0b, 0x26, 0x21 // smulwb cs r6 r4 r11
};
const byte kInstruction_smulwb_cs_r12_r5_r9[] = {
0xa5, 0x09, 0x2c, 0x21 // smulwb cs r12 r5 r9
};
const byte kInstruction_smulwb_ls_r5_r10_r5[] = {
0xaa, 0x05, 0x25, 0x91 // smulwb ls r5 r10 r5
};
const byte kInstruction_smulwb_ls_r0_r9_r13[] = {
0xa9, 0x0d, 0x20, 0x91 // smulwb ls r0 r9 r13
};
const byte kInstruction_smulwb_lt_r3_r3_r5[] = {
0xa3, 0x05, 0x23, 0xb1 // smulwb lt r3 r3 r5
};
const byte kInstruction_smulwb_mi_r0_r12_r8[] = {
0xac, 0x08, 0x20, 0x41 // smulwb mi r0 r12 r8
};
const byte kInstruction_smulwb_pl_r3_r12_r12[] = {
0xac, 0x0c, 0x23, 0x51 // smulwb pl r3 r12 r12
};
const byte kInstruction_smulwb_eq_r8_r12_r5[] = {
0xac, 0x05, 0x28, 0x01 // smulwb eq r8 r12 r5
};
const byte kInstruction_smulwb_cc_r7_r8_r1[] = {
0xa8, 0x01, 0x27, 0x31 // smulwb cc r7 r8 r1
};
const byte kInstruction_smulwb_hi_r2_r13_r10[] = {
0xad, 0x0a, 0x22, 0x81 // smulwb hi r2 r13 r10
};
const byte kInstruction_smulwb_al_r7_r10_r10[] = {
0xaa, 0x0a, 0x27, 0xe1 // smulwb al r7 r10 r10
};
const byte kInstruction_smulwb_vc_r1_r12_r2[] = {
0xac, 0x02, 0x21, 0x71 // smulwb vc r1 r12 r2
};
const byte kInstruction_smulwb_cc_r8_r5_r8[] = {
0xa5, 0x08, 0x28, 0x31 // smulwb cc r8 r5 r8
};
const byte kInstruction_smulwb_ls_r3_r7_r9[] = {
0xa7, 0x09, 0x23, 0x91 // smulwb ls r3 r7 r9
};
const byte kInstruction_smulwb_al_r8_r10_r8[] = {
0xaa, 0x08, 0x28, 0xe1 // smulwb al r8 r10 r8
};
const byte kInstruction_smulwb_lt_r4_r12_r10[] = {
0xac, 0x0a, 0x24, 0xb1 // smulwb lt r4 r12 r10
};
const byte kInstruction_smulwb_ge_r10_r5_r11[] = {
0xa5, 0x0b, 0x2a, 0xa1 // smulwb ge r10 r5 r11
};
const byte kInstruction_smulwb_ls_r3_r14_r4[] = {
0xae, 0x04, 0x23, 0x91 // smulwb ls r3 r14 r4
};
const byte kInstruction_smulwb_hi_r3_r6_r12[] = {
0xa6, 0x0c, 0x23, 0x81 // smulwb hi r3 r6 r12
};
const byte kInstruction_smulwb_hi_r6_r0_r4[] = {
0xa0, 0x04, 0x26, 0x81 // smulwb hi r6 r0 r4
};
const byte kInstruction_smulwb_al_r11_r6_r0[] = {
0xa6, 0x00, 0x2b, 0xe1 // smulwb al r11 r6 r0
};
const byte kInstruction_smulwb_mi_r3_r1_r9[] = {
0xa1, 0x09, 0x23, 0x41 // smulwb mi r3 r1 r9
};
const byte kInstruction_smulwb_mi_r12_r13_r0[] = {
0xad, 0x00, 0x2c, 0x41 // smulwb mi r12 r13 r0
};
const byte kInstruction_smulwb_le_r1_r2_r5[] = {
0xa2, 0x05, 0x21, 0xd1 // smulwb le r1 r2 r5
};
const byte kInstruction_smulwb_hi_r4_r3_r14[] = {
0xa3, 0x0e, 0x24, 0x81 // smulwb hi r4 r3 r14
};
const byte kInstruction_smulwb_eq_r6_r11_r11[] = {
0xab, 0x0b, 0x26, 0x01 // smulwb eq r6 r11 r11
};
const byte kInstruction_smulwb_cc_r14_r11_r14[] = {
0xab, 0x0e, 0x2e, 0x31 // smulwb cc r14 r11 r14
};
const byte kInstruction_smulwb_hi_r4_r10_r0[] = {
0xaa, 0x00, 0x24, 0x81 // smulwb hi r4 r10 r0
};
const byte kInstruction_smulwb_cc_r7_r11_r1[] = {
0xab, 0x01, 0x27, 0x31 // smulwb cc r7 r11 r1
};
const byte kInstruction_smulwb_mi_r14_r6_r10[] = {
0xa6, 0x0a, 0x2e, 0x41 // smulwb mi r14 r6 r10
};
const byte kInstruction_smulwb_eq_r2_r0_r11[] = {
0xa0, 0x0b, 0x22, 0x01 // smulwb eq r2 r0 r11
};
const byte kInstruction_smulwb_mi_r13_r5_r12[] = {
0xa5, 0x0c, 0x2d, 0x41 // smulwb mi r13 r5 r12
};
const byte kInstruction_smulwb_eq_r2_r12_r5[] = {
0xac, 0x05, 0x22, 0x01 // smulwb eq r2 r12 r5
};
const byte kInstruction_smulwb_le_r12_r0_r2[] = {
0xa0, 0x02, 0x2c, 0xd1 // smulwb le r12 r0 r2
};
const byte kInstruction_smulwb_vc_r10_r10_r9[] = {
0xaa, 0x09, 0x2a, 0x71 // smulwb vc r10 r10 r9
};
const byte kInstruction_smulwb_ls_r11_r11_r8[] = {
0xab, 0x08, 0x2b, 0x91 // smulwb ls r11 r11 r8
};
const byte kInstruction_smulwb_hi_r10_r11_r9[] = {
0xab, 0x09, 0x2a, 0x81 // smulwb hi r10 r11 r9
};
const byte kInstruction_smulwb_vs_r7_r12_r14[] = {
0xac, 0x0e, 0x27, 0x61 // smulwb vs r7 r12 r14
};
const byte kInstruction_smulwb_gt_r11_r14_r12[] = {
0xae, 0x0c, 0x2b, 0xc1 // smulwb gt r11 r14 r12
};
const byte kInstruction_smulwb_vs_r0_r12_r8[] = {
0xac, 0x08, 0x20, 0x61 // smulwb vs r0 r12 r8
};
const byte kInstruction_smulwb_al_r0_r5_r7[] = {
0xa5, 0x07, 0x20, 0xe1 // smulwb al r0 r5 r7
};
const byte kInstruction_smulwb_hi_r5_r13_r8[] = {
0xad, 0x08, 0x25, 0x81 // smulwb hi r5 r13 r8
};
const byte kInstruction_smulwb_le_r9_r9_r7[] = {
0xa9, 0x07, 0x29, 0xd1 // smulwb le r9 r9 r7
};
const byte kInstruction_smulwb_cc_r4_r9_r5[] = {
0xa9, 0x05, 0x24, 0x31 // smulwb cc r4 r9 r5
};
const byte kInstruction_smulwb_vs_r8_r1_r3[] = {
0xa1, 0x03, 0x28, 0x61 // smulwb vs r8 r1 r3
};
const byte kInstruction_smulwb_cc_r0_r10_r12[] = {
0xaa, 0x0c, 0x20, 0x31 // smulwb cc r0 r10 r12
};
const byte kInstruction_smulwb_eq_r7_r14_r0[] = {
0xae, 0x00, 0x27, 0x01 // smulwb eq r7 r14 r0
};
const byte kInstruction_smulwb_vs_r12_r9_r11[] = {
0xa9, 0x0b, 0x2c, 0x61 // smulwb vs r12 r9 r11
};
const byte kInstruction_smulwb_gt_r5_r9_r11[] = {
0xa9, 0x0b, 0x25, 0xc1 // smulwb gt r5 r9 r11
};
const byte kInstruction_smulwb_cs_r14_r13_r7[] = {
0xad, 0x07, 0x2e, 0x21 // smulwb cs r14 r13 r7
};
const byte kInstruction_smulwb_mi_r11_r3_r10[] = {
0xa3, 0x0a, 0x2b, 0x41 // smulwb mi r11 r3 r10
};
const byte kInstruction_smulwb_hi_r11_r8_r12[] = {
0xa8, 0x0c, 0x2b, 0x81 // smulwb hi r11 r8 r12
};
const byte kInstruction_smulwb_cs_r3_r8_r13[] = {
0xa8, 0x0d, 0x23, 0x21 // smulwb cs r3 r8 r13
};
const byte kInstruction_smulwb_pl_r10_r12_r6[] = {
0xac, 0x06, 0x2a, 0x51 // smulwb pl r10 r12 r6
};
const byte kInstruction_smulwb_vc_r7_r3_r2[] = {
0xa3, 0x02, 0x27, 0x71 // smulwb vc r7 r3 r2
};
const byte kInstruction_smulwb_mi_r9_r0_r8[] = {
0xa0, 0x08, 0x29, 0x41 // smulwb mi r9 r0 r8
};
const byte kInstruction_smulwb_eq_r2_r13_r7[] = {
0xad, 0x07, 0x22, 0x01 // smulwb eq r2 r13 r7
};
const byte kInstruction_smulwb_ne_r2_r14_r0[] = {
0xae, 0x00, 0x22, 0x11 // smulwb ne r2 r14 r0
};
const byte kInstruction_smulwb_vs_r4_r10_r0[] = {
0xaa, 0x00, 0x24, 0x61 // smulwb vs r4 r10 r0
};
const byte kInstruction_smulwb_ls_r0_r2_r2[] = {
0xa2, 0x02, 0x20, 0x91 // smulwb ls r0 r2 r2
};
const byte kInstruction_smulwb_cc_r1_r6_r0[] = {
0xa6, 0x00, 0x21, 0x31 // smulwb cc r1 r6 r0
};
const byte kInstruction_smulwb_lt_r12_r0_r8[] = {
0xa0, 0x08, 0x2c, 0xb1 // smulwb lt r12 r0 r8
};
const byte kInstruction_smulwb_cc_r9_r3_r14[] = {
0xa3, 0x0e, 0x29, 0x31 // smulwb cc r9 r3 r14
};
const byte kInstruction_smulwb_vs_r7_r9_r1[] = {
0xa9, 0x01, 0x27, 0x61 // smulwb vs r7 r9 r1
};
const byte kInstruction_smulwb_eq_r11_r9_r14[] = {
0xa9, 0x0e, 0x2b, 0x01 // smulwb eq r11 r9 r14
};
const byte kInstruction_smulwb_pl_r6_r10_r4[] = {
0xaa, 0x04, 0x26, 0x51 // smulwb pl r6 r10 r4
};
const byte kInstruction_smulwb_ne_r8_r5_r6[] = {
0xa5, 0x06, 0x28, 0x11 // smulwb ne r8 r5 r6
};
const byte kInstruction_smulwb_cs_r0_r6_r2[] = {
0xa6, 0x02, 0x20, 0x21 // smulwb cs r0 r6 r2
};
const byte kInstruction_smulwb_eq_r11_r12_r4[] = {
0xac, 0x04, 0x2b, 0x01 // smulwb eq r11 r12 r4
};
const byte kInstruction_smulwb_lt_r14_r3_r14[] = {
0xa3, 0x0e, 0x2e, 0xb1 // smulwb lt r14 r3 r14
};
const byte kInstruction_smulwb_le_r7_r12_r14[] = {
0xac, 0x0e, 0x27, 0xd1 // smulwb le r7 r12 r14
};
const byte kInstruction_smulwb_hi_r2_r9_r9[] = {
0xa9, 0x09, 0x22, 0x81 // smulwb hi r2 r9 r9
};
const byte kInstruction_smulwb_ne_r8_r1_r0[] = {
0xa1, 0x00, 0x28, 0x11 // smulwb ne r8 r1 r0
};
const byte kInstruction_smulwb_cc_r5_r11_r2[] = {
0xab, 0x02, 0x25, 0x31 // smulwb cc r5 r11 r2
};
const byte kInstruction_smulwb_hi_r0_r1_r2[] = {
0xa1, 0x02, 0x20, 0x81 // smulwb hi r0 r1 r2
};
const byte kInstruction_smulwb_al_r4_r9_r4[] = {
0xa9, 0x04, 0x24, 0xe1 // smulwb al r4 r9 r4
};
const byte kInstruction_smulwb_cs_r12_r7_r14[] = {
0xa7, 0x0e, 0x2c, 0x21 // smulwb cs r12 r7 r14
};
const byte kInstruction_smulwb_cc_r4_r12_r10[] = {
0xac, 0x0a, 0x24, 0x31 // smulwb cc r4 r12 r10
};
const byte kInstruction_smulwb_al_r3_r5_r10[] = {
0xa5, 0x0a, 0x23, 0xe1 // smulwb al r3 r5 r10
};
const byte kInstruction_smulwb_mi_r5_r3_r7[] = {
0xa3, 0x07, 0x25, 0x41 // smulwb mi r5 r3 r7
};
const byte kInstruction_smulwb_ls_r10_r6_r2[] = {
0xa6, 0x02, 0x2a, 0x91 // smulwb ls r10 r6 r2
};
const byte kInstruction_smulwb_mi_r0_r12_r11[] = {
0xac, 0x0b, 0x20, 0x41 // smulwb mi r0 r12 r11
};
const byte kInstruction_smulwb_vc_r12_r5_r6[] = {
0xa5, 0x06, 0x2c, 0x71 // smulwb vc r12 r5 r6
};
const byte kInstruction_smulwb_cs_r3_r9_r4[] = {
0xa9, 0x04, 0x23, 0x21 // smulwb cs r3 r9 r4
};
const byte kInstruction_smulwb_ls_r4_r9_r11[] = {
0xa9, 0x0b, 0x24, 0x91 // smulwb ls r4 r9 r11
};
const byte kInstruction_smulwb_le_r14_r8_r13[] = {
0xa8, 0x0d, 0x2e, 0xd1 // smulwb le r14 r8 r13
};
const byte kInstruction_smulwb_gt_r4_r10_r8[] = {
0xaa, 0x08, 0x24, 0xc1 // smulwb gt r4 r10 r8
};
const byte kInstruction_smulwb_al_r6_r9_r9[] = {
0xa9, 0x09, 0x26, 0xe1 // smulwb al r6 r9 r9
};
const byte kInstruction_smulwb_ne_r8_r5_r12[] = {
0xa5, 0x0c, 0x28, 0x11 // smulwb ne r8 r5 r12
};
const byte kInstruction_smulwb_ne_r0_r4_r8[] = {
0xa4, 0x08, 0x20, 0x11 // smulwb ne r0 r4 r8
};
const byte kInstruction_smulwb_mi_r7_r13_r3[] = {
0xad, 0x03, 0x27, 0x41 // smulwb mi r7 r13 r3
};
const byte kInstruction_smulwb_cc_r11_r7_r0[] = {
0xa7, 0x00, 0x2b, 0x31 // smulwb cc r11 r7 r0
};
const byte kInstruction_smulwb_hi_r1_r0_r12[] = {
0xa0, 0x0c, 0x21, 0x81 // smulwb hi r1 r0 r12
};
const byte kInstruction_smulwb_lt_r8_r9_r3[] = {
0xa9, 0x03, 0x28, 0xb1 // smulwb lt r8 r9 r3
};
const byte kInstruction_smulwb_al_r0_r2_r1[] = {
0xa2, 0x01, 0x20, 0xe1 // smulwb al r0 r2 r1
};
const byte kInstruction_smulwb_vs_r4_r3_r14[] = {
0xa3, 0x0e, 0x24, 0x61 // smulwb vs r4 r3 r14
};
const byte kInstruction_smulwb_ge_r2_r11_r1[] = {
0xab, 0x01, 0x22, 0xa1 // smulwb ge r2 r11 r1
};
const byte kInstruction_smulwb_lt_r12_r9_r6[] = {
0xa9, 0x06, 0x2c, 0xb1 // smulwb lt r12 r9 r6
};
const byte kInstruction_smulwb_ls_r8_r2_r7[] = {
0xa2, 0x07, 0x28, 0x91 // smulwb ls r8 r2 r7
};
const byte kInstruction_smulwb_le_r8_r13_r3[] = {
0xad, 0x03, 0x28, 0xd1 // smulwb le r8 r13 r3
};
const byte kInstruction_smulwb_eq_r11_r13_r14[] = {
0xad, 0x0e, 0x2b, 0x01 // smulwb eq r11 r13 r14
};
const byte kInstruction_smulwb_lt_r1_r6_r13[] = {
0xa6, 0x0d, 0x21, 0xb1 // smulwb lt r1 r6 r13
};
const byte kInstruction_smulwb_cs_r3_r8_r11[] = {
0xa8, 0x0b, 0x23, 0x21 // smulwb cs r3 r8 r11
};
const byte kInstruction_smulwb_pl_r12_r5_r4[] = {
0xa5, 0x04, 0x2c, 0x51 // smulwb pl r12 r5 r4
};
const byte kInstruction_smulwb_eq_r8_r7_r2[] = {
0xa7, 0x02, 0x28, 0x01 // smulwb eq r8 r7 r2
};
const byte kInstruction_smulwb_ls_r2_r12_r2[] = {
0xac, 0x02, 0x22, 0x91 // smulwb ls r2 r12 r2
};
const byte kInstruction_smulwb_le_r14_r2_r3[] = {
0xa2, 0x03, 0x2e, 0xd1 // smulwb le r14 r2 r3
};
const byte kInstruction_smulwb_ge_r10_r11_r6[] = {
0xab, 0x06, 0x2a, 0xa1 // smulwb ge r10 r11 r6
};
const byte kInstruction_smulwb_hi_r0_r2_r2[] = {
0xa2, 0x02, 0x20, 0x81 // smulwb hi r0 r2 r2
};
const byte kInstruction_smulwb_ge_r2_r0_r2[] = {
0xa0, 0x02, 0x22, 0xa1 // smulwb ge r2 r0 r2
};
const byte kInstruction_smulwb_vs_r11_r14_r0[] = {
0xae, 0x00, 0x2b, 0x61 // smulwb vs r11 r14 r0
};
const byte kInstruction_smulwb_lt_r2_r0_r1[] = {
0xa0, 0x01, 0x22, 0xb1 // smulwb lt r2 r0 r1
};
const byte kInstruction_smulwb_cs_r2_r5_r11[] = {
0xa5, 0x0b, 0x22, 0x21 // smulwb cs r2 r5 r11
};
const byte kInstruction_smulwb_ls_r7_r14_r5[] = {
0xae, 0x05, 0x27, 0x91 // smulwb ls r7 r14 r5
};
const byte kInstruction_smulwb_pl_r0_r0_r3[] = {
0xa0, 0x03, 0x20, 0x51 // smulwb pl r0 r0 r3
};
const byte kInstruction_smulwb_ge_r6_r8_r8[] = {
0xa8, 0x08, 0x26, 0xa1 // smulwb ge r6 r8 r8
};
const byte kInstruction_smulwb_le_r11_r1_r10[] = {
0xa1, 0x0a, 0x2b, 0xd1 // smulwb le r11 r1 r10
};
const byte kInstruction_smulwb_vs_r5_r2_r7[] = {
0xa2, 0x07, 0x25, 0x61 // smulwb vs r5 r2 r7
};
const byte kInstruction_smulwb_ne_r4_r4_r8[] = {
0xa4, 0x08, 0x24, 0x11 // smulwb ne r4 r4 r8
};
const byte kInstruction_smulwb_cc_r9_r14_r13[] = {
0xae, 0x0d, 0x29, 0x31 // smulwb cc r9 r14 r13
};
const byte kInstruction_smulwb_hi_r14_r6_r3[] = {
0xa6, 0x03, 0x2e, 0x81 // smulwb hi r14 r6 r3
};
const byte kInstruction_smulwb_al_r0_r8_r0[] = {
0xa8, 0x00, 0x20, 0xe1 // smulwb al r0 r8 r0
};
const byte kInstruction_smulwb_lt_r6_r11_r1[] = {
0xab, 0x01, 0x26, 0xb1 // smulwb lt r6 r11 r1
};
const byte kInstruction_smulwb_ge_r7_r6_r12[] = {
0xa6, 0x0c, 0x27, 0xa1 // smulwb ge r7 r6 r12
};
const byte kInstruction_smulwb_cs_r4_r6_r14[] = {
0xa6, 0x0e, 0x24, 0x21 // smulwb cs r4 r6 r14
};
const byte kInstruction_smulwb_cs_r7_r6_r7[] = {
0xa6, 0x07, 0x27, 0x21 // smulwb cs r7 r6 r7
};
const byte kInstruction_smulwb_cs_r3_r7_r10[] = {
0xa7, 0x0a, 0x23, 0x21 // smulwb cs r3 r7 r10
};
const byte kInstruction_smulwb_ne_r0_r2_r1[] = {
0xa2, 0x01, 0x20, 0x11 // smulwb ne r0 r2 r1
};
const byte kInstruction_smulwb_vs_r9_r10_r13[] = {
0xaa, 0x0d, 0x29, 0x61 // smulwb vs r9 r10 r13
};
const byte kInstruction_smulwb_vc_r11_r14_r12[] = {
0xae, 0x0c, 0x2b, 0x71 // smulwb vc r11 r14 r12
};
const byte kInstruction_smulwb_ge_r14_r8_r7[] = {
0xa8, 0x07, 0x2e, 0xa1 // smulwb ge r14 r8 r7
};
const byte kInstruction_smulwb_lt_r13_r0_r11[] = {
0xa0, 0x0b, 0x2d, 0xb1 // smulwb lt r13 r0 r11
};
const byte kInstruction_smulwb_lt_r14_r13_r4[] = {
0xad, 0x04, 0x2e, 0xb1 // smulwb lt r14 r13 r4
};
const byte kInstruction_smulwb_al_r1_r10_r9[] = {
0xaa, 0x09, 0x21, 0xe1 // smulwb al r1 r10 r9
};
const byte kInstruction_smulwb_ge_r11_r14_r11[] = {
0xae, 0x0b, 0x2b, 0xa1 // smulwb ge r11 r14 r11
};
const byte kInstruction_smulwb_cs_r11_r4_r11[] = {
0xa4, 0x0b, 0x2b, 0x21 // smulwb cs r11 r4 r11
};
const byte kInstruction_smulwb_ge_r0_r14_r7[] = {
0xae, 0x07, 0x20, 0xa1 // smulwb ge r0 r14 r7
};
const byte kInstruction_smulwb_mi_r1_r2_r9[] = {
0xa2, 0x09, 0x21, 0x41 // smulwb mi r1 r2 r9
};
const byte kInstruction_smulwb_eq_r5_r12_r3[] = {
0xac, 0x03, 0x25, 0x01 // smulwb eq r5 r12 r3
};
const byte kInstruction_smulwb_ge_r1_r5_r12[] = {
0xa5, 0x0c, 0x21, 0xa1 // smulwb ge r1 r5 r12
};
const byte kInstruction_smulwb_lt_r10_r11_r4[] = {
0xab, 0x04, 0x2a, 0xb1 // smulwb lt r10 r11 r4
};
const byte kInstruction_smulwb_le_r1_r1_r5[] = {
0xa1, 0x05, 0x21, 0xd1 // smulwb le r1 r1 r5
};
const byte kInstruction_smulwb_al_r9_r1_r8[] = {
0xa1, 0x08, 0x29, 0xe1 // smulwb al r9 r1 r8
};
const byte kInstruction_smulwb_ne_r6_r8_r4[] = {
0xa8, 0x04, 0x26, 0x11 // smulwb ne r6 r8 r4
};
const byte kInstruction_smulwb_ge_r12_r2_r9[] = {
0xa2, 0x09, 0x2c, 0xa1 // smulwb ge r12 r2 r9
};
const byte kInstruction_smulwb_pl_r4_r3_r10[] = {
0xa3, 0x0a, 0x24, 0x51 // smulwb pl r4 r3 r10
};
const byte kInstruction_smulwb_eq_r14_r4_r11[] = {
0xa4, 0x0b, 0x2e, 0x01 // smulwb eq r14 r4 r11
};
const byte kInstruction_smulwb_cc_r9_r7_r6[] = {
0xa7, 0x06, 0x29, 0x31 // smulwb cc r9 r7 r6
};
const byte kInstruction_smulwb_ge_r12_r4_r5[] = {
0xa4, 0x05, 0x2c, 0xa1 // smulwb ge r12 r4 r5
};
const byte kInstruction_smulwb_hi_r2_r3_r4[] = {
0xa3, 0x04, 0x22, 0x81 // smulwb hi r2 r3 r4
};
const byte kInstruction_smulwb_cs_r0_r3_r1[] = {
0xa3, 0x01, 0x20, 0x21 // smulwb cs r0 r3 r1
};
const byte kInstruction_smulwb_hi_r6_r2_r8[] = {
0xa2, 0x08, 0x26, 0x81 // smulwb hi r6 r2 r8
};
const byte kInstruction_smulwb_cc_r3_r14_r13[] = {
0xae, 0x0d, 0x23, 0x31 // smulwb cc r3 r14 r13
};
const byte kInstruction_smulwb_gt_r11_r4_r7[] = {
0xa4, 0x07, 0x2b, 0xc1 // smulwb gt r11 r4 r7
};
const byte kInstruction_smulwb_hi_r5_r0_r12[] = {
0xa0, 0x0c, 0x25, 0x81 // smulwb hi r5 r0 r12
};
const byte kInstruction_smulwb_gt_r0_r14_r14[] = {
0xae, 0x0e, 0x20, 0xc1 // smulwb gt r0 r14 r14
};
const byte kInstruction_smulwb_hi_r9_r0_r10[] = {
0xa0, 0x0a, 0x29, 0x81 // smulwb hi r9 r0 r10
};
const byte kInstruction_smulwb_vc_r7_r11_r8[] = {
0xab, 0x08, 0x27, 0x71 // smulwb vc r7 r11 r8
};
const byte kInstruction_smulwb_pl_r11_r9_r6[] = {
0xa9, 0x06, 0x2b, 0x51 // smulwb pl r11 r9 r6
};
const byte kInstruction_smulwb_al_r3_r3_r7[] = {
0xa3, 0x07, 0x23, 0xe1 // smulwb al r3 r3 r7
};
const byte kInstruction_smulwb_mi_r5_r7_r9[] = {
0xa7, 0x09, 0x25, 0x41 // smulwb mi r5 r7 r9
};
const byte kInstruction_smulwb_cc_r11_r2_r4[] = {
0xa2, 0x04, 0x2b, 0x31 // smulwb cc r11 r2 r4
};
const byte kInstruction_smulwb_cc_r9_r13_r10[] = {
0xad, 0x0a, 0x29, 0x31 // smulwb cc r9 r13 r10
};
const byte kInstruction_smulwb_al_r5_r2_r6[] = {
0xa2, 0x06, 0x25, 0xe1 // smulwb al r5 r2 r6
};
const byte kInstruction_smulwb_ge_r9_r4_r6[] = {
0xa4, 0x06, 0x29, 0xa1 // smulwb ge r9 r4 r6
};
const byte kInstruction_smulwb_ls_r3_r3_r4[] = {
0xa3, 0x04, 0x23, 0x91 // smulwb ls r3 r3 r4
};
const byte kInstruction_smulwb_ge_r14_r1_r8[] = {
0xa1, 0x08, 0x2e, 0xa1 // smulwb ge r14 r1 r8
};
const byte kInstruction_smulwb_ls_r7_r12_r7[] = {
0xac, 0x07, 0x27, 0x91 // smulwb ls r7 r12 r7
};
const byte kInstruction_smulwb_al_r11_r10_r5[] = {
0xaa, 0x05, 0x2b, 0xe1 // smulwb al r11 r10 r5
};
const byte kInstruction_smulwb_al_r7_r4_r6[] = {
0xa4, 0x06, 0x27, 0xe1 // smulwb al r7 r4 r6
};
const byte kInstruction_smulwb_vs_r12_r4_r10[] = {
0xa4, 0x0a, 0x2c, 0x61 // smulwb vs r12 r4 r10
};
const byte kInstruction_smulwb_eq_r4_r4_r4[] = {
0xa4, 0x04, 0x24, 0x01 // smulwb eq r4 r4 r4
};
const byte kInstruction_smulwb_vs_r6_r6_r12[] = {
0xa6, 0x0c, 0x26, 0x61 // smulwb vs r6 r6 r12
};
const byte kInstruction_smulwb_pl_r9_r3_r5[] = {
0xa3, 0x05, 0x29, 0x51 // smulwb pl r9 r3 r5
};
const byte kInstruction_smulwb_eq_r6_r5_r13[] = {
0xa5, 0x0d, 0x26, 0x01 // smulwb eq r6 r5 r13
};
const byte kInstruction_smulwb_cc_r8_r2_r12[] = {
0xa2, 0x0c, 0x28, 0x31 // smulwb cc r8 r2 r12
};
const byte kInstruction_smulwb_le_r4_r2_r0[] = {
0xa2, 0x00, 0x24, 0xd1 // smulwb le r4 r2 r0
};
const byte kInstruction_smulwb_lt_r7_r9_r8[] = {
0xa9, 0x08, 0x27, 0xb1 // smulwb lt r7 r9 r8
};
const byte kInstruction_smulwb_le_r4_r7_r11[] = {
0xa7, 0x0b, 0x24, 0xd1 // smulwb le r4 r7 r11
};
const byte kInstruction_smulwb_eq_r5_r7_r5[] = {
0xa7, 0x05, 0x25, 0x01 // smulwb eq r5 r7 r5
};
const byte kInstruction_smulwb_vc_r10_r7_r12[] = {
0xa7, 0x0c, 0x2a, 0x71 // smulwb vc r10 r7 r12
};
const byte kInstruction_smulwb_eq_r7_r10_r6[] = {
0xaa, 0x06, 0x27, 0x01 // smulwb eq r7 r10 r6
};
const byte kInstruction_smulwb_pl_r1_r12_r2[] = {
0xac, 0x02, 0x21, 0x51 // smulwb pl r1 r12 r2
};
const byte kInstruction_smulwb_le_r14_r6_r6[] = {
0xa6, 0x06, 0x2e, 0xd1 // smulwb le r14 r6 r6
};
const byte kInstruction_smulwb_ne_r3_r8_r8[] = {
0xa8, 0x08, 0x23, 0x11 // smulwb ne r3 r8 r8
};
const byte kInstruction_smulwb_eq_r4_r12_r8[] = {
0xac, 0x08, 0x24, 0x01 // smulwb eq r4 r12 r8
};
const byte kInstruction_smulwb_ge_r11_r2_r3[] = {
0xa2, 0x03, 0x2b, 0xa1 // smulwb ge r11 r2 r3
};
const byte kInstruction_smulwb_hi_r12_r6_r11[] = {
0xa6, 0x0b, 0x2c, 0x81 // smulwb hi r12 r6 r11
};
const byte kInstruction_smulwb_cs_r4_r5_r10[] = {
0xa5, 0x0a, 0x24, 0x21 // smulwb cs r4 r5 r10
};
const byte kInstruction_smulwb_ge_r10_r2_r10[] = {
0xa2, 0x0a, 0x2a, 0xa1 // smulwb ge r10 r2 r10
};
const byte kInstruction_smulwb_ge_r5_r14_r6[] = {
0xae, 0x06, 0x25, 0xa1 // smulwb ge r5 r14 r6
};
const byte kInstruction_smulwb_gt_r13_r7_r5[] = {
0xa7, 0x05, 0x2d, 0xc1 // smulwb gt r13 r7 r5
};
const byte kInstruction_smulwb_ge_r13_r4_r12[] = {
0xa4, 0x0c, 0x2d, 0xa1 // smulwb ge r13 r4 r12
};
const byte kInstruction_smulwb_lt_r8_r10_r14[] = {
0xaa, 0x0e, 0x28, 0xb1 // smulwb lt r8 r10 r14
};
const byte kInstruction_smulwb_le_r4_r3_r13[] = {
0xa3, 0x0d, 0x24, 0xd1 // smulwb le r4 r3 r13
};
const byte kInstruction_smulwb_pl_r0_r9_r0[] = {
0xa9, 0x00, 0x20, 0x51 // smulwb pl r0 r9 r0
};
const byte kInstruction_smulwb_eq_r2_r3_r1[] = {
0xa3, 0x01, 0x22, 0x01 // smulwb eq r2 r3 r1
};
const byte kInstruction_smulwb_vc_r0_r0_r3[] = {
0xa0, 0x03, 0x20, 0x71 // smulwb vc r0 r0 r3
};
const byte kInstruction_smulwb_mi_r10_r8_r11[] = {
0xa8, 0x0b, 0x2a, 0x41 // smulwb mi r10 r8 r11
};
const byte kInstruction_smulwb_mi_r5_r14_r14[] = {
0xae, 0x0e, 0x25, 0x41 // smulwb mi r5 r14 r14
};
const byte kInstruction_smulwb_gt_r5_r11_r2[] = {
0xab, 0x02, 0x25, 0xc1 // smulwb gt r5 r11 r2
};
const byte kInstruction_smulwb_al_r4_r7_r11[] = {
0xa7, 0x0b, 0x24, 0xe1 // smulwb al r4 r7 r11
};
const TestResult kReferencesmulwb[] = {
{
ARRAY_SIZE(kInstruction_smulwb_hi_r1_r9_r5),
kInstruction_smulwb_hi_r1_r9_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r8_r6_r2),
kInstruction_smulwb_pl_r8_r6_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r5_r8_r2),
kInstruction_smulwb_hi_r5_r8_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r9_r2_r7),
kInstruction_smulwb_vc_r9_r2_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r4_r6_r3),
kInstruction_smulwb_lt_r4_r6_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r11_r6_r2),
kInstruction_smulwb_le_r11_r6_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r8_r14_r4),
kInstruction_smulwb_cc_r8_r14_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r5_r14_r6),
kInstruction_smulwb_le_r5_r14_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r6_r1_r0),
kInstruction_smulwb_lt_r6_r1_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r5_r0_r9),
kInstruction_smulwb_lt_r5_r0_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r8_r12_r7),
kInstruction_smulwb_le_r8_r12_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r7_r14_r6),
kInstruction_smulwb_eq_r7_r14_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r7_r4_r6),
kInstruction_smulwb_cs_r7_r4_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r9_r6_r9),
kInstruction_smulwb_gt_r9_r6_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r13_r9_r1),
kInstruction_smulwb_ne_r13_r9_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r13_r1_r13),
kInstruction_smulwb_ge_r13_r1_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r8_r10_r2),
kInstruction_smulwb_ls_r8_r10_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r0_r13_r5),
kInstruction_smulwb_hi_r0_r13_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r13_r7_r8),
kInstruction_smulwb_pl_r13_r7_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r4_r13_r11),
kInstruction_smulwb_ge_r4_r13_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r5_r10_r5),
kInstruction_smulwb_cs_r5_r10_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r5_r4_r3),
kInstruction_smulwb_cs_r5_r4_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r6_r14_r8),
kInstruction_smulwb_ls_r6_r14_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r3_r8_r6),
kInstruction_smulwb_vs_r3_r8_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r7_r12_r3),
kInstruction_smulwb_vc_r7_r12_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r1_r4_r1),
kInstruction_smulwb_ge_r1_r4_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r4_r7_r10),
kInstruction_smulwb_cc_r4_r7_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r2_r0_r13),
kInstruction_smulwb_cc_r2_r0_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r9_r6_r8),
kInstruction_smulwb_vs_r9_r6_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r14_r11_r13),
kInstruction_smulwb_cs_r14_r11_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r5_r8_r4),
kInstruction_smulwb_pl_r5_r8_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r2_r3_r7),
kInstruction_smulwb_pl_r2_r3_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r7_r12_r14),
kInstruction_smulwb_cs_r7_r12_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r6_r6_r1),
kInstruction_smulwb_hi_r6_r6_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r6_r9_r6),
kInstruction_smulwb_cc_r6_r9_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r12_r12_r0),
kInstruction_smulwb_ne_r12_r12_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r9_r3_r8),
kInstruction_smulwb_cc_r9_r3_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r13_r6_r1),
kInstruction_smulwb_mi_r13_r6_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r4_r8_r6),
kInstruction_smulwb_lt_r4_r8_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r11_r5_r9),
kInstruction_smulwb_hi_r11_r5_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r6_r10_r6),
kInstruction_smulwb_cc_r6_r10_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r10_r10_r5),
kInstruction_smulwb_eq_r10_r10_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r5_r4_r11),
kInstruction_smulwb_al_r5_r4_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r11_r11_r2),
kInstruction_smulwb_pl_r11_r11_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r6_r14_r12),
kInstruction_smulwb_ls_r6_r14_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r7_r7_r2),
kInstruction_smulwb_vc_r7_r7_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r10_r8_r4),
kInstruction_smulwb_eq_r10_r8_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r14_r7_r2),
kInstruction_smulwb_al_r14_r7_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r3_r11_r10),
kInstruction_smulwb_cs_r3_r11_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r11_r4_r0),
kInstruction_smulwb_ls_r11_r4_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r11_r8_r9),
kInstruction_smulwb_hi_r11_r8_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r2_r14_r13),
kInstruction_smulwb_vs_r2_r14_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r1_r13_r9),
kInstruction_smulwb_al_r1_r13_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r3_r9_r13),
kInstruction_smulwb_eq_r3_r9_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r10_r3_r13),
kInstruction_smulwb_ge_r10_r3_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r8_r5_r10),
kInstruction_smulwb_pl_r8_r5_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r8_r11_r6),
kInstruction_smulwb_vc_r8_r11_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r0_r0_r5),
kInstruction_smulwb_eq_r0_r0_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r6_r5_r8),
kInstruction_smulwb_ne_r6_r5_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r5_r13_r3),
kInstruction_smulwb_hi_r5_r13_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r11_r14_r14),
kInstruction_smulwb_ne_r11_r14_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r1_r0_r6),
kInstruction_smulwb_mi_r1_r0_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r14_r8_r2),
kInstruction_smulwb_le_r14_r8_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r9_r6_r5),
kInstruction_smulwb_eq_r9_r6_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r11_r0_r13),
kInstruction_smulwb_eq_r11_r0_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r4_r5_r14),
kInstruction_smulwb_pl_r4_r5_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r13_r5_r13),
kInstruction_smulwb_cs_r13_r5_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r0_r13_r8),
kInstruction_smulwb_mi_r0_r13_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r2_r13_r3),
kInstruction_smulwb_lt_r2_r13_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r8_r1_r11),
kInstruction_smulwb_ls_r8_r1_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r14_r11_r8),
kInstruction_smulwb_vc_r14_r11_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r4_r13_r12),
kInstruction_smulwb_lt_r4_r13_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r2_r1_r14),
kInstruction_smulwb_eq_r2_r1_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r9_r4_r14),
kInstruction_smulwb_eq_r9_r4_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r10_r6_r13),
kInstruction_smulwb_hi_r10_r6_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r12_r9_r4),
kInstruction_smulwb_ge_r12_r9_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r9_r11_r14),
kInstruction_smulwb_le_r9_r11_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r0_r9_r5),
kInstruction_smulwb_ls_r0_r9_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r2_r3_r8),
kInstruction_smulwb_mi_r2_r3_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r14_r10_r14),
kInstruction_smulwb_ne_r14_r10_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r6_r2_r10),
kInstruction_smulwb_eq_r6_r2_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r11_r0_r12),
kInstruction_smulwb_lt_r11_r0_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r1_r12_r10),
kInstruction_smulwb_ne_r1_r12_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r1_r0_r2),
kInstruction_smulwb_cc_r1_r0_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r5_r5_r7),
kInstruction_smulwb_al_r5_r5_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r7_r13_r1),
kInstruction_smulwb_hi_r7_r13_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r4_r4_r9),
kInstruction_smulwb_cs_r4_r4_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r14_r4_r14),
kInstruction_smulwb_eq_r14_r4_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r10_r5_r14),
kInstruction_smulwb_vs_r10_r5_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r4_r3_r11),
kInstruction_smulwb_gt_r4_r3_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r14_r10_r12),
kInstruction_smulwb_ne_r14_r10_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r2_r11_r0),
kInstruction_smulwb_vs_r2_r11_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r5_r12_r7),
kInstruction_smulwb_ge_r5_r12_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r7_r14_r6),
kInstruction_smulwb_mi_r7_r14_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r8_r3_r8),
kInstruction_smulwb_gt_r8_r3_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r9_r14_r3),
kInstruction_smulwb_hi_r9_r14_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r2_r11_r2),
kInstruction_smulwb_vc_r2_r11_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r11_r7_r12),
kInstruction_smulwb_hi_r11_r7_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r6_r4_r11),
kInstruction_smulwb_cs_r6_r4_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r12_r5_r9),
kInstruction_smulwb_cs_r12_r5_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r5_r10_r5),
kInstruction_smulwb_ls_r5_r10_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r0_r9_r13),
kInstruction_smulwb_ls_r0_r9_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r3_r3_r5),
kInstruction_smulwb_lt_r3_r3_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r0_r12_r8),
kInstruction_smulwb_mi_r0_r12_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r3_r12_r12),
kInstruction_smulwb_pl_r3_r12_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r8_r12_r5),
kInstruction_smulwb_eq_r8_r12_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r7_r8_r1),
kInstruction_smulwb_cc_r7_r8_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r2_r13_r10),
kInstruction_smulwb_hi_r2_r13_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r7_r10_r10),
kInstruction_smulwb_al_r7_r10_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r1_r12_r2),
kInstruction_smulwb_vc_r1_r12_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r8_r5_r8),
kInstruction_smulwb_cc_r8_r5_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r3_r7_r9),
kInstruction_smulwb_ls_r3_r7_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r8_r10_r8),
kInstruction_smulwb_al_r8_r10_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r4_r12_r10),
kInstruction_smulwb_lt_r4_r12_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r10_r5_r11),
kInstruction_smulwb_ge_r10_r5_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r3_r14_r4),
kInstruction_smulwb_ls_r3_r14_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r3_r6_r12),
kInstruction_smulwb_hi_r3_r6_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r6_r0_r4),
kInstruction_smulwb_hi_r6_r0_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r11_r6_r0),
kInstruction_smulwb_al_r11_r6_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r3_r1_r9),
kInstruction_smulwb_mi_r3_r1_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r12_r13_r0),
kInstruction_smulwb_mi_r12_r13_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r1_r2_r5),
kInstruction_smulwb_le_r1_r2_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r4_r3_r14),
kInstruction_smulwb_hi_r4_r3_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r6_r11_r11),
kInstruction_smulwb_eq_r6_r11_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r14_r11_r14),
kInstruction_smulwb_cc_r14_r11_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r4_r10_r0),
kInstruction_smulwb_hi_r4_r10_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r7_r11_r1),
kInstruction_smulwb_cc_r7_r11_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r14_r6_r10),
kInstruction_smulwb_mi_r14_r6_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r2_r0_r11),
kInstruction_smulwb_eq_r2_r0_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r13_r5_r12),
kInstruction_smulwb_mi_r13_r5_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r2_r12_r5),
kInstruction_smulwb_eq_r2_r12_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r12_r0_r2),
kInstruction_smulwb_le_r12_r0_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r10_r10_r9),
kInstruction_smulwb_vc_r10_r10_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r11_r11_r8),
kInstruction_smulwb_ls_r11_r11_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r10_r11_r9),
kInstruction_smulwb_hi_r10_r11_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r7_r12_r14),
kInstruction_smulwb_vs_r7_r12_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r11_r14_r12),
kInstruction_smulwb_gt_r11_r14_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r0_r12_r8),
kInstruction_smulwb_vs_r0_r12_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r0_r5_r7),
kInstruction_smulwb_al_r0_r5_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r5_r13_r8),
kInstruction_smulwb_hi_r5_r13_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r9_r9_r7),
kInstruction_smulwb_le_r9_r9_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r4_r9_r5),
kInstruction_smulwb_cc_r4_r9_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r8_r1_r3),
kInstruction_smulwb_vs_r8_r1_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r0_r10_r12),
kInstruction_smulwb_cc_r0_r10_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r7_r14_r0),
kInstruction_smulwb_eq_r7_r14_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r12_r9_r11),
kInstruction_smulwb_vs_r12_r9_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r5_r9_r11),
kInstruction_smulwb_gt_r5_r9_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r14_r13_r7),
kInstruction_smulwb_cs_r14_r13_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r11_r3_r10),
kInstruction_smulwb_mi_r11_r3_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r11_r8_r12),
kInstruction_smulwb_hi_r11_r8_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r3_r8_r13),
kInstruction_smulwb_cs_r3_r8_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r10_r12_r6),
kInstruction_smulwb_pl_r10_r12_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r7_r3_r2),
kInstruction_smulwb_vc_r7_r3_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r9_r0_r8),
kInstruction_smulwb_mi_r9_r0_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r2_r13_r7),
kInstruction_smulwb_eq_r2_r13_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r2_r14_r0),
kInstruction_smulwb_ne_r2_r14_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r4_r10_r0),
kInstruction_smulwb_vs_r4_r10_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r0_r2_r2),
kInstruction_smulwb_ls_r0_r2_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r1_r6_r0),
kInstruction_smulwb_cc_r1_r6_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r12_r0_r8),
kInstruction_smulwb_lt_r12_r0_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r9_r3_r14),
kInstruction_smulwb_cc_r9_r3_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r7_r9_r1),
kInstruction_smulwb_vs_r7_r9_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r11_r9_r14),
kInstruction_smulwb_eq_r11_r9_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r6_r10_r4),
kInstruction_smulwb_pl_r6_r10_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r8_r5_r6),
kInstruction_smulwb_ne_r8_r5_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r0_r6_r2),
kInstruction_smulwb_cs_r0_r6_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r11_r12_r4),
kInstruction_smulwb_eq_r11_r12_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r14_r3_r14),
kInstruction_smulwb_lt_r14_r3_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r7_r12_r14),
kInstruction_smulwb_le_r7_r12_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r2_r9_r9),
kInstruction_smulwb_hi_r2_r9_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r8_r1_r0),
kInstruction_smulwb_ne_r8_r1_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r5_r11_r2),
kInstruction_smulwb_cc_r5_r11_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r0_r1_r2),
kInstruction_smulwb_hi_r0_r1_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r4_r9_r4),
kInstruction_smulwb_al_r4_r9_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r12_r7_r14),
kInstruction_smulwb_cs_r12_r7_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r4_r12_r10),
kInstruction_smulwb_cc_r4_r12_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r3_r5_r10),
kInstruction_smulwb_al_r3_r5_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r5_r3_r7),
kInstruction_smulwb_mi_r5_r3_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r10_r6_r2),
kInstruction_smulwb_ls_r10_r6_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r0_r12_r11),
kInstruction_smulwb_mi_r0_r12_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r12_r5_r6),
kInstruction_smulwb_vc_r12_r5_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r3_r9_r4),
kInstruction_smulwb_cs_r3_r9_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r4_r9_r11),
kInstruction_smulwb_ls_r4_r9_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r14_r8_r13),
kInstruction_smulwb_le_r14_r8_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r4_r10_r8),
kInstruction_smulwb_gt_r4_r10_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r6_r9_r9),
kInstruction_smulwb_al_r6_r9_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r8_r5_r12),
kInstruction_smulwb_ne_r8_r5_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r0_r4_r8),
kInstruction_smulwb_ne_r0_r4_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r7_r13_r3),
kInstruction_smulwb_mi_r7_r13_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r11_r7_r0),
kInstruction_smulwb_cc_r11_r7_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r1_r0_r12),
kInstruction_smulwb_hi_r1_r0_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r8_r9_r3),
kInstruction_smulwb_lt_r8_r9_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r0_r2_r1),
kInstruction_smulwb_al_r0_r2_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r4_r3_r14),
kInstruction_smulwb_vs_r4_r3_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r2_r11_r1),
kInstruction_smulwb_ge_r2_r11_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r12_r9_r6),
kInstruction_smulwb_lt_r12_r9_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r8_r2_r7),
kInstruction_smulwb_ls_r8_r2_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r8_r13_r3),
kInstruction_smulwb_le_r8_r13_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r11_r13_r14),
kInstruction_smulwb_eq_r11_r13_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r1_r6_r13),
kInstruction_smulwb_lt_r1_r6_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r3_r8_r11),
kInstruction_smulwb_cs_r3_r8_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r12_r5_r4),
kInstruction_smulwb_pl_r12_r5_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r8_r7_r2),
kInstruction_smulwb_eq_r8_r7_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r2_r12_r2),
kInstruction_smulwb_ls_r2_r12_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r14_r2_r3),
kInstruction_smulwb_le_r14_r2_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r10_r11_r6),
kInstruction_smulwb_ge_r10_r11_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r0_r2_r2),
kInstruction_smulwb_hi_r0_r2_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r2_r0_r2),
kInstruction_smulwb_ge_r2_r0_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r11_r14_r0),
kInstruction_smulwb_vs_r11_r14_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r2_r0_r1),
kInstruction_smulwb_lt_r2_r0_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r2_r5_r11),
kInstruction_smulwb_cs_r2_r5_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r7_r14_r5),
kInstruction_smulwb_ls_r7_r14_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r0_r0_r3),
kInstruction_smulwb_pl_r0_r0_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r6_r8_r8),
kInstruction_smulwb_ge_r6_r8_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r11_r1_r10),
kInstruction_smulwb_le_r11_r1_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r5_r2_r7),
kInstruction_smulwb_vs_r5_r2_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r4_r4_r8),
kInstruction_smulwb_ne_r4_r4_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r9_r14_r13),
kInstruction_smulwb_cc_r9_r14_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r14_r6_r3),
kInstruction_smulwb_hi_r14_r6_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r0_r8_r0),
kInstruction_smulwb_al_r0_r8_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r6_r11_r1),
kInstruction_smulwb_lt_r6_r11_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r7_r6_r12),
kInstruction_smulwb_ge_r7_r6_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r4_r6_r14),
kInstruction_smulwb_cs_r4_r6_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r7_r6_r7),
kInstruction_smulwb_cs_r7_r6_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r3_r7_r10),
kInstruction_smulwb_cs_r3_r7_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r0_r2_r1),
kInstruction_smulwb_ne_r0_r2_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r9_r10_r13),
kInstruction_smulwb_vs_r9_r10_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r11_r14_r12),
kInstruction_smulwb_vc_r11_r14_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r14_r8_r7),
kInstruction_smulwb_ge_r14_r8_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r13_r0_r11),
kInstruction_smulwb_lt_r13_r0_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r14_r13_r4),
kInstruction_smulwb_lt_r14_r13_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r1_r10_r9),
kInstruction_smulwb_al_r1_r10_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r11_r14_r11),
kInstruction_smulwb_ge_r11_r14_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r11_r4_r11),
kInstruction_smulwb_cs_r11_r4_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r0_r14_r7),
kInstruction_smulwb_ge_r0_r14_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r1_r2_r9),
kInstruction_smulwb_mi_r1_r2_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r5_r12_r3),
kInstruction_smulwb_eq_r5_r12_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r1_r5_r12),
kInstruction_smulwb_ge_r1_r5_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r10_r11_r4),
kInstruction_smulwb_lt_r10_r11_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r1_r1_r5),
kInstruction_smulwb_le_r1_r1_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r9_r1_r8),
kInstruction_smulwb_al_r9_r1_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r6_r8_r4),
kInstruction_smulwb_ne_r6_r8_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r12_r2_r9),
kInstruction_smulwb_ge_r12_r2_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r4_r3_r10),
kInstruction_smulwb_pl_r4_r3_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r14_r4_r11),
kInstruction_smulwb_eq_r14_r4_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r9_r7_r6),
kInstruction_smulwb_cc_r9_r7_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r12_r4_r5),
kInstruction_smulwb_ge_r12_r4_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r2_r3_r4),
kInstruction_smulwb_hi_r2_r3_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r0_r3_r1),
kInstruction_smulwb_cs_r0_r3_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r6_r2_r8),
kInstruction_smulwb_hi_r6_r2_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r3_r14_r13),
kInstruction_smulwb_cc_r3_r14_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r11_r4_r7),
kInstruction_smulwb_gt_r11_r4_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r5_r0_r12),
kInstruction_smulwb_hi_r5_r0_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r0_r14_r14),
kInstruction_smulwb_gt_r0_r14_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r9_r0_r10),
kInstruction_smulwb_hi_r9_r0_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r7_r11_r8),
kInstruction_smulwb_vc_r7_r11_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r11_r9_r6),
kInstruction_smulwb_pl_r11_r9_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r3_r3_r7),
kInstruction_smulwb_al_r3_r3_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r5_r7_r9),
kInstruction_smulwb_mi_r5_r7_r9,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r11_r2_r4),
kInstruction_smulwb_cc_r11_r2_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r9_r13_r10),
kInstruction_smulwb_cc_r9_r13_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r5_r2_r6),
kInstruction_smulwb_al_r5_r2_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r9_r4_r6),
kInstruction_smulwb_ge_r9_r4_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r3_r3_r4),
kInstruction_smulwb_ls_r3_r3_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r14_r1_r8),
kInstruction_smulwb_ge_r14_r1_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ls_r7_r12_r7),
kInstruction_smulwb_ls_r7_r12_r7,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r11_r10_r5),
kInstruction_smulwb_al_r11_r10_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r7_r4_r6),
kInstruction_smulwb_al_r7_r4_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r12_r4_r10),
kInstruction_smulwb_vs_r12_r4_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r4_r4_r4),
kInstruction_smulwb_eq_r4_r4_r4,
},
{
ARRAY_SIZE(kInstruction_smulwb_vs_r6_r6_r12),
kInstruction_smulwb_vs_r6_r6_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r9_r3_r5),
kInstruction_smulwb_pl_r9_r3_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r6_r5_r13),
kInstruction_smulwb_eq_r6_r5_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_cc_r8_r2_r12),
kInstruction_smulwb_cc_r8_r2_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r4_r2_r0),
kInstruction_smulwb_le_r4_r2_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r7_r9_r8),
kInstruction_smulwb_lt_r7_r9_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r4_r7_r11),
kInstruction_smulwb_le_r4_r7_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r5_r7_r5),
kInstruction_smulwb_eq_r5_r7_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r10_r7_r12),
kInstruction_smulwb_vc_r10_r7_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r7_r10_r6),
kInstruction_smulwb_eq_r7_r10_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r1_r12_r2),
kInstruction_smulwb_pl_r1_r12_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r14_r6_r6),
kInstruction_smulwb_le_r14_r6_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_ne_r3_r8_r8),
kInstruction_smulwb_ne_r3_r8_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r4_r12_r8),
kInstruction_smulwb_eq_r4_r12_r8,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r11_r2_r3),
kInstruction_smulwb_ge_r11_r2_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_hi_r12_r6_r11),
kInstruction_smulwb_hi_r12_r6_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_cs_r4_r5_r10),
kInstruction_smulwb_cs_r4_r5_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r10_r2_r10),
kInstruction_smulwb_ge_r10_r2_r10,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r5_r14_r6),
kInstruction_smulwb_ge_r5_r14_r6,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r13_r7_r5),
kInstruction_smulwb_gt_r13_r7_r5,
},
{
ARRAY_SIZE(kInstruction_smulwb_ge_r13_r4_r12),
kInstruction_smulwb_ge_r13_r4_r12,
},
{
ARRAY_SIZE(kInstruction_smulwb_lt_r8_r10_r14),
kInstruction_smulwb_lt_r8_r10_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_le_r4_r3_r13),
kInstruction_smulwb_le_r4_r3_r13,
},
{
ARRAY_SIZE(kInstruction_smulwb_pl_r0_r9_r0),
kInstruction_smulwb_pl_r0_r9_r0,
},
{
ARRAY_SIZE(kInstruction_smulwb_eq_r2_r3_r1),
kInstruction_smulwb_eq_r2_r3_r1,
},
{
ARRAY_SIZE(kInstruction_smulwb_vc_r0_r0_r3),
kInstruction_smulwb_vc_r0_r0_r3,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r10_r8_r11),
kInstruction_smulwb_mi_r10_r8_r11,
},
{
ARRAY_SIZE(kInstruction_smulwb_mi_r5_r14_r14),
kInstruction_smulwb_mi_r5_r14_r14,
},
{
ARRAY_SIZE(kInstruction_smulwb_gt_r5_r11_r2),
kInstruction_smulwb_gt_r5_r11_r2,
},
{
ARRAY_SIZE(kInstruction_smulwb_al_r4_r7_r11),
kInstruction_smulwb_al_r4_r7_r11,
},
};
#endif // VIXL_ASSEMBLER_COND_RD_RN_RM_SMULWB_A32_H_
| 412 | 0.748194 | 1 | 0.748194 | game-dev | MEDIA | 0.282998 | game-dev | 0.740843 | 1 | 0.740843 |
ProjectIgnis/CardScripts | 3,286 | official/c38529357.lua | --命の代行者 ネプチューン
--The Agent of Life - Neptune
--Scripted by Hatter
local s,id=GetID()
function s.initial_effect(c)
--Special Summon from hand or GY
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCost(Cost.SelfDiscard)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Add "The Sanctuary in the Sky" to hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCode(EVENT_REMOVE)
e2:SetCountLimit(1,{id,1})
e2:SetTarget(s.thtg)
e2:SetOperation(s.thop)
c:RegisterEffect(e2)
end
s.listed_series={SET_THE_AGENT,SET_HYPERION}
s.listed_names={CARD_SANCTUARY_SKY}
function s.spfilter(c,e,tp,sanc)
return ((c:IsSetCard(SET_THE_AGENT) and not c:IsCode(id)) or (sanc and c:IsSetCard(SET_HYPERION))) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local sanc=Duel.IsEnvironment(CARD_SANCTUARY_SKY)
or Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,CARD_SANCTUARY_SKY),e:GetHandlerPlayer(),LOCATION_ONFIELD|LOCATION_GRAVE,LOCATION_ONFIELD|LOCATION_GRAVE,1,nil)
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_GRAVE|LOCATION_HAND,0,1,nil,e,tp,sanc)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE|LOCATION_HAND)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<1 then return end
local sanc=Duel.IsEnvironment(CARD_SANCTUARY_SKY)
or Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsCode,CARD_SANCTUARY_SKY),e:GetHandlerPlayer(),LOCATION_ONFIELD|LOCATION_GRAVE,LOCATION_ONFIELD|LOCATION_GRAVE,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tc=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(s.spfilter),tp,LOCATION_GRAVE|LOCATION_HAND,0,1,1,nil,e,tp,sanc):GetFirst()
if tc then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
--Cannot be tributed
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(3303)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UNRELEASABLE_SUM)
e1:SetValue(1)
e1:SetReset(RESETS_STANDARD_DISABLE_PHASE_END,2)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_UNRELEASABLE_NONSUM)
e2:SetValue(1)
e2:SetReset(RESETS_STANDARD_DISABLE_PHASE_END,2)
tc:RegisterEffect(e2)
end
end
function s.thfilter(c)
return c:IsCode(CARD_SANCTUARY_SKY) and c:IsAbleToHand()
end
function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function s.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end | 412 | 0.949736 | 1 | 0.949736 | game-dev | MEDIA | 0.956819 | game-dev | 0.87946 | 1 | 0.87946 |
Hiro420/CockPY | 2,297 | server_data/lua/gadget/gear_keep_spray.lua |
-- 初始状态
local state_ = GadgetState.GearStart
-- 启动元素
local start_elem_type_ = ElementType.Fire
-- 最大启动值
local max_start_value_ = 1
-- 停止元素
local stop_elem_type_ = ElementType.Ice
-- 最大停止值
local max_stop_value_ = 1
-- 停止持续时间
local stop_last_time_ = 4
--
-- 机关被攻击
function OnBeHurt(context, element_type, strike_type)
-- 获取机关当前状态
local state = ScriptLib.GetGadgetState(context)
if state == GadgetState.GearStop then
if element_type == start_elem_type then
-- 获取原有的启动值
local start_value = ScriptLib.GetGearStartValue(context)
start_value = start_value + 1
if start_value >= max_start_value_ then
-- 在Default状态下,启动值超过最大启动值,则转换为GearStart状态
ScriptLib.SetGadgetState(context, GadgetState.GearStart)
-- 启动值设置为最大启动值
ScriptLib.SetGearStartValue(context, max_start_value_)
else
-- 在Default状态下,被启动元素攻击一次,增加1点启动值
ScriptLib.SetGearStartValue(context, start_value)
end
--待机状态的机关也会进入停止状态
elseif stop_elem_type_ ~= ElementType.None and element_type == stop_elem_type_ then
-- 在GearStop状态下,重置停止状态(刷新开始时间)
ScriptLib.ResetGadgetState(context, GadgetState.GearStop)
end
elseif state == GadgetState.GearStart then
if stop_elem_type_ ~= ElementType.None and element_type == stop_elem_type_ then
-- 获取原有的停止值
local stop_value = ScriptLib.GetGearStopValue(context)
stop_value = stop_value + 1
if stop_value >= max_stop_value_ then
-- 在GearStart状态下,停止值超过最大停止值,则转换为GearStop状态
ScriptLib.SetGadgetState(context, GadgetState.GearStop)
-- 停止值设置为最大停止值
ScriptLib.SetGearStopValue(context, max_stop_value_)
else
-- 在GearStart状态下,被停止元素攻击一次,增加1点停止值
ScriptLib.SetGearStopValue(context, stop_value)
end
end
end
end
function OnClientExecuteReq(context, param1, param2, param3)
if param1 == 1 then
ScriptLib.SetGadgetState(context, GadgetState.GearStart)
end
end
--[[-- 定时器回调
function OnTimer(context, now)
-- 获取机关当前状态
local state = ScriptLib.GetGadgetState(context)
if state == GadgetState.GearStop then
-- 获取当前状态的开始时间
local state_begin_time = ScriptLib.GetGadgetStateBeginTime(context)
if now >= state_begin_time + stop_last_time_ then
-- 如果停止时间超过停止持续时间,则转换为GearStart状态
ScriptLib.SetGadgetState(context, GadgetState.GearStart)
-- 设置停止值为0
ScriptLib.SetGearStopValue(context, 0)
end
end
end--]]
| 412 | 0.905302 | 1 | 0.905302 | game-dev | MEDIA | 0.98457 | game-dev | 0.954123 | 1 | 0.954123 |
renpy/rapt | 50,183 | native/jni/sdl2/src/video/x11/SDL_x11events.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2015 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.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_X11
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <limits.h> /* For INT_MAX */
#include "SDL_x11video.h"
#include "SDL_x11touch.h"
#include "SDL_x11xinput2.h"
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_touch_c.h"
#include "SDL_timer.h"
#include "SDL_syswm.h"
#include <stdio.h>
/*#define DEBUG_XEVENTS*/
#ifndef _NET_WM_MOVERESIZE_SIZE_TOPLEFT
#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_TOP
#define _NET_WM_MOVERESIZE_SIZE_TOP 1
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_TOPRIGHT
#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_RIGHT
#define _NET_WM_MOVERESIZE_SIZE_RIGHT 3
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOM
#define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_LEFT
#define _NET_WM_MOVERESIZE_SIZE_LEFT 7
#endif
#ifndef _NET_WM_MOVERESIZE_MOVE
#define _NET_WM_MOVERESIZE_MOVE 8
#endif
typedef struct {
unsigned char *data;
int format, count;
Atom type;
} SDL_x11Prop;
/* Reads property
Must call X11_XFree on results
*/
static void X11_ReadProperty(SDL_x11Prop *p, Display *disp, Window w, Atom prop)
{
unsigned char *ret=NULL;
Atom type;
int fmt;
unsigned long count;
unsigned long bytes_left;
int bytes_fetch = 0;
do {
if (ret != 0) X11_XFree(ret);
X11_XGetWindowProperty(disp, w, prop, 0, bytes_fetch, False, AnyPropertyType, &type, &fmt, &count, &bytes_left, &ret);
bytes_fetch += bytes_left;
} while (bytes_left != 0);
p->data=ret;
p->format=fmt;
p->count=count;
p->type=type;
}
/* Find text-uri-list in a list of targets and return it's atom
if available, else return None */
static Atom X11_PickTarget(Display *disp, Atom list[], int list_count)
{
Atom request = None;
char *name;
int i;
for (i=0; i < list_count && request == None; i++) {
name = X11_XGetAtomName(disp, list[i]);
if (strcmp("text/uri-list", name)==0) request = list[i];
X11_XFree(name);
}
return request;
}
/* Wrapper for X11_PickTarget for a maximum of three targets, a special
case in the Xdnd protocol */
static Atom X11_PickTargetFromAtoms(Display *disp, Atom a0, Atom a1, Atom a2)
{
int count=0;
Atom atom[3];
if (a0 != None) atom[count++] = a0;
if (a1 != None) atom[count++] = a1;
if (a2 != None) atom[count++] = a2;
return X11_PickTarget(disp, atom, count);
}
struct KeyRepeatCheckData
{
XEvent *event;
SDL_bool found;
};
static Bool X11_KeyRepeatCheckIfEvent(Display *display, XEvent *chkev,
XPointer arg)
{
struct KeyRepeatCheckData *d = (struct KeyRepeatCheckData *) arg;
if (chkev->type == KeyPress &&
chkev->xkey.keycode == d->event->xkey.keycode &&
chkev->xkey.time - d->event->xkey.time < 2)
d->found = SDL_TRUE;
return False;
}
/* Check to see if this is a repeated key.
(idea shamelessly lifted from GII -- thanks guys! :)
*/
static SDL_bool X11_KeyRepeat(Display *display, XEvent *event)
{
XEvent dummyev;
struct KeyRepeatCheckData d;
d.event = event;
d.found = SDL_FALSE;
if (X11_XPending(display))
X11_XCheckIfEvent(display, &dummyev, X11_KeyRepeatCheckIfEvent,
(XPointer) &d);
return d.found;
}
static Bool X11_IsWheelCheckIfEvent(Display *display, XEvent *chkev,
XPointer arg)
{
XEvent *event = (XEvent *) arg;
/* we only handle buttons 4 and 5 - false positive avoidance */
if (chkev->type == ButtonRelease &&
(event->xbutton.button == Button4 || event->xbutton.button == Button5 ||
event->xbutton.button == 6 || event->xbutton.button == 7) &&
chkev->xbutton.button == event->xbutton.button &&
chkev->xbutton.time == event->xbutton.time)
return True;
return False;
}
static SDL_bool X11_IsWheelEvent(Display * display,XEvent * event,int * xticks,int * yticks)
{
XEvent relevent;
if (X11_XPending(display)) {
/* according to the xlib docs, no specific mouse wheel events exist.
however, mouse wheel events trigger a button press and a button release
immediately. thus, checking if the same button was released at the same
time as it was pressed, should be an adequate hack to derive a mouse
wheel event.
However, there is broken and unusual hardware out there...
- False positive: a button for which a release event is
generated (or synthesised) immediately.
- False negative: a wheel which, when rolled, doesn't have
a release event generated immediately. */
if (X11_XCheckIfEvent(display, &relevent, X11_IsWheelCheckIfEvent,
(XPointer) event)) {
/* by default, X11 only knows 5 buttons. on most 3 button + wheel mouse,
Button4 maps to (vertical) wheel up, Button5 maps to wheel down.
Horizontal scrolling usually maps to 6 and 7 which have no name */
if (event->xbutton.button == Button4) {
*yticks = 1;
}
else if (event->xbutton.button == Button5) {
*yticks = -1;
}
else if (event->xbutton.button == 6) {
*xticks = 1;
}
else if (event->xbutton.button == 7) {
*xticks = -1;
}
return SDL_TRUE;
}
}
return SDL_FALSE;
}
/* Decodes URI escape sequences in string buf of len bytes
(excluding the terminating NULL byte) in-place. Since
URI-encoded characters take three times the space of
normal characters, this should not be an issue.
Returns the number of decoded bytes that wound up in
the buffer, excluding the terminating NULL byte.
The buffer is guaranteed to be NULL-terminated but
may contain embedded NULL bytes.
On error, -1 is returned.
*/
int X11_URIDecode(char *buf, int len) {
int ri, wi, di;
char decode = '\0';
if (buf == NULL || len < 0) {
errno = EINVAL;
return -1;
}
if (len == 0) {
len = SDL_strlen(buf);
}
for (ri = 0, wi = 0, di = 0; ri < len && wi < len; ri += 1) {
if (di == 0) {
/* start decoding */
if (buf[ri] == '%') {
decode = '\0';
di += 1;
continue;
}
/* normal write */
buf[wi] = buf[ri];
wi += 1;
continue;
} else if (di == 1 || di == 2) {
char off = '\0';
char isa = buf[ri] >= 'a' && buf[ri] <= 'f';
char isA = buf[ri] >= 'A' && buf[ri] <= 'F';
char isn = buf[ri] >= '0' && buf[ri] <= '9';
if (!(isa || isA || isn)) {
/* not a hexadecimal */
int sri;
for (sri = ri - di; sri <= ri; sri += 1) {
buf[wi] = buf[sri];
wi += 1;
}
di = 0;
continue;
}
/* itsy bitsy magicsy */
if (isn) {
off = 0 - '0';
} else if (isa) {
off = 10 - 'a';
} else if (isA) {
off = 10 - 'A';
}
decode |= (buf[ri] + off) << (2 - di) * 4;
if (di == 2) {
buf[wi] = decode;
wi += 1;
di = 0;
} else {
di += 1;
}
continue;
}
}
buf[wi] = '\0';
return wi;
}
/* Convert URI to local filename
return filename if possible, else NULL
*/
static char* X11_URIToLocal(char* uri) {
char *file = NULL;
SDL_bool local;
if (memcmp(uri,"file:/",6) == 0) uri += 6; /* local file? */
else if (strstr(uri,":/") != NULL) return file; /* wrong scheme */
local = uri[0] != '/' || (uri[0] != '\0' && uri[1] == '/');
/* got a hostname? */
if (!local && uri[0] == '/' && uri[2] != '/') {
char* hostname_end = strchr(uri+1, '/');
if (hostname_end != NULL) {
char hostname[ 257 ];
if (gethostname(hostname, 255) == 0) {
hostname[ 256 ] = '\0';
if (memcmp(uri+1, hostname, hostname_end - (uri+1)) == 0) {
uri = hostname_end + 1;
local = SDL_TRUE;
}
}
}
}
if (local) {
file = uri;
/* Convert URI escape sequences to real characters */
X11_URIDecode(file, 0);
if (uri[1] == '/') {
file++;
} else {
file--;
}
}
return file;
}
#if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
static void X11_HandleGenericEvent(SDL_VideoData *videodata,XEvent event)
{
/* event is a union, so cookie == &event, but this is type safe. */
XGenericEventCookie *cookie = &event.xcookie;
if (X11_XGetEventData(videodata->display, cookie)) {
X11_HandleXinput2Event(videodata, cookie);
X11_XFreeEventData(videodata->display, cookie);
}
}
#endif /* SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS */
static unsigned
X11_GetNumLockModifierMask(_THIS)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
Display *display = viddata->display;
unsigned num_mask = 0;
int i, j;
XModifierKeymap *xmods;
unsigned n;
xmods = X11_XGetModifierMapping(display);
n = xmods->max_keypermod;
for(i = 3; i < 8; i++) {
for(j = 0; j < n; j++) {
KeyCode kc = xmods->modifiermap[i * n + j];
if (viddata->key_layout[kc] == SDL_SCANCODE_NUMLOCKCLEAR) {
num_mask = 1 << i;
break;
}
}
}
X11_XFreeModifiermap(xmods);
return num_mask;
}
static void
X11_ReconcileKeyboardState(_THIS)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
Display *display = viddata->display;
char keys[32];
int keycode;
Window junk_window;
int x, y;
unsigned int mask;
X11_XQueryKeymap(display, keys);
/* Get the keyboard modifier state */
if (X11_XQueryPointer(display, DefaultRootWindow(display), &junk_window, &junk_window, &x, &y, &x, &y, &mask)) {
unsigned num_mask = X11_GetNumLockModifierMask(_this);
const Uint8 *keystate = SDL_GetKeyboardState(NULL);
Uint8 capslockState = keystate[SDL_SCANCODE_CAPSLOCK];
Uint8 numlockState = keystate[SDL_SCANCODE_NUMLOCKCLEAR];
/* Toggle key mod state if needed */
if (!!(mask & LockMask) != !!(SDL_GetModState() & KMOD_CAPS)) {
SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_CAPSLOCK);
if (capslockState == SDL_RELEASED) {
SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_CAPSLOCK);
}
}
if (!!(mask & num_mask) != !!(SDL_GetModState() & KMOD_NUM)) {
SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_NUMLOCKCLEAR);
if (numlockState == SDL_RELEASED) {
SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_NUMLOCKCLEAR);
}
}
}
for (keycode = 0; keycode < 256; ++keycode) {
if (keys[keycode / 8] & (1 << (keycode % 8))) {
SDL_SendKeyboardKey(SDL_PRESSED, viddata->key_layout[keycode]);
} else {
SDL_SendKeyboardKey(SDL_RELEASED, viddata->key_layout[keycode]);
}
}
}
static void
X11_DispatchFocusIn(_THIS, SDL_WindowData *data)
{
#ifdef DEBUG_XEVENTS
printf("window %p: Dispatching FocusIn\n", data);
#endif
SDL_SetKeyboardFocus(data->window);
X11_ReconcileKeyboardState(_this);
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_XSetICFocus(data->ic);
}
#endif
#ifdef SDL_USE_IBUS
SDL_IBus_SetFocus(SDL_TRUE);
#endif
}
static void
X11_DispatchFocusOut(_THIS, SDL_WindowData *data)
{
#ifdef DEBUG_XEVENTS
printf("window %p: Dispatching FocusOut\n", data);
#endif
/* If another window has already processed a focus in, then don't try to
* remove focus here. Doing so will incorrectly remove focus from that
* window, and the focus lost event for this window will have already
* been dispatched anyway. */
if (data->window == SDL_GetKeyboardFocus()) {
SDL_SetKeyboardFocus(NULL);
}
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_XUnsetICFocus(data->ic);
}
#endif
#ifdef SDL_USE_IBUS
SDL_IBus_SetFocus(SDL_FALSE);
#endif
}
static void
X11_DispatchMapNotify(SDL_WindowData *data)
{
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_SHOWN, 0, 0);
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0);
}
static void
X11_DispatchUnmapNotify(SDL_WindowData *data)
{
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0);
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
}
static void
InitiateWindowMove(_THIS, const SDL_WindowData *data, const SDL_Point *point)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
SDL_Window* window = data->window;
Display *display = viddata->display;
XEvent evt;
/* !!! FIXME: we need to regrab this if necessary when the drag is done. */
X11_XUngrabPointer(display, 0L);
X11_XFlush(display);
evt.xclient.type = ClientMessage;
evt.xclient.window = data->xwindow;
evt.xclient.message_type = X11_XInternAtom(display, "_NET_WM_MOVERESIZE", True);
evt.xclient.format = 32;
evt.xclient.data.l[0] = window->x + point->x;
evt.xclient.data.l[1] = window->y + point->y;
evt.xclient.data.l[2] = _NET_WM_MOVERESIZE_MOVE;
evt.xclient.data.l[3] = Button1;
evt.xclient.data.l[4] = 0;
X11_XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask, &evt);
X11_XSync(display, 0);
}
static void
InitiateWindowResize(_THIS, const SDL_WindowData *data, const SDL_Point *point, int direction)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
SDL_Window* window = data->window;
Display *display = viddata->display;
XEvent evt;
if (direction < _NET_WM_MOVERESIZE_SIZE_TOPLEFT || direction > _NET_WM_MOVERESIZE_SIZE_LEFT)
return;
/* !!! FIXME: we need to regrab this if necessary when the drag is done. */
X11_XUngrabPointer(display, 0L);
X11_XFlush(display);
evt.xclient.type = ClientMessage;
evt.xclient.window = data->xwindow;
evt.xclient.message_type = X11_XInternAtom(display, "_NET_WM_MOVERESIZE", True);
evt.xclient.format = 32;
evt.xclient.data.l[0] = window->x + point->x;
evt.xclient.data.l[1] = window->y + point->y;
evt.xclient.data.l[2] = direction;
evt.xclient.data.l[3] = Button1;
evt.xclient.data.l[4] = 0;
X11_XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask, &evt);
X11_XSync(display, 0);
}
static SDL_bool
ProcessHitTest(_THIS, const SDL_WindowData *data, const XEvent *xev)
{
SDL_Window *window = data->window;
if (window->hit_test) {
const SDL_Point point = { xev->xbutton.x, xev->xbutton.y };
const SDL_HitTestResult rc = window->hit_test(window, &point, window->hit_test_data);
static const int directions[] = {
_NET_WM_MOVERESIZE_SIZE_TOPLEFT, _NET_WM_MOVERESIZE_SIZE_TOP,
_NET_WM_MOVERESIZE_SIZE_TOPRIGHT, _NET_WM_MOVERESIZE_SIZE_RIGHT,
_NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT, _NET_WM_MOVERESIZE_SIZE_BOTTOM,
_NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT, _NET_WM_MOVERESIZE_SIZE_LEFT
};
switch (rc) {
case SDL_HITTEST_DRAGGABLE:
InitiateWindowMove(_this, data, &point);
return SDL_TRUE;
case SDL_HITTEST_RESIZE_TOPLEFT:
case SDL_HITTEST_RESIZE_TOP:
case SDL_HITTEST_RESIZE_TOPRIGHT:
case SDL_HITTEST_RESIZE_RIGHT:
case SDL_HITTEST_RESIZE_BOTTOMRIGHT:
case SDL_HITTEST_RESIZE_BOTTOM:
case SDL_HITTEST_RESIZE_BOTTOMLEFT:
case SDL_HITTEST_RESIZE_LEFT:
InitiateWindowResize(_this, data, &point, directions[rc - SDL_HITTEST_RESIZE_TOPLEFT]);
return SDL_TRUE;
default: return SDL_FALSE;
}
}
return SDL_FALSE;
}
static void
X11_DispatchEvent(_THIS)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display = videodata->display;
SDL_WindowData *data;
XEvent xevent;
int orig_event_type;
KeyCode orig_keycode;
XClientMessageEvent m;
int i;
SDL_zero(xevent); /* valgrind fix. --ryan. */
X11_XNextEvent(display, &xevent);
/* Save the original keycode for dead keys, which are filtered out by
the XFilterEvent() call below.
*/
orig_event_type = xevent.type;
if (orig_event_type == KeyPress || orig_event_type == KeyRelease) {
orig_keycode = xevent.xkey.keycode;
} else {
orig_keycode = 0;
}
/* filter events catchs XIM events and sends them to the correct handler */
if (X11_XFilterEvent(&xevent, None) == True) {
#if 0
printf("Filtered event type = %d display = %d window = %d\n",
xevent.type, xevent.xany.display, xevent.xany.window);
#endif
if (orig_keycode) {
/* Make sure dead key press/release events are sent */
/* Actually, don't do this because it causes double-delivery
of some keys on Ubuntu 14.04 (bug 2526)
SDL_Scancode scancode = videodata->key_layout[orig_keycode];
if (orig_event_type == KeyPress) {
SDL_SendKeyboardKey(SDL_PRESSED, scancode);
} else {
SDL_SendKeyboardKey(SDL_RELEASED, scancode);
}
*/
}
return;
}
/* Send a SDL_SYSWMEVENT if the application wants them */
if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) {
SDL_SysWMmsg wmmsg;
SDL_VERSION(&wmmsg.version);
wmmsg.subsystem = SDL_SYSWM_X11;
wmmsg.msg.x11.event = xevent;
SDL_SendSysWMEvent(&wmmsg);
}
#if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
if(xevent.type == GenericEvent) {
X11_HandleGenericEvent(videodata,xevent);
return;
}
#endif
#if 0
printf("type = %d display = %d window = %d\n",
xevent.type, xevent.xany.display, xevent.xany.window);
#endif
data = NULL;
if (videodata && videodata->windowlist) {
for (i = 0; i < videodata->numwindows; ++i) {
if ((videodata->windowlist[i] != NULL) &&
(videodata->windowlist[i]->xwindow == xevent.xany.window)) {
data = videodata->windowlist[i];
break;
}
}
}
if (!data) {
/* The window for KeymapNotify, etc events is 0 */
if (xevent.type == KeymapNotify) {
if (SDL_GetKeyboardFocus() != NULL) {
X11_ReconcileKeyboardState(_this);
}
} else if (xevent.type == MappingNotify) {
/* Has the keyboard layout changed? */
const int request = xevent.xmapping.request;
#ifdef DEBUG_XEVENTS
printf("window %p: MappingNotify!\n", data);
#endif
if ((request == MappingKeyboard) || (request == MappingModifier)) {
X11_XRefreshKeyboardMapping(&xevent.xmapping);
}
X11_UpdateKeymap(_this);
}
return;
}
switch (xevent.type) {
/* Gaining mouse coverage? */
case EnterNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: EnterNotify! (%d,%d,%d)\n", data,
xevent.xcrossing.x,
xevent.xcrossing.y,
xevent.xcrossing.mode);
if (xevent.xcrossing.mode == NotifyGrab)
printf("Mode: NotifyGrab\n");
if (xevent.xcrossing.mode == NotifyUngrab)
printf("Mode: NotifyUngrab\n");
#endif
SDL_SetMouseFocus(data->window);
if (!SDL_GetMouse()->relative_mode) {
SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
}
}
break;
/* Losing mouse coverage? */
case LeaveNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: LeaveNotify! (%d,%d,%d)\n", data,
xevent.xcrossing.x,
xevent.xcrossing.y,
xevent.xcrossing.mode);
if (xevent.xcrossing.mode == NotifyGrab)
printf("Mode: NotifyGrab\n");
if (xevent.xcrossing.mode == NotifyUngrab)
printf("Mode: NotifyUngrab\n");
#endif
if (!SDL_GetMouse()->relative_mode) {
SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
}
if (xevent.xcrossing.mode != NotifyGrab &&
xevent.xcrossing.mode != NotifyUngrab &&
xevent.xcrossing.detail != NotifyInferior) {
SDL_SetMouseFocus(NULL);
}
}
break;
/* Gaining input focus? */
case FocusIn:{
if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
/* Someone is handling a global hotkey, ignore it */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn (NotifyGrab/NotifyUngrab, ignoring)\n", data);
#endif
break;
}
if (xevent.xfocus.detail == NotifyInferior) {
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn (NotifierInferior, ignoring)\n", data);
#endif
break;
}
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn!\n", data);
#endif
if (!videodata->last_mode_change_deadline) /* no recent mode changes */
{
data->pending_focus = PENDING_FOCUS_NONE;
data->pending_focus_time = 0;
X11_DispatchFocusIn(_this, data);
}
else
{
data->pending_focus = PENDING_FOCUS_IN;
data->pending_focus_time = SDL_GetTicks() + PENDING_FOCUS_TIME;
}
}
break;
/* Losing input focus? */
case FocusOut:{
if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
/* Someone is handling a global hotkey, ignore it */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut (NotifyGrab/NotifyUngrab, ignoring)\n", data);
#endif
break;
}
if (xevent.xfocus.detail == NotifyInferior) {
/* We still have focus if a child gets focus */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut (NotifierInferior, ignoring)\n", data);
#endif
break;
}
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut!\n", data);
#endif
if (!videodata->last_mode_change_deadline) /* no recent mode changes */
{
data->pending_focus = PENDING_FOCUS_NONE;
data->pending_focus_time = 0;
X11_DispatchFocusOut(_this, data);
}
else
{
data->pending_focus = PENDING_FOCUS_OUT;
data->pending_focus_time = SDL_GetTicks() + PENDING_FOCUS_TIME;
}
}
break;
/* Key press? */
case KeyPress:{
KeyCode keycode = xevent.xkey.keycode;
KeySym keysym = NoSymbol;
char text[SDL_TEXTINPUTEVENT_TEXT_SIZE];
Status status = 0;
SDL_bool handled_by_ime = SDL_FALSE;
#ifdef DEBUG_XEVENTS
printf("window %p: KeyPress (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
#endif
#if 1
if (videodata->key_layout[keycode] == SDL_SCANCODE_UNKNOWN && keycode) {
int min_keycode, max_keycode;
X11_XDisplayKeycodes(display, &min_keycode, &max_keycode);
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
keysym = X11_XkbKeycodeToKeysym(display, keycode, 0, 0);
#else
keysym = X11_XKeycodeToKeysym(display, keycode, 0);
#endif
fprintf(stderr,
"The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL mailing list <sdl@libsdl.org> X11 KeyCode %d (%d), X11 KeySym 0x%lX (%s).\n",
keycode, keycode - min_keycode, keysym,
X11_XKeysymToString(keysym));
}
#endif
/* */
SDL_zero(text);
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_Xutf8LookupString(data->ic, &xevent.xkey, text, sizeof(text),
&keysym, &status);
}
#else
X11_XLookupString(&xevent.xkey, text, sizeof(text), &keysym, NULL);
#endif
#ifdef SDL_USE_IBUS
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
handled_by_ime = SDL_IBus_ProcessKeyEvent(keysym, keycode);
}
#endif
if (!handled_by_ime) {
SDL_SendKeyboardKey(SDL_PRESSED, videodata->key_layout[keycode]);
if(*text) {
SDL_SendKeyboardText(text);
}
}
}
break;
/* Key release? */
case KeyRelease:{
KeyCode keycode = xevent.xkey.keycode;
#ifdef DEBUG_XEVENTS
printf("window %p: KeyRelease (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
#endif
if (X11_KeyRepeat(display, &xevent)) {
/* We're about to get a repeated key down, ignore the key up */
break;
}
SDL_SendKeyboardKey(SDL_RELEASED, videodata->key_layout[keycode]);
}
break;
/* Have we been iconified? */
case UnmapNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: UnmapNotify!\n", data);
#endif
X11_DispatchUnmapNotify(data);
}
break;
/* Have we been restored? */
case MapNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: MapNotify!\n", data);
#endif
X11_DispatchMapNotify(data);
}
break;
/* Have we been resized or moved? */
case ConfigureNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: ConfigureNotify! (position: %d,%d, size: %dx%d)\n", data,
xevent.xconfigure.x, xevent.xconfigure.y,
xevent.xconfigure.width, xevent.xconfigure.height);
#endif
long border_left = 0;
long border_top = 0;
if (data->xwindow) {
Atom _net_frame_extents = X11_XInternAtom(display, "_NET_FRAME_EXTENTS", 0);
Atom type;
int format;
unsigned long nitems, bytes_after;
unsigned char *property;
if (X11_XGetWindowProperty(display, data->xwindow,
_net_frame_extents, 0, 16, 0,
XA_CARDINAL, &type, &format,
&nitems, &bytes_after, &property) == Success) {
if (type != None && nitems == 4)
{
border_left = ((long*)property)[0];
border_top = ((long*)property)[2];
}
X11_XFree(property);
}
}
if (xevent.xconfigure.x != data->last_xconfigure.x ||
xevent.xconfigure.y != data->last_xconfigure.y) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MOVED,
xevent.xconfigure.x - border_left,
xevent.xconfigure.y - border_top);
#ifdef SDL_USE_IBUS
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
/* Update IBus candidate list position */
SDL_IBus_UpdateTextRect(NULL);
}
#endif
}
if (xevent.xconfigure.width != data->last_xconfigure.width ||
xevent.xconfigure.height != data->last_xconfigure.height) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESIZED,
xevent.xconfigure.width,
xevent.xconfigure.height);
}
data->last_xconfigure = xevent.xconfigure;
}
break;
/* Have we been requested to quit (or another client message?) */
case ClientMessage:{
static int xdnd_version=0;
if (xevent.xclient.message_type == videodata->XdndEnter) {
SDL_bool use_list = xevent.xclient.data.l[1] & 1;
data->xdnd_source = xevent.xclient.data.l[0];
xdnd_version = (xevent.xclient.data.l[1] >> 24);
#ifdef DEBUG_XEVENTS
printf("XID of source window : %ld\n", data->xdnd_source);
printf("Protocol version to use : %d\n", xdnd_version);
printf("More then 3 data types : %d\n", (int) use_list);
#endif
if (use_list) {
/* fetch conversion targets */
SDL_x11Prop p;
X11_ReadProperty(&p, display, data->xdnd_source, videodata->XdndTypeList);
/* pick one */
data->xdnd_req = X11_PickTarget(display, (Atom*)p.data, p.count);
X11_XFree(p.data);
} else {
/* pick from list of three */
data->xdnd_req = X11_PickTargetFromAtoms(display, xevent.xclient.data.l[2], xevent.xclient.data.l[3], xevent.xclient.data.l[4]);
}
}
else if (xevent.xclient.message_type == videodata->XdndPosition) {
#ifdef DEBUG_XEVENTS
Atom act= videodata->XdndActionCopy;
if(xdnd_version >= 2) {
act = xevent.xclient.data.l[4];
}
printf("Action requested by user is : %s\n", X11_XGetAtomName(display , act));
#endif
/* reply with status */
memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = xevent.xclient.display;
m.window = xevent.xclient.data.l[0];
m.message_type = videodata->XdndStatus;
m.format=32;
m.data.l[0] = data->xwindow;
m.data.l[1] = (data->xdnd_req != None);
m.data.l[2] = 0; /* specify an empty rectangle */
m.data.l[3] = 0;
m.data.l[4] = videodata->XdndActionCopy; /* we only accept copying anyway */
X11_XSendEvent(display, xevent.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
X11_XFlush(display);
}
else if(xevent.xclient.message_type == videodata->XdndDrop) {
if (data->xdnd_req == None) {
/* say again - not interested! */
memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = xevent.xclient.display;
m.window = xevent.xclient.data.l[0];
m.message_type = videodata->XdndFinished;
m.format=32;
m.data.l[0] = data->xwindow;
m.data.l[1] = 0;
m.data.l[2] = None; /* fail! */
X11_XSendEvent(display, xevent.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
} else {
/* convert */
if(xdnd_version >= 1) {
X11_XConvertSelection(display, videodata->XdndSelection, data->xdnd_req, videodata->PRIMARY, data->xwindow, xevent.xclient.data.l[2]);
} else {
X11_XConvertSelection(display, videodata->XdndSelection, data->xdnd_req, videodata->PRIMARY, data->xwindow, CurrentTime);
}
}
}
else if ((xevent.xclient.message_type == videodata->WM_PROTOCOLS) &&
(xevent.xclient.format == 32) &&
(xevent.xclient.data.l[0] == videodata->_NET_WM_PING)) {
Window root = DefaultRootWindow(display);
#ifdef DEBUG_XEVENTS
printf("window %p: _NET_WM_PING\n", data);
#endif
xevent.xclient.window = root;
X11_XSendEvent(display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &xevent);
break;
}
else if ((xevent.xclient.message_type == videodata->WM_PROTOCOLS) &&
(xevent.xclient.format == 32) &&
(xevent.xclient.data.l[0] == videodata->WM_DELETE_WINDOW)) {
#ifdef DEBUG_XEVENTS
printf("window %p: WM_DELETE_WINDOW\n", data);
#endif
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_CLOSE, 0, 0);
break;
}
}
break;
/* Do we need to refresh ourselves? */
case Expose:{
#ifdef DEBUG_XEVENTS
printf("window %p: Expose (count = %d)\n", data, xevent.xexpose.count);
#endif
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_EXPOSED, 0, 0);
}
break;
case MotionNotify:{
SDL_Mouse *mouse = SDL_GetMouse();
if(!mouse->relative_mode || mouse->relative_mode_warp) {
#ifdef DEBUG_MOTION
printf("window %p: X11 motion: %d,%d\n", xevent.xmotion.x, xevent.xmotion.y);
#endif
SDL_SendMouseMotion(data->window, 0, 0, xevent.xmotion.x, xevent.xmotion.y);
}
}
break;
case ButtonPress:{
int xticks = 0, yticks = 0;
if (X11_IsWheelEvent(display,&xevent,&xticks, &yticks)) {
SDL_SendMouseWheel(data->window, 0, xticks, yticks, SDL_MOUSEWHEEL_NORMAL);
} else {
int button = xevent.xbutton.button;
if(button == Button1) {
if (ProcessHitTest(_this, data, &xevent)) {
break; /* don't pass this event on to app. */
}
}
else if(button > 7) {
/* X button values 4-7 are used for scrolling, so X1 is 8, X2 is 9, ...
=> subtract (8-SDL_BUTTON_X1) to get value SDL expects */
button -= (8-SDL_BUTTON_X1);
}
SDL_SendMouseButton(data->window, 0, SDL_PRESSED, button);
}
}
break;
case ButtonRelease:{
int button = xevent.xbutton.button;
if (button > 7) {
/* see explanation at case ButtonPress */
button -= (8-SDL_BUTTON_X1);
}
SDL_SendMouseButton(data->window, 0, SDL_RELEASED, button);
}
break;
case PropertyNotify:{
#ifdef DEBUG_XEVENTS
unsigned char *propdata;
int status, real_format;
Atom real_type;
unsigned long items_read, items_left;
char *name = X11_XGetAtomName(display, xevent.xproperty.atom);
if (name) {
printf("window %p: PropertyNotify: %s %s\n", data, name, (xevent.xproperty.state == PropertyDelete) ? "deleted" : "changed");
X11_XFree(name);
}
status = X11_XGetWindowProperty(display, data->xwindow, xevent.xproperty.atom, 0L, 8192L, False, AnyPropertyType, &real_type, &real_format, &items_read, &items_left, &propdata);
if (status == Success && items_read > 0) {
if (real_type == XA_INTEGER) {
int *values = (int *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_type == XA_CARDINAL) {
if (real_format == 32) {
Uint32 *values = (Uint32 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_format == 16) {
Uint16 *values = (Uint16 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_format == 8) {
Uint8 *values = (Uint8 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
}
} else if (real_type == XA_STRING ||
real_type == videodata->UTF8_STRING) {
printf("{ \"%s\" }\n", propdata);
} else if (real_type == XA_ATOM) {
Atom *atoms = (Atom *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
char *atomname = X11_XGetAtomName(display, atoms[i]);
if (atomname) {
printf(" %s", atomname);
X11_XFree(atomname);
}
}
printf(" }\n");
} else {
char *atomname = X11_XGetAtomName(display, real_type);
printf("Unknown type: %ld (%s)\n", real_type, atomname ? atomname : "UNKNOWN");
if (atomname) {
X11_XFree(atomname);
}
}
}
if (status == Success) {
X11_XFree(propdata);
}
#endif /* DEBUG_XEVENTS */
if (xevent.xproperty.atom == data->videodata->_NET_WM_STATE) {
/* Get the new state from the window manager.
Compositing window managers can alter visibility of windows
without ever mapping / unmapping them, so we handle that here,
because they use the NETWM protocol to notify us of changes.
*/
const Uint32 flags = X11_GetNetWMState(_this, xevent.xproperty.window);
const Uint32 changed = flags ^ data->window->flags;
if ((changed & SDL_WINDOW_HIDDEN) || (changed & SDL_WINDOW_FULLSCREEN)) {
if (flags & SDL_WINDOW_HIDDEN) {
X11_DispatchUnmapNotify(data);
} else {
X11_DispatchMapNotify(data);
}
}
if (changed & SDL_WINDOW_MAXIMIZED) {
if (flags & SDL_WINDOW_MAXIMIZED) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0);
} else {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0);
}
}
}
}
break;
/* Copy the selection from our own CUTBUFFER to the requested property */
case SelectionRequest: {
XSelectionRequestEvent *req;
XEvent sevent;
int seln_format;
unsigned long nbytes;
unsigned long overflow;
unsigned char *seln_data;
req = &xevent.xselectionrequest;
#ifdef DEBUG_XEVENTS
printf("window %p: SelectionRequest (requestor = %ld, target = %ld)\n", data,
req->requestor, req->target);
#endif
SDL_zero(sevent);
sevent.xany.type = SelectionNotify;
sevent.xselection.selection = req->selection;
sevent.xselection.target = None;
sevent.xselection.property = None;
sevent.xselection.requestor = req->requestor;
sevent.xselection.time = req->time;
if (X11_XGetWindowProperty(display, DefaultRootWindow(display),
X11_GetSDLCutBufferClipboardType(display), 0, INT_MAX/4, False, req->target,
&sevent.xselection.target, &seln_format, &nbytes,
&overflow, &seln_data) == Success) {
Atom XA_TARGETS = X11_XInternAtom(display, "TARGETS", 0);
if (sevent.xselection.target == req->target) {
X11_XChangeProperty(display, req->requestor, req->property,
sevent.xselection.target, seln_format, PropModeReplace,
seln_data, nbytes);
sevent.xselection.property = req->property;
} else if (XA_TARGETS == req->target) {
Atom SupportedFormats[] = { XA_TARGETS, sevent.xselection.target };
X11_XChangeProperty(display, req->requestor, req->property,
XA_ATOM, 32, PropModeReplace,
(unsigned char*)SupportedFormats,
SDL_arraysize(SupportedFormats));
sevent.xselection.property = req->property;
sevent.xselection.target = XA_TARGETS;
}
X11_XFree(seln_data);
}
X11_XSendEvent(display, req->requestor, False, 0, &sevent);
X11_XSync(display, False);
}
break;
case SelectionNotify: {
#ifdef DEBUG_XEVENTS
printf("window %p: SelectionNotify (requestor = %ld, target = %ld)\n", data,
xevent.xselection.requestor, xevent.xselection.target);
#endif
Atom target = xevent.xselection.target;
if (target == data->xdnd_req) {
/* read data */
SDL_x11Prop p;
X11_ReadProperty(&p, display, data->xwindow, videodata->PRIMARY);
if (p.format == 8) {
SDL_bool expect_lf = SDL_FALSE;
char *start = NULL;
char *scan = (char*)p.data;
char *fn;
char *uri;
int length = 0;
while (p.count--) {
if (!expect_lf) {
if (*scan == 0x0D) {
expect_lf = SDL_TRUE;
}
if (start == NULL) {
start = scan;
length = 0;
}
length++;
} else {
if (*scan == 0x0A && length > 0) {
uri = SDL_malloc(length--);
SDL_memcpy(uri, start, length);
uri[length] = '\0';
fn = X11_URIToLocal(uri);
if (fn) {
SDL_SendDropFile(fn);
}
SDL_free(uri);
}
expect_lf = SDL_FALSE;
start = NULL;
}
scan++;
}
}
X11_XFree(p.data);
/* send reply */
SDL_memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = display;
m.window = data->xdnd_source;
m.message_type = videodata->XdndFinished;
m.format = 32;
m.data.l[0] = data->xwindow;
m.data.l[1] = 1;
m.data.l[2] = videodata->XdndActionCopy;
X11_XSendEvent(display, data->xdnd_source, False, NoEventMask, (XEvent*)&m);
X11_XSync(display, False);
} else {
videodata->selection_waiting = SDL_FALSE;
}
}
break;
case SelectionClear: {
Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
if (xevent.xselectionclear.selection == XA_PRIMARY ||
(XA_CLIPBOARD != None && xevent.xselectionclear.selection == XA_CLIPBOARD)) {
SDL_SendClipboardUpdate();
}
}
break;
default:{
#ifdef DEBUG_XEVENTS
printf("window %p: Unhandled event %d\n", data, xevent.type);
#endif
}
break;
}
}
static void
X11_HandleFocusChanges(_THIS)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
int i;
if (videodata && videodata->windowlist) {
for (i = 0; i < videodata->numwindows; ++i) {
SDL_WindowData *data = videodata->windowlist[i];
if (data && data->pending_focus != PENDING_FOCUS_NONE) {
Uint32 now = SDL_GetTicks();
if (SDL_TICKS_PASSED(now, data->pending_focus_time)) {
if (data->pending_focus == PENDING_FOCUS_IN) {
X11_DispatchFocusIn(_this, data);
} else {
X11_DispatchFocusOut(_this, data);
}
data->pending_focus = PENDING_FOCUS_NONE;
}
}
}
}
}
/* Ack! X11_XPending() actually performs a blocking read if no events available */
static int
X11_Pending(Display * display)
{
/* Flush the display connection and look to see if events are queued */
X11_XFlush(display);
if (X11_XEventsQueued(display, QueuedAlready)) {
return (1);
}
/* More drastic measures are required -- see if X is ready to talk */
{
static struct timeval zero_time; /* static == 0 */
int x11_fd;
fd_set fdset;
x11_fd = ConnectionNumber(display);
FD_ZERO(&fdset);
FD_SET(x11_fd, &fdset);
if (select(x11_fd + 1, &fdset, NULL, NULL, &zero_time) == 1) {
return (X11_XPending(display));
}
}
/* Oh well, nothing is ready .. */
return (0);
}
void
X11_PumpEvents(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
if (data->last_mode_change_deadline) {
if (SDL_TICKS_PASSED(SDL_GetTicks(), data->last_mode_change_deadline)) {
data->last_mode_change_deadline = 0; /* assume we're done. */
}
}
/* Update activity every 30 seconds to prevent screensaver */
if (_this->suspend_screensaver) {
const Uint32 now = SDL_GetTicks();
if (!data->screensaver_activity ||
SDL_TICKS_PASSED(now, data->screensaver_activity + 30000)) {
X11_XResetScreenSaver(data->display);
#if SDL_USE_LIBDBUS
SDL_DBus_ScreensaverTickle();
#endif
data->screensaver_activity = now;
}
}
/* Keep processing pending events */
while (X11_Pending(data->display)) {
X11_DispatchEvent(_this);
}
#ifdef SDL_USE_IBUS
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
SDL_IBus_PumpEvents();
}
#endif
/* FIXME: Only need to do this when there are pending focus changes */
X11_HandleFocusChanges(_this);
}
void
X11_SuspendScreenSaver(_THIS)
{
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int dummy;
int major_version, minor_version;
#endif /* SDL_VIDEO_DRIVER_X11_XSCRNSAVER */
#if SDL_USE_LIBDBUS
if (SDL_DBus_ScreensaverInhibit(_this->suspend_screensaver)) {
return;
}
if (_this->suspend_screensaver) {
SDL_DBus_ScreensaverTickle();
}
#endif
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
if (SDL_X11_HAVE_XSS) {
/* X11_XScreenSaverSuspend was introduced in MIT-SCREEN-SAVER 1.1 */
if (!X11_XScreenSaverQueryExtension(data->display, &dummy, &dummy) ||
!X11_XScreenSaverQueryVersion(data->display,
&major_version, &minor_version) ||
major_version < 1 || (major_version == 1 && minor_version < 1)) {
return;
}
X11_XScreenSaverSuspend(data->display, _this->suspend_screensaver);
X11_XResetScreenSaver(data->display);
}
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.946101 | 1 | 0.946101 | game-dev | MEDIA | 0.304158 | game-dev | 0.985752 | 1 | 0.985752 |
jheruty/hscpp | 2,633 | src/ModuleManager.cpp | #include "hscpp/ModuleManager.h"
#include "hscpp/Log.h"
#include "hscpp/Util.h"
#include "hscpp/module/ModuleInterface.h"
hscpp::ModuleManager::ModuleManager()
{
Hscpp_GetModuleInterface()->SetIsSwapping(&m_bSwapping);
Hscpp_GetModuleInterface()->SetTrackersByKey(&m_TrackersByKey);
Hscpp_GetModuleInterface()->SetConstructorsByKey(&m_ConstructorsByKey);
m_ConstructorsByKey = Hscpp_GetModuleInterface()->GetModuleConstructorsByKey();
WarnDuplicateKeys(Hscpp_GetModuleInterface());
}
void hscpp::ModuleManager::SetAllocator(IAllocator* pAllocator)
{
m_pAllocator = pAllocator;
Hscpp_GetModuleInterface()->SetAllocator(pAllocator);
}
void hscpp::ModuleManager::SetGlobalUserData(void* pGlobalUserData)
{
m_pGlobalUserData = pGlobalUserData;
Hscpp_GetModuleInterface()->SetGlobalUserData(m_pGlobalUserData);
}
bool hscpp::ModuleManager::PerformRuntimeSwap(const fs::path& modulePath)
{
void* pModule = platform::LoadModule(modulePath);
if (pModule == nullptr)
{
log::Error() << HSCPP_LOG_PREFIX << "Failed to load module "
<< modulePath << ". " << log::LastOsError() << log::End();
return false;
}
auto GetModuleInterface = platform::GetModuleFunction<ModuleInterface*()>(
pModule, "Hscpp_GetModuleInterface");
if (GetModuleInterface == nullptr)
{
log::Error() << HSCPP_LOG_PREFIX << "Failed to load Hscpp_GetModuleInterface procedure. "
<< log::LastOsError() << log::End();
return false;
}
ModuleInterface* pModuleInterface = GetModuleInterface();
if (pModuleInterface == nullptr)
{
log::Error() << HSCPP_LOG_PREFIX << "Failed to get pointer to module interface." << log::End();
return false;
}
pModuleInterface->SetIsSwapping(&m_bSwapping);
pModuleInterface->SetTrackersByKey(&m_TrackersByKey);
pModuleInterface->SetConstructorsByKey(&m_ConstructorsByKey);
pModuleInterface->SetAllocator(m_pAllocator);
pModuleInterface->SetGlobalUserData(m_pGlobalUserData);
pModuleInterface->PerformRuntimeSwap();
WarnDuplicateKeys(pModuleInterface);
log::Build() << HSCPP_LOG_PREFIX << "Successfully performed runtime swap." << log::End();
return true;
}
void hscpp::ModuleManager::WarnDuplicateKeys(ModuleInterface* pModuleInterface)
{
auto duplicateKeys = pModuleInterface->GetDuplicateKeys();
for (const auto& duplicate : duplicateKeys)
{
log::Warning() << HSCPP_LOG_PREFIX << "Duplicate HSCPP_TRACK key detected (key="
<< duplicate.key << ", type=" << duplicate.type << log::End(").");
}
}
| 412 | 0.684996 | 1 | 0.684996 | game-dev | MEDIA | 0.593133 | game-dev | 0.871518 | 1 | 0.871518 |
leptos-rs/leptos | 19,409 | reactive_graph/src/owner.rs | //! The reactive ownership model, which manages effect cancellation, cleanups, and arena allocation.
#[cfg(feature = "hydration")]
use hydration_context::SharedContext;
use or_poisoned::OrPoisoned;
use rustc_hash::FxHashMap;
use std::{
any::{Any, TypeId},
cell::RefCell,
fmt::Debug,
mem,
sync::{Arc, RwLock, Weak},
};
mod arc_stored_value;
mod arena;
mod arena_item;
mod context;
mod storage;
mod stored_value;
use self::arena::Arena;
pub use arc_stored_value::ArcStoredValue;
#[cfg(feature = "sandboxed-arenas")]
pub use arena::sandboxed::Sandboxed;
#[cfg(feature = "sandboxed-arenas")]
use arena::ArenaMap;
use arena::NodeId;
pub use arena_item::*;
pub use context::*;
pub use storage::*;
#[allow(deprecated)] // allow exporting deprecated fn
pub use stored_value::{store_value, FromLocal, StoredValue};
/// A reactive owner, which manages
/// 1) the cancellation of [`Effect`](crate::effect::Effect)s,
/// 2) providing and accessing environment data via [`provide_context`] and [`use_context`],
/// 3) running cleanup functions defined via [`Owner::on_cleanup`], and
/// 4) an arena storage system to provide `Copy` handles via [`ArenaItem`], which is what allows
/// types like [`RwSignal`](crate::signal::RwSignal), [`Memo`](crate::computed::Memo), and so on to be `Copy`.
///
/// Every effect and computed reactive value has an associated `Owner`. While it is running, this
/// is marked as the current `Owner`. Whenever it re-runs, this `Owner` is cleared by calling
/// [`Owner::with_cleanup`]. This runs cleanup functions, cancels any [`Effect`](crate::effect::Effect)s created during the
/// last run, drops signals stored in the arena, and so on, because those effects and signals will
/// be re-created as needed during the next run.
///
/// When the owner is ultimately dropped, it will clean up its owned resources in the same way.
///
/// The "current owner" is set on the thread-local basis: whenever one of these reactive nodes is
/// running, it will set the current owner on its thread with [`Owner::with`] or [`Owner::set`],
/// allowing other reactive nodes implicitly to access the fact that it is currently the owner.
///
/// For a longer discussion of the ownership model, [see
/// here](https://book.leptos.dev/appendix_life_cycle.html).
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct Owner {
pub(crate) inner: Arc<RwLock<OwnerInner>>,
#[cfg(feature = "hydration")]
pub(crate) shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
}
impl Owner {
fn downgrade(&self) -> WeakOwner {
WeakOwner {
inner: Arc::downgrade(&self.inner),
#[cfg(feature = "hydration")]
shared_context: self.shared_context.as_ref().map(Arc::downgrade),
}
}
}
#[derive(Clone)]
struct WeakOwner {
inner: Weak<RwLock<OwnerInner>>,
#[cfg(feature = "hydration")]
shared_context: Option<Weak<dyn SharedContext + Send + Sync>>,
}
impl WeakOwner {
fn upgrade(&self) -> Option<Owner> {
self.inner.upgrade().map(|inner| {
#[cfg(feature = "hydration")]
let shared_context =
self.shared_context.as_ref().and_then(|sc| sc.upgrade());
Owner {
inner,
#[cfg(feature = "hydration")]
shared_context,
}
})
}
}
impl PartialEq for Owner {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
thread_local! {
static OWNER: RefCell<Option<WeakOwner>> = Default::default();
}
impl Owner {
/// Returns a unique identifier for this owner, which can be used to identify it for debugging
/// purposes.
///
/// Intended for debugging only; this is not guaranteed to be stable between runs.
pub fn debug_id(&self) -> usize {
Arc::as_ptr(&self.inner) as usize
}
/// Returns the list of parents, grandparents, and ancestors, with values corresponding to
/// [`Owner::debug_id`] for each.
///
/// Intended for debugging only; this is not guaranteed to be stable between runs.
pub fn ancestry(&self) -> Vec<usize> {
let mut ancestors = Vec::new();
let mut curr_parent = self
.inner
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|n| n.upgrade());
while let Some(parent) = curr_parent {
ancestors.push(Arc::as_ptr(&parent) as usize);
curr_parent = parent
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|n| n.upgrade());
}
ancestors
}
/// Creates a new `Owner` and registers it as a child of the current `Owner`, if there is one.
pub fn new() -> Self {
#[cfg(not(feature = "hydration"))]
let parent = OWNER.with(|o| {
o.borrow()
.as_ref()
.and_then(|o| o.upgrade())
.map(|o| Arc::downgrade(&o.inner))
});
#[cfg(feature = "hydration")]
let (parent, shared_context) = OWNER
.with(|o| {
o.borrow().as_ref().and_then(|o| o.upgrade()).map(|o| {
(Some(Arc::downgrade(&o.inner)), o.shared_context.clone())
})
})
.unwrap_or((None, None));
let this = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent: parent.clone(),
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena: parent
.as_ref()
.and_then(|parent| parent.upgrade())
.map(|parent| parent.read().or_poisoned().arena.clone())
.unwrap_or_default(),
paused: false,
})),
#[cfg(feature = "hydration")]
shared_context,
};
if let Some(parent) = parent.and_then(|n| n.upgrade()) {
parent
.write()
.or_poisoned()
.children
.push(Arc::downgrade(&this.inner));
}
this
}
/// Creates a new "root" context with the given [`SharedContext`], which allows sharing data
/// between the server and client.
///
/// Only one `SharedContext` needs to be created per request, and will be automatically shared
/// by any other `Owner`s created under this one.
#[cfg(feature = "hydration")]
#[track_caller]
pub fn new_root(
shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
) -> Self {
let this = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent: None,
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena: Default::default(),
paused: false,
})),
#[cfg(feature = "hydration")]
shared_context,
};
this.set();
this
}
/// Returns the parent of this `Owner`, if any.
///
/// None when:
/// - This is a root owner
/// - The parent has been dropped
pub fn parent(&self) -> Option<Owner> {
self.inner
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|p| p.upgrade())
.map(|inner| Owner {
inner,
#[cfg(feature = "hydration")]
shared_context: self.shared_context.clone(),
})
}
/// Creates a new `Owner` that is the child of the current `Owner`, if any.
pub fn child(&self) -> Self {
let parent = Some(Arc::downgrade(&self.inner));
let mut inner = self.inner.write().or_poisoned();
#[cfg(feature = "sandboxed-arenas")]
let arena = inner.arena.clone();
let paused = inner.paused;
let child = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent,
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena,
paused,
})),
#[cfg(feature = "hydration")]
shared_context: self.shared_context.clone(),
};
inner.children.push(Arc::downgrade(&child.inner));
child
}
/// Sets this as the current `Owner`.
pub fn set(&self) {
OWNER.with_borrow_mut(|owner| *owner = Some(self.downgrade()));
#[cfg(feature = "sandboxed-arenas")]
Arena::set(&self.inner.read().or_poisoned().arena);
}
/// Runs the given function with this as the current `Owner`.
pub fn with<T>(&self, fun: impl FnOnce() -> T) -> T {
// codegen optimisation:
fn inner_1(self_: &Owner) -> Option<WeakOwner> {
let prev = {
OWNER.with(|o| (*o.borrow_mut()).replace(self_.downgrade()))
};
#[cfg(feature = "sandboxed-arenas")]
Arena::set(&self_.inner.read().or_poisoned().arena);
prev
}
let prev = inner_1(self);
let val = fun();
// monomorphisation optimisation:
fn inner_2(prev: Option<WeakOwner>) {
OWNER.with(|o| {
*o.borrow_mut() = prev;
});
}
inner_2(prev);
val
}
/// Cleans up this owner, the given function with this as the current `Owner`.
pub fn with_cleanup<T>(&self, fun: impl FnOnce() -> T) -> T {
self.cleanup();
self.with(fun)
}
/// Cleans up this owner in the following order:
/// 1) Runs `cleanup` on all children,
/// 2) Runs all cleanup functions registered with [`Owner::on_cleanup`],
/// 3) Drops the values of any arena-allocated [`ArenaItem`]s.
pub fn cleanup(&self) {
self.inner.cleanup();
}
/// Registers a function to be run the next time the current owner is cleaned up.
///
/// Because the ownership model is associated with reactive nodes, each "decision point" in an
/// application tends to have a separate `Owner`: as a result, these cleanup functions often
/// fill the same need as an "on unmount" function in other UI approaches, etc.
pub fn on_cleanup(fun: impl FnOnce() + Send + Sync + 'static) {
if let Some(owner) = Owner::current() {
let mut inner = owner.inner.write().or_poisoned();
#[cfg(feature = "sandboxed-arenas")]
let fun = {
let arena = Arc::clone(&inner.arena);
move || {
Arena::set(&arena);
fun()
}
};
inner.cleanups.push(Box::new(fun));
}
}
fn register(&self, node: NodeId) {
self.inner.write().or_poisoned().nodes.push(node);
}
/// Returns the current `Owner`, if any.
pub fn current() -> Option<Owner> {
OWNER.with(|o| o.borrow().as_ref().and_then(|n| n.upgrade()))
}
/// Returns the [`SharedContext`] associated with this owner, if any.
#[cfg(feature = "hydration")]
pub fn shared_context(
&self,
) -> Option<Arc<dyn SharedContext + Send + Sync>> {
self.shared_context.clone()
}
/// Removes this from its state as the thread-local owner and drops it.
pub fn unset(self) {
OWNER.with_borrow_mut(|owner| {
if owner.as_ref().and_then(|n| n.upgrade()) == Some(self) {
mem::take(owner);
}
})
}
/// Returns the current [`SharedContext`], if any.
#[cfg(feature = "hydration")]
pub fn current_shared_context(
) -> Option<Arc<dyn SharedContext + Send + Sync>> {
OWNER.with(|o| {
o.borrow()
.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
})
}
/// Runs the given function, after indicating that the current [`SharedContext`] should be
/// prepared to handle any data created in the function.
#[cfg(feature = "hydration")]
pub fn with_hydration<T>(fun: impl FnOnce() -> T + 'static) -> T {
fn inner<T>(fun: Box<dyn FnOnce() -> T>) -> T {
provide_context(IsHydrating(true));
let sc = OWNER.with_borrow(|o| {
o.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
});
match sc {
None => fun(),
Some(sc) => {
let prev = sc.get_is_hydrating();
sc.set_is_hydrating(true);
let value = fun();
sc.set_is_hydrating(prev);
value
}
}
}
inner(Box::new(fun))
}
/// Runs the given function, after indicating that the current [`SharedContext`] should /// not handle data created in this function.
#[cfg(feature = "hydration")]
pub fn with_no_hydration<T>(fun: impl FnOnce() -> T + 'static) -> T {
fn inner<T>(fun: Box<dyn FnOnce() -> T>) -> T {
provide_context(IsHydrating(false));
let sc = OWNER.with_borrow(|o| {
o.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
});
match sc {
None => fun(),
Some(sc) => {
let prev = sc.get_is_hydrating();
sc.set_is_hydrating(false);
let value = fun();
sc.set_is_hydrating(prev);
value
}
}
}
inner(Box::new(fun))
}
/// Pauses the execution of side effects for this owner, and any of its descendants.
///
/// If this owner is the owner for an [`Effect`](crate::effect::Effect) or [`RenderEffect`](crate::effect::RenderEffect), this effect will not run until [`Owner::resume`] is called. All children of this effects are also paused.
///
/// Any notifications will be ignored; effects that are notified will paused will not run when
/// resumed, until they are notified again by a source after being resumed.
pub fn pause(&self) {
let mut stack = Vec::with_capacity(16);
stack.push(Arc::downgrade(&self.inner));
while let Some(curr) = stack.pop() {
if let Some(curr) = curr.upgrade() {
let mut curr = curr.write().or_poisoned();
curr.paused = true;
stack.extend(curr.children.iter().map(Weak::clone));
}
}
}
/// Whether this owner has been paused by [`Owner::pause`].
pub fn paused(&self) -> bool {
self.inner.read().or_poisoned().paused
}
/// Resumes side effects that have been paused by [`Owner::pause`].
///
/// All children will also be resumed.
///
/// This will *not* cause side effects that were notified while paused to run, until they are
/// notified again by a source after being resumed.
pub fn resume(&self) {
let mut stack = Vec::with_capacity(16);
stack.push(Arc::downgrade(&self.inner));
while let Some(curr) = stack.pop() {
if let Some(curr) = curr.upgrade() {
let mut curr = curr.write().or_poisoned();
curr.paused = false;
stack.extend(curr.children.iter().map(Weak::clone));
}
}
}
}
#[doc(hidden)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct IsHydrating(pub bool);
/// Registers a function to be run the next time the current owner is cleaned up.
///
/// Because the ownership model is associated with reactive nodes, each "decision point" in an
/// application tends to have a separate `Owner`: as a result, these cleanup functions often
/// fill the same need as an "on unmount" function in other UI approaches, etc.
///
/// This is an alias for [`Owner::on_cleanup`].
pub fn on_cleanup(fun: impl FnOnce() + Send + Sync + 'static) {
Owner::on_cleanup(fun)
}
#[derive(Default)]
pub(crate) struct OwnerInner {
pub parent: Option<Weak<RwLock<OwnerInner>>>,
nodes: Vec<NodeId>,
pub contexts: FxHashMap<TypeId, Box<dyn Any + Send + Sync>>,
pub cleanups: Vec<Box<dyn FnOnce() + Send + Sync>>,
pub children: Vec<Weak<RwLock<OwnerInner>>>,
#[cfg(feature = "sandboxed-arenas")]
arena: Arc<RwLock<ArenaMap>>,
paused: bool,
}
impl Debug for OwnerInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OwnerInner")
.field("parent", &self.parent)
.field("nodes", &self.nodes)
.field("contexts", &self.contexts)
.field("cleanups", &self.cleanups.len())
.finish()
}
}
impl Drop for OwnerInner {
fn drop(&mut self) {
for child in std::mem::take(&mut self.children) {
if let Some(child) = child.upgrade() {
child.cleanup();
}
}
for cleanup in mem::take(&mut self.cleanups) {
cleanup();
}
let nodes = mem::take(&mut self.nodes);
if !nodes.is_empty() {
#[cfg(not(feature = "sandboxed-arenas"))]
Arena::with_mut(|arena| {
for node in nodes {
_ = arena.remove(node);
}
});
#[cfg(feature = "sandboxed-arenas")]
{
let mut arena = self.arena.write().or_poisoned();
for node in nodes {
_ = arena.remove(node);
}
}
}
}
}
trait Cleanup {
fn cleanup(&self);
}
impl Cleanup for RwLock<OwnerInner> {
fn cleanup(&self) {
let (cleanups, nodes, children) = {
let mut lock = self.write().or_poisoned();
(
mem::take(&mut lock.cleanups),
mem::take(&mut lock.nodes),
mem::take(&mut lock.children),
)
};
for child in children {
if let Some(child) = child.upgrade() {
child.cleanup();
}
}
for cleanup in cleanups {
cleanup();
}
if !nodes.is_empty() {
#[cfg(not(feature = "sandboxed-arenas"))]
Arena::with_mut(|arena| {
for node in nodes {
_ = arena.remove(node);
}
});
#[cfg(feature = "sandboxed-arenas")]
{
let arena = self.read().or_poisoned().arena.clone();
let mut arena = arena.write().or_poisoned();
for node in nodes {
_ = arena.remove(node);
}
}
}
}
}
| 412 | 0.963538 | 1 | 0.963538 | game-dev | MEDIA | 0.702865 | game-dev | 0.892932 | 1 | 0.892932 |
anegostudios/vssurvivalmod | 2,249 | Inventory/InventoryQuern.cs | using System;
using Vintagestory.API.Common;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
#nullable disable
namespace Vintagestory.GameContent
{
/// <summary>
/// Inventory with one normal slot and one output slot
/// </summary>
public class InventoryQuern : InventoryBase, ISlotProvider
{
ItemSlot[] slots;
public ItemSlot[] Slots { get { return slots; } }
public InventoryQuern(string inventoryID, ICoreAPI api) : base(inventoryID, api)
{
// slot 0 = input
// slot 1 = output
slots = GenEmptySlots(2);
}
public InventoryQuern(string className, string instanceID, ICoreAPI api) : base(className, instanceID, api)
{
slots = GenEmptySlots(2);
}
public override int Count
{
get { return 2; }
}
public override ItemSlot this[int slotId]
{
get
{
if (slotId < 0 || slotId >= Count) return null;
return slots[slotId];
}
set
{
if (slotId < 0 || slotId >= Count) throw new ArgumentOutOfRangeException(nameof(slotId));
if (value == null) throw new ArgumentNullException(nameof(value));
slots[slotId] = value;
}
}
public override void FromTreeAttributes(ITreeAttribute tree)
{
slots = SlotsFromTreeAttributes(tree, slots);
}
public override void ToTreeAttributes(ITreeAttribute tree)
{
SlotsToTreeAttributes(slots, tree);
}
protected override ItemSlot NewSlot(int i)
{
return new ItemSlotSurvival(this);
}
public override float GetSuitability(ItemSlot sourceSlot, ItemSlot targetSlot, bool isMerge)
{
if (targetSlot == slots[0] && sourceSlot.Itemstack.Collectible.GrindingProps != null) return 4f;
return base.GetSuitability(sourceSlot, targetSlot, isMerge);
}
public override ItemSlot GetAutoPushIntoSlot(BlockFacing atBlockFace, ItemSlot fromSlot)
{
return slots[0];
}
}
}
| 412 | 0.917741 | 1 | 0.917741 | game-dev | MEDIA | 0.89523 | game-dev | 0.961298 | 1 | 0.961298 |
andr3wmac/Torque6 | 8,908 | plugins/PolyVox/PolyVoxCore/include/PolyVoxCore/DefaultMarchingCubesController.h | /*******************************************************************************
Copyright (c) 2005-2009 David Williams
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 __PolyVox_MarchingCubesController_H__
#define __PolyVox_MarchingCubesController_H__
#include <limits>
namespace PolyVox
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// This class provides a default implementation of a controller for the MarchingCubesSurfaceExtractor. It controls the behaviour of the
/// MarchingCubesSurfaceExtractor and provides the required properties from the underlying voxel type.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PolyVox does not enforce any requirements regarding what data must be present in a voxel, and instead allows any primitive or user-defined
/// type to be used. However, the Marching Cubes algorithm does have some requirents about the underlying data in that conceptually it operates
/// on a <i>density field</i>. In addition, the PolyVox implementation of the Marching Cubes algorithm also understands the idea of each voxel
/// having a material which is copied into the vertex data.
///
/// Because we want the MarchingCubesSurfaceExtractor to work on <i>any</i> voxel type, we use a <i>Marching Cubes controller</i> (passed as
/// a parameter of the MarchingCubesSurfaceExtractor) to expose the required properties. This parameter defaults to the DefaultMarchingCubesController.
/// The main implementation of this class is designed to work with primitives data types, and the class is also specialised for the Material,
/// Density and MaterialdensityPair classes.
///
/// If you create a custom class for your voxel data then you probably want to include a specialisation of DefaultMarchingCubesController,
/// though you don't have to if you don't want to use the Marching Cubes algorithm or if you prefer to define a seperate Marching Cubes controller
/// and pass it as an explicit parameter (rather than relying on the default).
///
/// For primitive types, the DefaultMarchingCubesController considers the value of the voxel to represent it's density and just returns a constant
/// for the material. So you can, for example, run the MarchingCubesSurfaceExtractor on a volume of floats or ints.
///
/// It is possible to customise the behaviour of the controller by providing a threshold value through the constructor. The extracted surface
/// will pass through the density value specified by the threshold, and so you should make sure that the threshold value you choose is between
/// the minimum and maximum values found in your volume data. By default it is in the middle of the representable range of the underlying type.
///
/// \sa MarchingCubesSurfaceExtractor
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename VoxelType>
class DefaultMarchingCubesController
{
public:
/// Used to inform the MarchingCubesSurfaceExtractor about which type it should use for representing densities.
typedef VoxelType DensityType;
/// Used to inform the MarchingCubesSurfaceExtractor about which type it should use for representing materials. We're using a float here
/// because this implementation always returns a constant value off 1.0f. PolyVox also uses floats to store the materials in the mesh vertices
/// but this is not really desirable on modern hardware. We'll probably come back to material representation in the future.
typedef float MaterialType;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// This version of the constructor takes no parameters and sets the threshold to the middle of the representable range of the underlying type.
/// For example, if the voxel type is 'uint8_t' then the representable range is 0-255, and the threshold will be set to 127. On the other hand,
/// if the voxel type is 'float' then the representable range is -FLT_MAX to FLT_MAX and the threshold will be set to zero.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DefaultMarchingCubesController(void)
{
m_tThreshold = ((std::numeric_limits<DensityType>::min)() + (std::numeric_limits<DensityType>::max)()) / 2;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// This version of the constructor allows you to set a custom threshold.
/// \param tThreshold The threshold to use.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DefaultMarchingCubesController(DensityType tThreshold)
{
m_tThreshold = tThreshold;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Converts the underlying voxel type into a density value.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The default implementation of this function just returns the voxel type directly and is suitable for primitives types. Specialisations of
/// this class can modify this behaviour.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DensityType convertToDensity(VoxelType voxel)
{
return voxel;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Converts the underlying voxel type into a material value.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The default implementation of this function just returns the constant '1'. There's not much else it can do, as it needs to work with primitive
/// types and the actual value of the type is already being considered to be the density. Specialisations of this class can modify this behaviour.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MaterialType convertToMaterial(VoxelType /*voxel*/)
{
return 1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Returns the density value which was passed to the constructor.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// As mentioned in the class description, the extracted surface will pass through the density value specified by the threshold, and so you
/// should make sure that the threshold value you choose is between the minimum and maximum values found in your volume data. By default it
///is in the middle of the representable range of the underlying type.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DensityType getThreshold(void)
{
return m_tThreshold;
}
private:
DensityType m_tThreshold;
};
}
#endif
| 412 | 0.638345 | 1 | 0.638345 | game-dev | MEDIA | 0.550577 | game-dev | 0.690834 | 1 | 0.690834 |
cwensley/pablodraw | 1,176 | Source/Pablo/Formats/Character/Actions/Undo.cs | using System;
using Eto.Forms;
using Eto;
namespace Pablo.Formats.Character.Actions
{
public class Undo : PabloCommand
{
public const string ActionID = "character_undo";
public new CharacterHandler Handler { get { return base.Handler as CharacterHandler; } }
public Undo (CharacterHandler handler)
: base(handler)
{
this.ID = ActionID;
this.MenuText = "&Undo";
this.ToolTip = "Undo the last action";
this.Shortcut = CommonModifier | Keys.Z;
}
public override bool Enabled {
get { return Handler.AllowKeyboardEditing && Handler.Undo.CanUndo && base.Enabled; }
set { base.Enabled = value; }
}
public override int CommandID {
get { return (int)NetCommands.Undo; }
}
public override Pablo.Network.UserLevel Level {
get { return Pablo.Network.UserLevel.Operator; }
}
protected override void Execute (CommandExecuteArgs args)
{
Handler.Undo.Undo ();
}
public override bool Send (Pablo.Network.SendCommandArgs args)
{
base.Send (args);
return true;
}
public override void Receive (Pablo.Network.ReceiveCommandArgs args)
{
base.Receive (args);
Handler.Undo.Undo(args);
}
}
}
| 412 | 0.585495 | 1 | 0.585495 | game-dev | MEDIA | 0.438616 | game-dev | 0.538068 | 1 | 0.538068 |
ElspethThePict/S2Absolute | 3,128 | SonLVLObjDefs/CPZ/RotatingStair.cs | using SonicRetro.SonLVL.API;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
namespace S2ObjectDefinitions.CPZ
{
class RotatingStair : ObjectDefinition
{
private readonly Sprite[] sprites = new Sprite[2];
private readonly Sprite[] debug = new Sprite[2];
private PropertySpec[] properties = new PropertySpec[2];
public override void Init(ObjectData data)
{
Sprite sprite;
if (LevelData.StageInfo.folder.EndsWith("Zone02"))
{
sprite = new Sprite(LevelData.GetSpriteSheet("CPZ/Objects3.gif").GetSection(1, 62, 32, 32), -16, -16);
}
else
{
sprite = new Sprite(LevelData.GetSpriteSheet("MBZ/Objects.gif").GetSection(130, 829, 32, 32), -16, -16);
}
sprites[0] = new Sprite(new Sprite(sprite, -48, -48),
new Sprite(sprite, -16, -16),
new Sprite(sprite, 16, 16),
new Sprite(sprite, 48, 48));
sprites[1] = new Sprite(new Sprite(sprite, -48, -48),
new Sprite(sprite, 48, 48));
BitmapBits bitmap = new BitmapBits(129, 129);
bitmap.DrawRectangle(6, 0, 96, 31, 31); // bottom right
bitmap.DrawRectangle(6, 96, 0, 31, 31); // top right
debug[1] = new Sprite(bitmap, -64, -64);
bitmap.DrawRectangle(6, 32, 64, 31, 31); // middle, bottom left
bitmap.DrawRectangle(6, 64, 32, 31, 31); // middle, top right
debug[0] = new Sprite(bitmap, -64, -64);
properties[0] = new PropertySpec("Direction", typeof(int), "Extended",
"Which way these stairs should rotate.", null, new Dictionary<string, int>
{
{ "Clockwise", 0 },
{ "Counter-Clockwise", 1 }
},
(obj) => obj.PropertyValue & 1,
(obj, value) => obj.PropertyValue = (byte)((obj.PropertyValue & ~1) | (int)value));
properties[1] = new PropertySpec("Size", typeof(int), "Extended",
"How many blocks this set of stairs should have.", null, new Dictionary<string, int>
{
{ "4 Blocks", 0 },
{ "2 Blocks", 2 }
},
(obj) => obj.PropertyValue & 2,
(obj, value) => obj.PropertyValue = (byte)((obj.PropertyValue & ~2) | (int)value));
}
public override ReadOnlyCollection<byte> Subtypes
{
get { return new ReadOnlyCollection<byte>(new byte[] {0, 1, 2, 3}); }
}
public override PropertySpec[] CustomProperties
{
get { return properties; }
}
public override string SubtypeName(byte subtype)
{
switch (subtype & 3)
{
default:
case 0:
return "4 Blocks, Clockwise";
case 1:
return "4 Blocks, Counter-Clockwise";
case 2:
return "2 Blocks, Clockwise";
case 3:
return "2 Blocks, Counter-Clockwise";
}
}
public override Sprite Image
{
get { return sprites[0]; }
}
public override Sprite SubtypeImage(byte subtype)
{
return sprites[(subtype & 2) >> 1];
}
public override Sprite GetSprite(ObjectEntry obj)
{
return sprites[(obj.PropertyValue & 2) >> 1];
}
public override Sprite GetDebugOverlay(ObjectEntry obj)
{
return debug[(obj.PropertyValue & 2) >> 1];
}
}
} | 412 | 0.679771 | 1 | 0.679771 | game-dev | MEDIA | 0.769285 | game-dev,graphics-rendering | 0.848361 | 1 | 0.848361 |
sdcb/FlysEngine | 16,856 | FlysEngine.Desktop/linqpad-samples/BlockBreaker.linq | <Query Kind="Program">
<Reference><RuntimeDirectory>\Accessibility.dll</Reference>
<Reference><RuntimeDirectory>\WPF\PresentationCore.dll</Reference>
<Reference><RuntimeDirectory>\WPF\PresentationFramework.dll</Reference>
<Reference><RuntimeDirectory>\WPF\PresentationUI.dll</Reference>
<Reference><RuntimeDirectory>\WPF\ReachFramework.dll</Reference>
<Reference><RuntimeDirectory>\System.Configuration.dll</Reference>
<Reference><RuntimeDirectory>\System.Deployment.dll</Reference>
<Reference><RuntimeDirectory>\WPF\System.Printing.dll</Reference>
<Reference><RuntimeDirectory>\System.Runtime.Serialization.Formatters.Soap.dll</Reference>
<Reference><RuntimeDirectory>\System.Security.dll</Reference>
<Reference><RuntimeDirectory>\System.Windows.Forms.dll</Reference>
<Reference><RuntimeDirectory>\System.Xaml.dll</Reference>
<Reference><RuntimeDirectory>\WPF\UIAutomationProvider.dll</Reference>
<Reference><RuntimeDirectory>\WPF\UIAutomationTypes.dll</Reference>
<Reference><RuntimeDirectory>\WPF\WindowsBase.dll</Reference>
<NuGetReference>AdamsLair.FarseerDuality</NuGetReference>
<NuGetReference>FlysEngine</NuGetReference>
<NuGetReference>FlysEngine.Desktop</NuGetReference>
<Namespace>Direct2D = Vortice.Direct2D1</Namespace>
<Namespace>DirectWrite = Vortice.DirectWrite</Namespace>
<Namespace>EngineShapes = FarseerPhysics.Collision.Shapes</Namespace>
<Namespace>FarseerPhysics.Common</Namespace>
<Namespace>FarseerPhysics.Dynamics</Namespace>
<Namespace>FlysEngine</Namespace>
<Namespace>FlysEngine.Desktop</Namespace>
<Namespace>FlysEngine.Managers</Namespace>
<Namespace>System.Drawing</Namespace>
<Namespace>System.Numerics</Namespace>
<Namespace>System.Windows.Forms</Namespace>
<Namespace>Vortice.Mathematics</Namespace>
<Namespace>Xna = Duality</Namespace>
<Namespace>Vortice.UIAnimation</Namespace>
</Query>
static class C
{
public const float DefaultSpeed = 200.0f;
public const float Restitution = 1.0f, Friction = 0.0f, Density = 1.0f;
public const float BlockWidth = Width / 9f, BlockHeight = Width / 30, Offset = (Width - BlockWidth * 7) / 8, BallR = Width / 40;
public const float Width = 300.0f, Height = Width * 0.9f;
public const float SimDisScale = 64.0f;
public static float ToSim(float x) => x / SimDisScale;
public static float ToDis(float x) => x * SimDisScale;
}
class Game : RenderWindow
{
public World World = new World(Xna.Vector2.Zero);
public Dictionary<Guid, Sprite> Blocks = new Dictionary<System.Guid, Sprite>();
public Sprite Breaker, Ball, Walls, FailureArea;
public IEnumerable<Sprite> Sprites => Blocks.Values.Concat(new[] { Breaker, Ball, Walls, FailureArea });
public GameState State { get; set; } = GameState.BallOnBreaker;
private Direct2D.ID2D1Brush BallBrush;
private List<Direct2D.ID2D1Brush> RectBrushes;
public Matrix3x2 GlobalTransform { get; set; }
protected override void OnLoad(EventArgs e)
{
Text = "Block Breaker";
base.OnLoad(e);
for (var row = 0; row < 4; ++row)
{
for (var col = 0; col < 7; ++col)
{
var block = new Sprite(this)
{
Name = $"Blocker-{row}-{col}",
Position = new Vector2(
C.Offset + col * (C.Offset + C.BlockWidth),
C.Offset + row * (C.BlockHeight + C.Offset)),
};
block.Shapes = new List<UserQuery.Shape>
{
new RectangleShape
{
Size = new Vector2(C.BlockWidth, C.BlockHeight)
},
};
block.Body.BodyType = BodyType.Static;
block.AddBehavior(new BlockBehavior(GetRectBrushByHitPoint, 4 - row, block));
Blocks.Add(block.Id, block);
}
}
Breaker = CreateBreaker();
Ball = CreateBallAtTopOf(Breaker);
Walls = CreateBorder();
FailureArea = CreateBottom();
World.ProcessChanges();
}
protected override void OnCreateDeviceResources()
{
BallBrush = XResource.RenderTarget.CreateRadialGradientBrush(
new Direct2D.RadialGradientBrushProperties { RadiusX = C.BallR, RadiusY = C.BallR, },
XResource.RenderTarget.CreateGradientStopCollection(new[]
{
new Direct2D.GradientStop{ Color = Colors.White, Position = 0.0f},
new Direct2D.GradientStop{ Color = Colors.Black, Position = 1.0f},
}));
RectBrushes = new[] { Colors.Yellow, Colors.Orange, Colors.Green, Colors.Blue, Colors.Purple }.Select(c => (Direct2D.ID2D1Brush)
XResource.RenderTarget.CreateLinearGradientBrush(
new Direct2D.LinearGradientBrushProperties { StartPoint = new Vector2(), EndPoint = new Vector2(C.BlockWidth, C.BlockHeight) },
XResource.RenderTarget.CreateGradientStopCollection(new[]
{
new Direct2D.GradientStop{ Color = c, Position = 0.1f},
new Direct2D.GradientStop{ Color = Colors.White, Position = 0.7f},
new Direct2D.GradientStop{ Color = c, Position = 1.0f},
}))).ToList();
}
protected override void OnReleaseDeviceResources()
{
BallBrush.Dispose();
foreach (var brush in RectBrushes) brush.Dispose();
RectBrushes.Clear();
}
private Direct2D.ID2D1Brush GetRectBrushByHitPoint(int hitpoint)
{
if (hitpoint <= 4) return RectBrushes[hitpoint - 1];
return RectBrushes[4];
}
Sprite CreateBorder()
{
var lines = new[]
{
new []{0, 0, C.Width, 0},
new []{C.Width, 0, C.Width, C.Height},
new []{0, 0, 0, C.Height},
};
var sprite = new Sprite(this)
{
Name = "Border",
Shapes = lines.Select(x =>
(Shape)new EdgeShape(new Vector2(x[0], x[1]), new Vector2(x[2], x[3]))).ToList()
};
sprite.Body.BodyType = BodyType.Kinematic;
return sprite;
}
Sprite CreateBottom()
{
var sprite = new Sprite(this)
{
Name = "Bottom",
Shapes = new List<Shape>
{
(Shape)new EdgeShape(new Vector2(0, C.Height), new Vector2(C.Width, C.Height))
},
};
sprite.Body.BodyType = BodyType.Static;
sprite.Hit += (o, e) =>
{
if (e == Ball && State == GameState.Started)
{
Ball.Body.LinearVelocity = ToXnaVector2(Vector2.Zero);
State = GameState.Failure;
$"Mark as failure".Dump();
}
};
return sprite;
}
Sprite CreateBallAtTopOf(Sprite breaker)
{
var ball = new Sprite(this)
{
Name = $"Ball",
Shapes = new List<UserQuery.Shape>
{
new CircleShape(C.BallR)
},
};
ball.Body.BodyType = BodyType.Dynamic;
ball.AddBehavior(new BallBehavior(() => BallBrush, ball));
SetBallOnBreaker(ball, breaker);
return ball;
}
Sprite CreateBreaker()
{
var sprite = new Sprite(this)
{
Name = $"Breaker",
Position = new Vector2(C.Width / 2 - C.BlockWidth * 1.5f / 2, C.Height - C.BallR * 3), // Center
Center = new Vector2(C.BlockWidth * 1.5f / 2, 0),
Shapes = new List<UserQuery.Shape>
{
new RectangleShape
{
Size = new Vector2(C.BlockWidth * 1.5f, C.BlockHeight),
}
},
};
sprite.Body.BodyType = BodyType.Kinematic;
sprite.AddBehavior(new BreakerBehavior(GetRectBrushByHitPoint, 5, sprite));
return sprite;
}
protected override void OnUpdateLogic(float lastFrameTimeInSecond)
{
base.OnUpdateLogic(lastFrameTimeInSecond);
foreach (var sprite in Sprites) sprite.OnUpdate(RenderTimer);
World.Step(lastFrameTimeInSecond);
var toDestroyIds = Blocks.Values.Where(x => x.IsDestroying).Select(x => x.Id).ToList();
foreach (var id in toDestroyIds)
{
World.RemoveBody(Blocks[id].Body);
Blocks.Remove(id);
}
World.ProcessChanges();
}
protected override void OnDraw(Direct2D.ID2D1DeviceContext ctx)
{
ctx.Clear(Colors.CornflowerBlue);
ctx.DrawText($"FPS: {RenderTimer.FramesPerSecond:F1}",
XResource.TextFormats[10.0f],
new Rect(0, 0, ctx.Size.Width, ctx.Size.Height),
XResource.GetColor(Colors.Red));
float scale = ctx.Size.Height / C.Height;
ctx.Transform = Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation((ctx.Size.Width - C.Width * scale) / 2, 0);
GlobalTransform = ctx.Transform;
foreach (var sprite in Sprites) sprite.Draw(ctx);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (State == GameState.BallOnBreaker)
{
SetBallOnBreaker(Ball, Breaker);
}
Matrix3x2.Invert(GlobalTransform, out Matrix3x2 inverted);
Vector2 invertPoint = Vector2.Transform(new Vector2(e.X, e.Y), inverted);
Breaker.QueryBehavior<BreakerBehavior>().MoveX(invertPoint.X);
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (State == GameState.BallOnBreaker)
{
Ball.Body.LinearVelocity = ToXnaVector2(new Vector2(
(float)Math.Sin(Breaker.Rotation) * C.DefaultSpeed,
(float)-Math.Cos(Breaker.Rotation) * C.DefaultSpeed));
State = GameState.Started;
}
else if (State == GameState.Failure || State == GameState.Started)
{
SetBallOnBreaker(Ball, Breaker);
Ball.Body.LinearVelocity = ToXnaVector2(Vector2.Zero);
State = GameState.BallOnBreaker;
}
}
}
public abstract class Shape
{
public Vector2 Center { get; set; }
public Vector2 Offset { get; set; }
public abstract bool TestPoint(Vector2 point);
public abstract EngineShapes.Shape ToEngineShape();
public abstract void Draw(
Direct2D.ID2D1DeviceContext renderTarget,
Direct2D.ID2D1Brush brush);
public static bool TestPoint(IEnumerable<Shape> shapes, Vector2 point)
{
return shapes.Any(shape => shape.TestPoint(point));
}
public static void CreateFixtures(
IEnumerable<Shape> shapes,
Body body)
{
foreach (var shape in shapes)
{
var engineShape = shape.ToEngineShape();
var fixture = body.CreateFixture(engineShape);
fixture.Restitution = C.Restitution;
fixture.Friction = C.Friction;
}
}
}
public class RectangleShape : Shape
{
public Vector2 Size { get; set; }
public Rect Rect => new (Offset.X, Offset.Y, Size.X, Size.Y);
public override void Draw(Direct2D.ID2D1DeviceContext renderTarget, Direct2D.ID2D1Brush brush) => renderTarget.FillRectangle(Rect, brush);
public override bool TestPoint(Vector2 point) => Rect.Contains(point);
public override EngineShapes.Shape ToEngineShape()
{
var offset = Offset - Center;
var shape = new EngineShapes.PolygonShape(C.Density);
shape.Set(new Vertices(new[]
{
ToXnaVector2(offset),
ToXnaVector2(offset + new Vector2(Size.X, 0)),
ToXnaVector2(offset + Size),
ToXnaVector2(offset + new Vector2(0, Size.Y)),
}));
return shape;
}
}
public class CircleShape : Shape
{
public CircleShape(float r) { R = r; }
public float R { get; private set; }
public Direct2D.Ellipse Ellipse => new Direct2D.Ellipse(Center + Offset, R, R);
public CircleShape Clone()
{
return new CircleShape(R)
{
Offset = Offset,
Center = Center,
};
}
public override void Draw(Direct2D.ID2D1DeviceContext renderTarget, Direct2D.ID2D1Brush brush)
{
renderTarget.DrawEllipse(Ellipse, brush, 1.0f);
}
public override bool TestPoint(Vector2 point)
{
return Vector2.DistanceSquared(Center + Offset, point)
< R * R;
}
public override EngineShapes.Shape ToEngineShape()
{
return new EngineShapes.CircleShape(
C.ToSim(R), C.Density);
}
}
public class EdgeShape : Shape
{
public Vector2 P1 { get; set; }
public Vector2 P2 { get; set; }
public EdgeShape(Vector2 p1, Vector2 p2)
{
P1 = p1;
P2 = p2;
}
public EdgeShape Clone()
{
return new EdgeShape(P1, P2)
{
Offset = Offset,
Center = Center,
};
}
public override void Draw(Direct2D.ID2D1DeviceContext renderTarget, Direct2D.ID2D1Brush brush)
{
renderTarget.DrawLine(P1, P2, brush);
}
public override bool TestPoint(Vector2 point) => false;
public override EngineShapes.Shape ToEngineShape()
{
return new EngineShapes.EdgeShape(ToXnaVector2(P1), ToXnaVector2(P2));
}
}
static void SetBallOnBreaker(Sprite ball, Sprite breaker)
{
ball.Position = new Vector2(
breaker.Position.X + (breaker.Shapes[0] as RectangleShape).Size.X / 2,
breaker.Position.Y - C.BallR);
}
static Vector2 ToVector2(Xna.Vector2 xnaVector2) => new Vector2
{
X = C.ToDis(xnaVector2.X),
Y = C.ToDis(xnaVector2.Y),
};
static Xna.Vector2 ToXnaVector2(Vector2 vector2) => new Xna.Vector2
{
X = C.ToSim(vector2.X),
Y = C.ToSim(vector2.Y),
};
class Sprite
{
public Guid Id { get; } = Guid.NewGuid();
public string Name { get; set;}
public Game Game { get; }
protected XResource XResource { get; }
public Vector2 Center { get; set;}
public event EventHandler<Sprite> Hit;
public Dictionary<Type, Behavior> Behaviors { get; } = new Dictionary<Type, Behavior>();
public T QueryBehavior<T>() where T : Behavior
{
var type = typeof(T);
if (Behaviors.ContainsKey(type)) return (T)Behaviors[type];
return null;
}
public void AddBehavior(Behavior behavior) => Behaviors.Add(behavior.GetType(), behavior);
public Sprite(Game game)
{
Game = game;
XResource = game.XResource;
Body = new Body(game.World);
Body.UserData = this;
}
public Vector2 Position
{
get => ToVector2(Body.Position);
set => Body.Position = ToXnaVector2(value);
}
public float Rotation
{
get => Body.Rotation;
set => Body.Rotation = value;
}
public bool SuppressDefaultDraw { get; set; }
public Matrix3x2 Transform => Matrix3x2.CreateRotation(Rotation, Center) * Matrix3x2.CreateTranslation(Position);
private List<Shape> _shapes;
public List<Shape> Shapes
{
get => _shapes;
set
{
_shapes = value;
foreach (var fixture in Body.FixtureList.ToList())
Body.DestroyFixture(fixture);
Shape.CreateFixtures(value, Body);
}
}
public readonly Body Body;
public bool IsDestroying { get; set; }
public virtual void OnUpdate(RenderTimer timer)
{
foreach (var behavior in Behaviors.Values) behavior.Update(timer);
if (Hit != null && Body.Enabled)
{
foreach (var contact in GetContacts())
{
Hit(this, contact);
}
IEnumerable<Sprite> GetContacts()
{
var c = Body.ContactList;
while (c != null)
{
if (c.Contact.IsTouching())
{
yield return (Sprite)c.Other.UserData;
}
c = c.Next;
}
}
}
}
public void Draw(Direct2D.ID2D1DeviceContext ctx)
{
var old = ctx.Transform;
ctx.Transform = Transform * old;
foreach (var behavior in Behaviors.Values) behavior.Draw(ctx);
if (!SuppressDefaultDraw) foreach (var shape in Shapes) shape.Draw(ctx, XResource.GetColor(Colors.Yellow));
ctx.Transform = old;
}
public override string ToString() => $"{Name}@{Position}";
}
class RectColorBehavior : Behavior
{
public int HitPoint { get; set; }
public Func<int, Direct2D.ID2D1Brush> BrushGetter;
public RectColorBehavior(Func<int, Direct2D.ID2D1Brush> brushGetter, int hitPoint, Sprite sprite) : base(sprite)
{
HitPoint = hitPoint;
BrushGetter = brushGetter;
Sprite.SuppressDefaultDraw = true;
}
public override void Draw(Direct2D.ID2D1DeviceContext ctx)
{
var rect = (RectangleShape)Sprite.Shapes[0];
ctx.FillRectangle(rect.Rect, BrushGetter(HitPoint));
ctx.DrawRectangle(rect.Rect, Sprite.Game.XResource.GetColor(Colors.Black), 0.5f);
}
}
class BlockBehavior : RectColorBehavior
{
public BlockBehavior(Func<int, Direct2D.ID2D1Brush> brushGetter, int hitPoint, Sprite sprite)
: base(brushGetter, hitPoint, sprite)
{
sprite.Hit += OnHit;
}
void OnHit(object sender, Sprite e)
{
HitPoint--;
if (HitPoint == 0) Sprite.IsDestroying = true;
}
}
class BreakerBehavior : RectColorBehavior
{
float _dx = 0;
IUIAnimationVariable2 _a;
public BreakerBehavior(Func<int, Direct2D.ID2D1Brush> brushGetter, int hitPoint, Sprite sprite)
: base(brushGetter, hitPoint, sprite)
{
}
public override void Update(RenderTimer timer)
{
base.Update(timer);
Sprite.Rotation = GetCurrentRotation();
float calcRotation = -_dx / C.Width * 3 * (float)Math.PI;
if (Math.Abs(calcRotation) > Math.Abs(Sprite.Rotation))
{
if (_a != null) _a.Dispose();
_a = Sprite.Game.XResource.CreateAnimation(calcRotation, 0, 1.0);
}
_dx = 0;
}
float GetCurrentRotation() => _a == null ? 0 : (float)_a.Value;
public void MoveX(float x)
{
_dx = Sprite.Position.X - x;
Sprite.Position = new Vector2(x, Sprite.Position.Y);
}
}
class BallBehavior : Behavior
{
Func<Direct2D.ID2D1Brush> BallBrushGetter;
public BallBehavior(Func<Direct2D.ID2D1Brush> ballBrushGetter, Sprite sprite) : base(sprite)
{
BallBrushGetter = ballBrushGetter;
Sprite.SuppressDefaultDraw = true;
}
public override void Draw(Direct2D.ID2D1DeviceContext ctx)
{
var shape = (CircleShape)Sprite.Shapes[0];
ctx.FillEllipse(shape.Ellipse, BallBrushGetter());
}
}
abstract class Behavior
{
public Sprite Sprite { get; }
public Behavior(Sprite sprite) { Sprite = sprite; }
public virtual void Update(RenderTimer timer) { }
public virtual void Draw(Direct2D.ID2D1DeviceContext ctx) { }
}
enum GameState
{
BallOnBreaker,
Started,
Failure,
}
static void Main()
{
FarseerPhysics.Settings.VelocityThreshold = 0.0f;
using (var window = new Game())
{
RenderLoop.Run(window, () => window.Render(1, 0));
}
} | 412 | 0.95927 | 1 | 0.95927 | game-dev | MEDIA | 0.628024 | game-dev,graphics-rendering | 0.801946 | 1 | 0.801946 |
onyxbits/TextFiction | 2,273 | src/de/onyxbits/textfiction/zengine/IFFInputFile.java | package de.onyxbits.textfiction.zengine;
import java.io.*;
import java.util.*;
public class IFFInputFile extends IFFFile {
private Stack openchunkends;
public IFFInputFile(File file) throws IOException {
super(file, "r");
openchunkends = new Stack();
}
public IFFInputFile(String name) throws IOException {
super(name, "r");
openchunkends = new Stack();
}
public synchronized IFFChunkInfo readChunkInfo() throws IOException {
IFFChunkInfo result = new IFFChunkInfo();
byte chunktype[] = new byte[4];
long chunkbegin;
read(chunktype, 0, 4);
chunkbegin = getFilePointer();
result.chunktype = new String(chunktype, 0);
result.chunklength = readInt();
openchunks.push(new Long(chunkbegin));
openchunkends.push(new Long(getFilePointer() + result.chunklength));
return result;
}
public synchronized IFFChunkInfo skipToChunk(String type) throws IOException,
IFFChunkNotFoundException {
IFFChunkInfo chunkinfo;
if (getFilePointer() >= ((Long) openchunkends.peek()).longValue())
throw new IFFChunkNotFoundException("Chunk " + type
+ " not found at current level");
chunkinfo = readChunkInfo();
while (!chunkinfo.chunktype.equals(type)) {
closeChunk();
if (getFilePointer() >= ((Long) openchunkends.peek()).longValue())
throw new IFFChunkNotFoundException("Chunk " + type
+ " not found at current level");
chunkinfo = readChunkInfo();
}
return chunkinfo;
}
public synchronized String readFORM() throws IOException {
IFFChunkInfo formchunkinfo;
byte subtype[] = new byte[4];
formchunkinfo = readChunkInfo();
if (formchunkinfo.chunktype.equals("FORM")) {
read(subtype, 0, 4);
}
else {
// throw new Exception("That's not a FORM!");
}
return new String(subtype, 0);
}
public synchronized void closeChunk() throws IOException {
long chunkend;
chunkend = (((Long) openchunkends.pop()).longValue() + 1) & ~1L;
openchunks.pop();
// doing the seek last ensures exceptions leave stacks consistent
seek(chunkend);
}
public synchronized void close() throws IOException {
while (!openchunks.empty()) {
try {
closeChunk();
}
catch (IOException ioexcpt) {
// Ignore seek errors probably caused by opening a bad chunk
}
}
super.close();
}
}
| 412 | 0.786778 | 1 | 0.786778 | game-dev | MEDIA | 0.501435 | game-dev | 0.594567 | 1 | 0.594567 |
dreemproject/dreemgl | 2,658 | examples/selection.js | /* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
Copyright 2015-2016 Teeming Society. 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.*/
//Pure JS based composition
define.class(function($server$, composition, $ui$, screen, cadgrid, view, icon, label){
define.class(this, "selectorrect", view, function(){
this.name = 'selectorrect'
this.bordercolorfn = function(pos){
var check = (int(mod(0.05 * (gl_FragCoord.x + gl_FragCoord.y + time * 40.),2.)) == 1)? 1.0: 0.0
return vec4(check * vec3(0.8), 1)
}
this.bordercolor = vec4(1, 1, 1, 0.4)
this.borderwidth = 5
this.bgcolor = vec4(1, 1, 1, 0.07)
this.borderradius = 2
this.position = "absolute"
this.visible = false
})
this.style = {
icon: {
fgcolor:"red",
margin:40,
fontsize:60
}
}
this.render = function(){ return [
screen({name:'default', clearcolor:vec4('black')},
cadgrid({
flex:1,
justifycontent:"center",
alignitems:"center",
pointermove:function(event){
var select = this.find('selectorrect');
select.visible = true;
select.pos = vec2(event.min[0], event.min[1]);
select.size = vec2(event.max[0] - event.min[0], event.max[1] - event.min[1])
},
pointerend:function(event){
for (var i=0;i< this.children.length;i++) {
var child = this.children[i];
child.bgcolor = "transparent";
}
var select = this.find('selectorrect');
var rect = vec4(event.min[0], event.min[1], event.max[0] - event.min[0], event.max[1] - event.min[1])
var selection = this.screen.childrenInRect(rect, [select]);
for (var i=0;i< selection.length;i++) {
var selected = selection[i];
if (selected.noselect !== true) {
selected.bgcolor = "green";
}
}
select.visible = false
}
},
label({noselect:true, text:"Drag the selection box around the objects below to demonstrate selection", fgcolor:"blue"}),
icon({icon:"star-o", bgcolor:"transparent"}), icon({icon:"circle-o", bgcolor:"transparent"}), icon({icon:"square-o", bgcolor:"transparent"}),
this.selectorrect()
)
)
]}
})
| 412 | 0.528325 | 1 | 0.528325 | game-dev | MEDIA | 0.408131 | game-dev | 0.877008 | 1 | 0.877008 |
MegaMek/megamek | 92,182 | megamek/src/megamek/client/ui/dialogs/minimap/MinimapPanel.java | /*
* Copyright (c) 2002-2005 Ben Mazur (bmazur@sev.org)
* Copyright (c) 2013 Edward Cullen (eddy@obsessedcomputers.co.uk)
* Copyright (C) 2021-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.client.ui.dialogs.minimap;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.FACING_ARROW;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.STD_DESTROYED;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.STRAT_BASE_RECT;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.STRAT_CX;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.STRAT_DESTROYED;
import static megamek.client.ui.dialogs.minimap.MinimapUnitSymbols.STRAT_SYMBOL_SIZE;
import static megamek.common.units.Terrains.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDialog;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import megamek.MMConstants;
import megamek.client.Client;
import megamek.client.event.BoardViewEvent;
import megamek.client.event.BoardViewListener;
import megamek.client.event.BoardViewListenerAdapter;
import megamek.client.ui.Messages;
import megamek.client.ui.clientGUI.AbstractClientGUI;
import megamek.client.ui.clientGUI.ClientGUI;
import megamek.client.ui.clientGUI.GUIPreferences;
import megamek.client.ui.clientGUI.IClientGUI;
import megamek.client.ui.clientGUI.boardview.BoardView;
import megamek.client.ui.util.ScalingPopup;
import megamek.client.ui.util.StringDrawer;
import megamek.client.ui.util.UIUtil;
import megamek.common.Configuration;
import megamek.common.Hex;
import megamek.common.Player;
import megamek.common.actions.AttackAction;
import megamek.common.actions.EntityAction;
import megamek.common.actions.WeaponAttackAction;
import megamek.common.annotations.Nullable;
import megamek.common.board.Board;
import megamek.common.board.BoardHelper;
import megamek.common.board.BoardLocation;
import megamek.common.board.Coords;
import megamek.common.compute.Compute;
import megamek.common.event.GameListenerAdapter;
import megamek.common.event.GameNewActionEvent;
import megamek.common.event.GamePhaseChangeEvent;
import megamek.common.event.GameTurnChangeEvent;
import megamek.common.event.board.BoardEvent;
import megamek.common.event.board.BoardListener;
import megamek.common.event.board.BoardListenerAdapter;
import megamek.common.event.board.GameBoardChangeEvent;
import megamek.common.event.board.GameBoardNewEvent;
import megamek.common.event.entity.GameEntityChangeEvent;
import megamek.common.game.Game;
import megamek.common.game.GameTurn;
import megamek.common.interfaces.IEntityRemovalConditions;
import megamek.common.options.OptionsConstants;
import megamek.common.preference.ClientPreferences;
import megamek.common.preference.IPreferenceChangeListener;
import megamek.common.preference.PreferenceChangeEvent;
import megamek.common.preference.PreferenceManager;
import megamek.common.units.*;
import megamek.common.util.ImageUtil;
import megamek.logging.MMLogger;
import megamek.utilities.GifWriter;
import megamek.utilities.GifWriterThread;
/**
* Obviously, displays the map in scaled-down size. TBD: -move the buttons from graphics to real Swing buttons -clean up
* listenercode.. -initializecolors is fugly -uses break-to-label -uses while-true
*/
public final class MinimapPanel extends JPanel implements IPreferenceChangeListener {
private static final MMLogger logger = MMLogger.create(MinimapPanel.class);
private static final Color[] terrainColors = new Color[Terrains.SIZE];
public static final int DESTROYED_UNIT_ALPHA = 64;
private static Color HEAVY_WOODS;
private static Color ULTRA_HEAVY_WOODS;
private static Color BACKGROUND;
private static Color SINKHOLE;
private static Color SMOKE_AND_FIRE;
private static final int[] FONT_SIZE = { 6, 6, 8, 10, 12, 14, 16 };
private static final int[] HEX_SIDE = { 2, 3, 5, 6, 8, 10, 12 };
private static final int[] HEX_SIDE_BY_COS30 = { 2, 3, 4, 5, 7, 9, 10 };
private static final int[] HEX_SIDE_BY_SIN30 = { 1, 2, 2, 3, 4, 5, 6 };
private static final int[] HALF_ROAD_WIDTH_BY_COS30 = { 0, 0, 0, 1, 2, 2, 3 };
private static final int[] HALF_ROAD_WIDTH_BY_SIN30 = { 0, 0, 0, 1, 1, 1, 2 };
private static final int[] HALF_ROAD_WIDTH = { 0, 0, 0, 1, 2, 3, 3 };
private static final int[] UNIT_SIZES = { 4, 5, 6, 7, 8, 9, 10 };
private static final int[] UNIT_SCALE = { 7, 8, 9, 11, 12, 14, 16 };
private static final int MIM_ZOOM = 0;
private static final int MAX_ZOOM = HEX_SIDE.length - 1;
private static final int MIM_ZOOM_FOR_HEIGHT = 4;
private static final int SHOW_NO_HEIGHT = 0;
private static final int SHOW_GROUND_HEIGHT = 1;
private static final int SHOW_BUILDING_HEIGHT = 2;
private static final int SHOW_TOTAL_HEIGHT = 3;
private static final int NBR_HEIGHT_MODES = 3;
private static final int SHOW_SYMBOLS = 0;
private static final int SHOW_NO_SYMBOLS = 1;
private static final int NBR_SYMBOLS_MODES = 1;
private static final int DIALOG_MARGIN = 6;
private static final int MARGIN = 3;
private static final int BUTTON_HEIGHT = 14;
/**
* The minimap zoom at which game summary images are saved regardless of the in game minimap setting.
*/
private static final int GAME_SUMMARY_ZOOM = 4;
private static final String ACTION_ZOOM_IN = "ZOOM_IN";
private static final String ACTION_ZOOM_OUT = "ZOOM_OUT";
private static final String ACTION_HEIGHT_NONE = "HEIGHT_NONE";
private static final String ACTION_HEIGHT_GROUND = "HEIGHT_GROUND";
private static final String ACTION_HEIGHT_BUILDING = "HEIGHT_BUILDING";
private static final String ACTION_HEIGHT_TOTAL = "HEIGHT_TOTAL";
private static final String ACTION_SYMBOLS_NO = "SYMBOLS_NO";
private static final String ACTION_SYMBOLS_SHOW = "SYMBOLS_SHOW";
private static final String ACTION_FACING_ARROWS_SHOW = "FACING_ARROWS_SHOW";
private static final String ACTION_SENSORS_SHOW = "SENSORS_SHOW";
private static final GUIPreferences GUIP = GUIPreferences.getInstance();
private static final ClientPreferences CLIENT_PREFERENCES = PreferenceManager.getClientPreferences();
private BufferedImage mapImage;
private final BoardView bv;
private final Game game;
private Board board;
private final int boardId;
private final JDialog dialog;
private Client client;
private final IClientGUI clientGui;
private GifWriterThread gifWriterThread;
private int margin = MARGIN;
private int topMargin;
private int leftMargin;
// This value is variable.
// if the container m_dialog is an instance of JDialog, it is 14. otherwise 0.
private int buttonHeight = 0;
/**
* Indicates if the minimap has been rolled up using the wide green button. Can only be true when in a dialog.
*/
private boolean minimized = false;
/** Stores the (non-minimized) height of the minimap when it is minimized. */
private int heightBuffer;
private int unitSize = 6;
/** A list of information on hexes with roads or bridges. */
private final List<int[]> roadHexes = new ArrayList<>();
private int zoom = GUIP.getMinimapZoom();
private int heightDisplayMode = GUIP.getMinimapHeightDisplayMode();
private int symbolsDisplayMode = GUIP.getMinimapSymbolsDisplayMode();
private boolean drawSensorRangeOnMiniMap = GUIP.getDrawSensorRangeOnMiniMap();
private boolean drawFacingArrowsOnMiniMap = GUIP.getDrawFacingArrowsOnMiniMap();
private boolean paintBorders = GUIP.paintBorders();
private Coords firstLOS;
private Coords secondLOS;
private static final Set<Integer> removalReasons = Set.of(IEntityRemovalConditions.REMOVE_CAPTURED,
IEntityRemovalConditions.REMOVE_SALVAGEABLE,
IEntityRemovalConditions.REMOVE_DEVASTATED,
IEntityRemovalConditions.REMOVE_EJECTED);
/** Signifies that the whole minimap must be repainted. */
private boolean dirtyMap = true;
/** Keeps track of portions of the minimap that must be repainted. */
private boolean[][] dirty = new boolean[1][1];
private Image terrainBuffer;
private final Map<Coords, Integer> multiUnits = new HashMap<>();
private static final String[] STRAT_WEIGHTS = { "L", "L", "M", "H", "A", "A" };
private boolean dragging = false;
/** Returns a minimap image of the given board at the maximum zoom index. */
public static BufferedImage getMinimapImageMaxZoom(Board board) {
return getMinimapImage(board, MAX_ZOOM, null);
}
/** Returns a minimap image of the given board at the maximum zoom index. */
public static BufferedImage getMinimapImageMaxZoom(Board board, @Nullable File minimapTheme) {
return getMinimapImage(board, MAX_ZOOM, minimapTheme);
}
/** Returns a minimap image of the given board at the given zoom index. */
public static BufferedImage getMinimapImage(Board board, int zoom) {
Game game = new Game();
game.setBoard(board);
return getMinimapImage(game, null, zoom, null, 0);
}
/** Returns a minimap image of the given board at the given zoom index. */
public static BufferedImage getMinimapImage(Board board, int zoom, @Nullable File minimapTheme) {
Game game = new Game();
game.setBoard(board);
return getMinimapImage(game, null, zoom, minimapTheme, 0);
}
/**
* Returns a minimap image of the given board at the given zoom index. The game and {@link BoardView} object will be
* used to display additional information.
*/
public static BufferedImage getMinimapImage(Game game, BoardView boardView, int zoom, @Nullable File minimapTheme,
int boardId) {
return getMinimapImage(game, boardView, zoom, null, minimapTheme, Collections.emptyList(), boardId);
}
/**
* Returns a minimap image of the given board at the given zoom index. The game and {@link BoardView} object will be
* used to display additional information.
*/
public static BufferedImage getMinimapImage(Game game, BoardView boardView, int zoom, IClientGUI clientGui,
@Nullable File minimapTheme, List<Line> movePathLines, int boardId) {
try {
// Send the fail image when the zoom index is wrong to make this noticeable
if ((zoom < MIM_ZOOM) || (zoom > MAX_ZOOM)) {
throw new Exception("The given zoom index is out of bounds.");
}
MinimapPanel tempMM = new MinimapPanel(null, game, boardView, clientGui, minimapTheme, boardId);
tempMM.zoom = zoom;
tempMM.movePathLines.clear();
tempMM.movePathLines.addAll(movePathLines);
tempMM.initializeMap();
tempMM.drawMap(true);
return ImageUtil.createAcceleratedImage(tempMM.mapImage);
} catch (Exception e) {
logger.error(e, "");
return ImageUtil.failStandardImage();
}
}
/**
* Creates a minimap panel. The only required parameter is a game that contains the board to display. When the
* dialog is not null, it is assumed that this minimap will be visible for a while, and it will register itself to
* various objects as a listener to changes. When the dialog is null, it is assumed that the minimap is only used to
* create a snapshot image. When a {@link BoardView} is given, the visible area is shown.
*/
public MinimapPanel(@Nullable MinimapDialog minimapDialog, Game game, @Nullable BoardView boardView,
@Nullable IClientGUI clientGUI,
@Nullable File minimapTheme, int boardId) {
this.game = Objects.requireNonNull(game);
board = Objects.requireNonNull(this.game.getBoard(boardId));
this.boardId = boardId;
bv = boardView;
dialog = minimapDialog;
clientGui = clientGUI;
if (clientGui != null && clientGui.getClient() instanceof Client castClient) {
client = castClient;
}
initializeColors(minimapTheme);
if (dialog != null) {
initializeDialog();
initializeListeners();
buttonHeight = BUTTON_HEIGHT;
margin = DIALOG_MARGIN;
}
}
/**
* Registers the minimap as listener to the given game, board, {@link BoardView} (that are not null).
*/
private void initializeListeners() {
game.addGameListener(new GameListenerAdapter() {
@Override
public void gamePhaseChange(GamePhaseChangeEvent e) {
if ((GUIP.getGameSummaryMinimap() || GUIP.getGifGameSummaryMinimap())
&& (e.getOldPhase().isDeployment() || e.getOldPhase().isMovement()
|| e.getOldPhase().isTargeting() || e.getOldPhase().isPremovement()
|| e.getOldPhase().isPreFiring() || e.getOldPhase().isFiring()
|| e.getOldPhase().isPhysical())) {
File dir = new File(Configuration.gameSummaryImagesMMDir(), game.getUUIDString());
if (!dir.exists()) {
dir.mkdirs();
}
File imgFile = new File(dir, "round_" + game.getRoundCount() + "_" + e.getOldPhase().ordinal() + "_"
+ e.getOldPhase() + ".png");
try {
BufferedImage image = getMinimapImage(game, bv, GAME_SUMMARY_ZOOM, clientGui, null,
movePathLines, boardId);
if (GUIP.getGameSummaryMinimap()) {
ImageIO.write(image, "png", imgFile);
}
if (GUIP.getGifGameSummaryMinimap()) {
if (gifWriterThread == null || !gifWriterThread.isAlive()) {
gifWriterThread = new GifWriterThread(new GifWriter(game.getUUIDString()),
"GifWriterThread");
gifWriterThread.start();
}
gifWriterThread.addFrame(image, 400);
}
} catch (Exception ex) {
logger.error(ex, "Error saving game summary image.");
}
}
if (e.getNewPhase().isVictory() && (gifWriterThread != null) && gifWriterThread.isAlive()) {
try {
gifWriterThread.stopThread();
} catch (Exception ex) {
logger.error(ex, "Error closing gif writer.");
}
}
// We clear the move path lines locally, since the game does not currently hold this information until the end of the turn
if (e.getNewPhase().isDeployment() || e.getNewPhase().isLounge() || e.getNewPhase().isVictory()) {
movePathLines.clear();
} else {
movePathLines.removeIf(line -> (line.round() + GUIP.getMovePathPersistenceOnMiniMap())
<= game.getCurrentRound());
}
refreshMap();
}
@Override
public void gameTurnChange(GameTurnChangeEvent e) {
refreshMap();
}
@Override
public void gameEntityChange(GameEntityChangeEvent e) {
// We store the move path lines locally because the game does not currently hold this information until the end of the turn
var movePath = e.getMovePath();
if (movePath != null && !movePath.isEmpty()) {
addMovePath(new ArrayList<>(movePath), e.getOldEntity());
refreshMap();
}
}
@Override
public void gameBoardNew(GameBoardNewEvent e) {
if (e.getBoardId() == boardId) {
Board b = e.getOldBoard();
if (b != null) {
b.removeBoardListener(boardListener);
}
b = e.getNewBoard();
if (b != null) {
b.addBoardListener(boardListener);
}
board = b;
initializeMap();
}
}
@Override
public void gameBoardChanged(GameBoardChangeEvent e) {
refreshMap();
}
@Override
public void gameNewAction(GameNewActionEvent e) {
refreshMap();
}
});
board.addBoardListener(boardListener);
if (bv != null) {
bv.addBoardViewListener(boardViewListener);
}
if (client != null) {
client.addCloseClientListener(() -> {
if (gifWriterThread != null && gifWriterThread.isAlive()) {
gifWriterThread.stopThread(true);
}
});
}
GUIP.addPreferenceChangeListener(this);
}
/**
* Adds listeners to the dialog to manipulate the minimap if it has an associated dialog.
*/
private void initializeDialog() {
if (dialog != null) {
if (dialog.getMouseListeners().length == 0) {
dialog.addMouseListener(mouseListener);
dialog.addMouseMotionListener(mouseMotionListener);
dialog.addMouseWheelListener(mouseWheelListener);
dialog.addComponentListener(componentListener);
dialog.addComponentListener(componentListener);
}
}
}
private @Nullable Player getLocalPlayer() {
if (client != null && client.getLocalPlayer() != null) {
return client.getLocalPlayer();
}
if (clientGui != null && clientGui.getClient() != null && clientGui.getClient().getLocalPlayer() != null) {
return clientGui.getClient().getLocalPlayer();
}
return null;
}
@Override
protected void paintComponent(Graphics g) {
if (mapImage != null) {
g.drawImage(mapImage, 0, 0, this);
paintVisibleSection(g);
}
}
/** Initialize default colors and override with config file if there is one. */
private void initializeColors(File minimapTheme) {
BACKGROUND = Color.black;
terrainColors[0] = new Color(218, 215, 170);
SINKHOLE = new Color(218, 215, 170);
terrainColors[WOODS] = new Color(180, 230, 130);
HEAVY_WOODS = new Color(160, 200, 100);
ULTRA_HEAVY_WOODS = new Color(0, 100, 0);
terrainColors[ROUGH] = new Color(215, 181, 0);
terrainColors[RUBBLE] = new Color(200, 200, 200);
terrainColors[WATER] = new Color(200, 247, 253);
terrainColors[PAVEMENT] = new Color(204, 204, 204);
terrainColors[ROAD] = new Color(71, 79, 107);
terrainColors[FIRE] = Color.red;
terrainColors[SMOKE] = new Color(204, 204, 204);
SMOKE_AND_FIRE = new Color(153, 0, 0);
terrainColors[SWAMP] = new Color(49, 136, 74);
terrainColors[BUILDING] = new Color(204, 204, 204);
terrainColors[FUEL_TANK] = new Color(255, 204, 204);
terrainColors[BRIDGE] = new Color(109, 55, 25);
terrainColors[ICE] = new Color(204, 204, 255);
terrainColors[MAGMA] = new Color(200, 0, 0);
// m_terrainColors[MUD] = new Color(218, 160, 100);
terrainColors[JUNGLE] = new Color(180, 230, 130);
terrainColors[FIELDS] = new Color(250, 255, 205);
terrainColors[INDUSTRIAL] = new Color(112, 138, 144);
terrainColors[SPACE] = Color.BLACK;
// now try to read in the config file
int red;
int green;
int blue;
if (minimapTheme == null || !minimapTheme.exists()) {
minimapTheme = CLIENT_PREFERENCES.getMinimapTheme();
}
// only while the defaults are hard-coded!
if (!minimapTheme.exists()) {
return;
}
try (Reader cr = new FileReader(minimapTheme)) {
StreamTokenizer st = new StreamTokenizer(cr);
st.lowerCaseMode(true);
st.quoteChar('"');
st.commentChar('#');
scan:
while (true) {
switch (st.nextToken()) {
case StreamTokenizer.TT_EOF:
case StreamTokenizer.TT_EOL:
break scan;
case StreamTokenizer.TT_WORD:
// read in
String key = st.sval;
switch (key) {
case "unitsize" -> {
st.nextToken();
unitSize = (int) st.nval;
}
case "background" -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
BACKGROUND = new Color(red, green, blue);
}
case "heavywoods" -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
HEAVY_WOODS = new Color(red, green, blue);
}
case "ultraheavywoods" -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
ULTRA_HEAVY_WOODS = new Color(red, green, blue);
}
case "sinkhole" -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
SINKHOLE = new Color(red, green, blue);
}
case "smokeandfire" -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
SMOKE_AND_FIRE = new Color(red, green, blue);
}
default -> {
st.nextToken();
red = (int) st.nval;
st.nextToken();
green = (int) st.nval;
st.nextToken();
blue = (int) st.nval;
terrainColors[getType(key)] = new Color(red, green, blue);
}
}
break;
}
}
} catch (Exception e) {
// Fall back to the default colors
logger.error(e, "");
}
}
/** Marks all the minimap as clean (not requiring an update). */
private void markAsClean() {
dirtyMap = false;
for (boolean[] booleans : dirty) {
Arrays.fill(booleans, false);
}
}
void initializeMap() {
dirty = new boolean[(board.getWidth() / 10) + 1][(board.getHeight() / 10) + 1];
dirtyMap = true;
unitSize = UNIT_SIZES[zoom];
topMargin = margin;
leftMargin = margin;
int requiredWidth = (board.getWidth() * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]))
+ HEX_SIDE_BY_SIN30[zoom] + (2 * margin);
int requiredHeight = minimized ? BUTTON_HEIGHT
: (((2 * board.getHeight()) + 1)
* HEX_SIDE_BY_COS30[zoom]) + (2 * margin) + buttonHeight;
if (dialog != null) {
setSize(new Dimension(requiredWidth, requiredHeight));
setPreferredSize(new Dimension(requiredWidth, requiredHeight));
dialog.pack();
mapImage = ImageUtil.createAcceleratedImage(getSize().width, getSize().height);
terrainBuffer = createImage(getSize().width, getSize().height);
// Center the minimap in the dialog
if (getSize().width > requiredWidth) {
leftMargin = ((getSize().width - requiredWidth) / 2) + DIALOG_MARGIN;
}
if (getSize().height > requiredHeight) {
topMargin = ((getSize().height - requiredHeight) / 2) + DIALOG_MARGIN;
}
// Start the refresh timer only for a "live" minimap in a dialog
refreshMap();
revalidate();
} else {
mapImage = ImageUtil.createAcceleratedImage(requiredWidth, requiredHeight);
terrainBuffer = ImageUtil.createAcceleratedImage(requiredWidth, requiredHeight);
}
Graphics gg = terrainBuffer.getGraphics();
gg.setColor(BACKGROUND);
gg.fillRect(0, 0, getSize().width, getSize().height);
}
private long lastDrawMapReq = 0;
private long lastDrawStarted = 0;
private final Runnable drawMapable = new Runnable() {
@Override
public void run() {
try {
int redrawDelay = 0;
if ((java.lang.System.currentTimeMillis() - lastDrawMapReq) > redrawDelay) {
drawMap();
} else {
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
// should never happen
}
SwingUtilities.invokeLater(drawMapable);
}
} catch (Throwable t) {
logger.error(t, "");
}
}
};
private final List<Line> movePathLines = new Vector<>();
public record Line(int x1, int y1, int x2, int y2, Color color, int round) {}
private final Color MOVE_PATH_COLOR = new Color(0, 0, 0, 128);
private void addMovePath(List<UnitLocation> unitLocations, Entity entity) {
if ((GUIP.getMovePathPersistenceOnMiniMap() <= 0)
|| !EntityVisibilityUtils.detectedOrHasVisual(getLocalPlayer(), game, entity)) {
return;
}
Coords previousCoords = entity.getPosition();
for (var unitLocation : unitLocations) {
var coords = unitLocation.coords();
if (previousCoords != null && unitLocation.boardId() == boardId) {
movePathLines.add(new Line(previousCoords.getX(),
previousCoords.getY(),
coords.getX(),
coords.getY(),
MOVE_PATH_COLOR,
game.getCurrentRound()));
}
previousCoords = coords;
}
}
/** Call this to schedule a minimap redraw. */
public void refreshMap() {
lastDrawMapReq = java.lang.System.currentTimeMillis();
SwingUtilities.invokeLater(drawMapable);
}
/**
* Draws the minimap to the back-buffer. If the dialog is not visible or the minimap is minimized, drawing will be
* kept to a minimum.
*/
private void drawMap() {
drawMap(false);
}
/**
* Draws the minimap to the back-buffer. When forceDraw is true, the map will be drawn even if it is minimized or
* not visible. This can be used to draw the minimap for saving it as an image regardless of its visual status
* onscreen.
*/
private void drawMap(boolean forceDraw) {
if ((lastDrawStarted > lastDrawMapReq) && !forceDraw) {
return;
}
lastDrawStarted = java.lang.System.currentTimeMillis();
if (!forceDraw && (dialog != null) && !dialog.isVisible()) {
return;
}
Graphics g = mapImage.getGraphics();
UIUtil.setHighQualityRendering(g);
if (!minimized || forceDraw) {
roadHexes.clear();
Graphics gg = terrainBuffer.getGraphics();
UIUtil.setHighQualityRendering(gg);
for (int j = 0; j < board.getWidth(); j++) {
for (int k = 0; k < board.getHeight(); k++) {
Hex h = board.getHex(j, k);
if (h == null) {
continue;
}
if (dirtyMap || dirty[j / 10][k / 10]) {
gg.setColor(terrainColor(h));
if (board.isHighAltitude()) {
paintHighAltCoord(gg, j, k);
} else if (board.isSpace()) {
paintSpaceCoord(gg, j, k);
} else if (h.containsTerrain(SKY)) {
paintLowAtmosphereSkyCoord(gg, j, k, paintBorders && zoom > 1);
} else {
paintCoord(gg, j, k, paintBorders && zoom > 1);
}
}
addRoadElements(h, j, k);
// Color invalid hexes red when in the Map Editor
if ((game != null) && game.getPhase().isUnknown() && !h.isValid(null)) {
gg.setColor(GUIP.getWarningColor());
paintCoord(gg, j, k, true);
}
}
}
g.drawImage(terrainBuffer, 0, 0, this);
markAsClean();
if (firstLOS != null) {
paintSingleCoordBorder(g, firstLOS.getX(), firstLOS.getY(), Color.red);
}
if (secondLOS != null) {
paintSingleCoordBorder(g, secondLOS.getX(), secondLOS.getY(), Color.red);
}
paintRoads(g);
if (SHOW_NO_HEIGHT != heightDisplayMode) {
for (int j = 0; j < board.getWidth(); j++) {
for (int k = 0; k < board.getHeight(); k++) {
Hex h = board.getHex(j, k);
paintHeight(g, h, j, k);
}
}
}
if (board.isHighAltitude()
&& (HEX_SIDE[zoom] >= 10)) {
int baseX = HEX_SIDE[zoom] + leftMargin;
int baseY = (board.getHeight() + 1) * HEX_SIDE_BY_COS30[zoom] + topMargin;
new StringDrawer("Ground Hexes").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.BLACK).draw(g);
if ((game != null) && !game.getPlanetaryConditions().getAtmosphere().isVacuum()) {
baseX = HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom] + HEX_SIDE[zoom] + leftMargin;
new StringDrawer("Atmospheric Row 1").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.LIGHT_GRAY).draw(g);
baseX = (4 * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) + HEX_SIDE[zoom]) + leftMargin;
new StringDrawer("Atmospheric Row 4").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.GRAY).draw(g);
if (game.getPlanetaryConditions().getAtmosphere().isVeryHigh()) {
baseX = (7 * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) + HEX_SIDE[zoom]) + leftMargin;
new StringDrawer("Atmospheric Row 7").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.GRAY).draw(g);
}
baseX = (BoardHelper.spaceAtmosphereInterfacePosition(game)
* (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) + HEX_SIDE[zoom]) + leftMargin;
new StringDrawer("Space/Atmosphere Interface").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.GRAY).draw(g);
}
if (board.getWidth() > 15) {
baseX = (15 * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) + HEX_SIDE[zoom]) + leftMargin;
new StringDrawer("End of Gravity").at(baseX, baseY).fontSize(HEX_SIDE[zoom])
.rotate(Math.toRadians(90)).center().color(Color.GRAY).draw(g);
}
}
drawDeploymentZone(g);
drawEmbeddedBoards(g);
// In case the flag SHOW SYMBOLS is set, it will draw the units and other stuff
if (symbolsDisplayMode == SHOW_SYMBOLS) {
if (null != game) {
// draw dead units
multiUnits.clear();
for (Entity e : game.getOutOfGameEntitiesVector()) {
if (e.getBoardLocation().isOn(boardId) &&
removalReasons.contains(e.getRemovalCondition())) {
paintUnit(g, e, true);
}
}
if (!movePathLines.isEmpty()) {
paintMoveTracks(g);
}
// draw declared fire
for (EntityAction action : game.getActionsVector()) {
if (action instanceof AttackAction) {
paintAttack(g, (AttackAction) action);
}
}
// draw living units
for (Entity e : game.getEntitiesVector()) {
if (e.getBoardLocation().isOn(boardId)) {
paintUnit(g, e, false);
}
}
if (drawSensorRangeOnMiniMap) {
for (Entity e : game.getEntitiesVector()) {
if (e.getBoardLocation().isOn(boardId)) {
paintSensor(g, e);
}
}
}
}
Player localPlayer = getLocalPlayer();
if (localPlayer != null) {
for (BoardLocation autoHitHex : localPlayer.getArtyAutoHitHexes()) {
if (autoHitHex.isOn(boardId)) {
drawAutoHit(g, autoHitHex.coords());
}
}
}
}
}
if (dialog != null) {
drawButtons(g);
repaint();
}
}
private void paintMoveTracks(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
0, new float[] { 6 }, 3);
g2d.setStroke(dashed);
for (Line line : movePathLines) {
paintMoveTrack(g2d, line);
}
g2d.dispose();
}
/** Indicates the deployment hexes. */
private void drawDeploymentZone(Graphics g) {
if ((null != client) && (null != game) && game.getPhase().isDeployment() && (bv != null)
&& (bv.getDeployingEntity() != null) && (dialog != null) && (getLocalPlayer() != null)) {
GameTurn turn = game.getTurn();
if ((turn != null) && (turn.playerId() == getLocalPlayer().getId())) {
Entity deployingUnit = bv.getDeployingEntity();
for (int j = 0; j < board.getWidth(); j++) {
for (int k = 0; k < board.getHeight(); k++) {
Coords coords = new Coords(j, k);
if (board.isLegalDeployment(coords, deployingUnit) &&
!deployingUnit.isLocationProhibited(BoardLocation.of(coords, boardId)) &&
!deployingUnit.isBoardProhibited(board)) {
paintSingleCoordBorder(g, j, k, Color.yellow);
}
}
}
}
}
}
/**
* Draw an outline around legal deployment hexes
*/
private void drawEmbeddedBoards(Graphics g) {
for (Coords coords : board.embeddedBoardCoords()) {
paintEmbeddedBoard(g, coords.getX(), coords.getY(), Color.GREEN);
}
}
/**
* Draws a box showing the portion of the board that is currently visible in the {@link BoardView}.
*/
private void paintVisibleSection(Graphics g) {
if (minimized || (bv == null)) {
return;
}
double[] relSize = bv.getVisibleArea();
for (int i = 0; i < 4; i++) {
// keep between 0 and 1 to not fall outside the minimap
relSize[i] = Math.min(1, Math.max(0, relSize[i]));
}
int x1 = (int) (relSize[0] * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) * board.getWidth()) + leftMargin;
int y1 = (int) (relSize[1] * 2 * HEX_SIDE_BY_COS30[zoom] * board.getHeight()) + topMargin;
int x2 = (int) ((relSize[2] - relSize[0]) * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) * board.getWidth());
int y2 = (int) ((relSize[3] - relSize[1]) * 2 * HEX_SIDE_BY_COS30[zoom] * board.getHeight());
// thicker but translucent rectangle
g.setColor(new Color(100, 100, 160, 80));
((Graphics2D) g).setStroke(new BasicStroke(zoom + 2));
g.drawRect(x1, y1, x2, y2);
// thin less translucent rectangle
g.setColor(new Color(255, 255, 255, 180));
((Graphics2D) g).setStroke(new BasicStroke(zoom / 2f));
g.drawRect(x1, y1, x2, y2);
}
/** Draws a red crosshair for artillery auto hit hexes (predesignated only). */
private void drawAutoHit(Graphics g, Coords hex) {
int baseX = (hex.getX() * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin + HEX_SIDE[zoom];
int baseY = (((2 * hex.getY()) + 1 + (hex.getX() % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
g.setColor(Color.RED);
g.drawOval(baseX - (unitSize - 1), baseY - (unitSize - 1), (2 * unitSize) - 2, (2 * unitSize) - 2);
g.drawLine(baseX - unitSize - 1, baseY, (baseX - unitSize) + 3, baseY);
g.drawLine(baseX + unitSize + 1, baseY, (baseX + unitSize) - 3, baseY);
g.drawLine(baseX, baseY - unitSize - 1, baseX, (baseY - unitSize) + 3);
g.drawLine(baseX, baseY + unitSize + 1, baseX, (baseY + unitSize) - 3);
}
/** Draws the green control buttons at the bottom of the Minimap. */
private void drawButtons(Graphics g) {
int w = getSize().width;
int h = getSize().height;
int w0 = w - BUTTON_HEIGHT;
int y0 = h - BUTTON_HEIGHT;
// the center bar for rolling up/down the Minimap
g.setColor(Color.green.darker().darker());
g.fillRect(0, y0, w, BUTTON_HEIGHT);
g.setColor(Color.green.darker());
g.drawLine(0, y0, w, y0);
g.drawLine(0, y0, 0, h);
g.setColor(Color.black);
g.drawLine(0, h - 1, w, h - 1);
g.drawLine(w - 1, y0, w - 1, h);
int[] xTriangle = new int[3];
int[] yTriangle = new int[3];
xTriangle[0] = Math.round((w - 11) / 2f);
xTriangle[1] = xTriangle[0] + 11;
if (minimized) {
yTriangle[0] = h - 10;
yTriangle[1] = yTriangle[0];
xTriangle[2] = xTriangle[0] + 6;
yTriangle[2] = yTriangle[0] + 5;
} else {
yTriangle[0] = h - 4;
yTriangle[1] = yTriangle[0];
xTriangle[2] = xTriangle[0] + 5;
yTriangle[2] = yTriangle[0] - 5;
}
g.setColor(Color.yellow);
g.fillPolygon(xTriangle, yTriangle, 3);
// the zoom control "+" and "-" buttons
if (!minimized) {
g.setColor(Color.black);
g.drawLine(BUTTON_HEIGHT - 1, y0, BUTTON_HEIGHT - 1, h);
g.drawLine(w0 - 1, y0, w0 - 1, h);
g.setColor(Color.green.darker());
g.drawLine(BUTTON_HEIGHT, y0, BUTTON_HEIGHT, getSize().height);
g.drawLine(w0, y0, w0, h);
if (zoom == 0) {
g.setColor(Color.gray.brighter());
} else {
g.setColor(Color.yellow);
}
g.fillRect(3, y0 + 6, 8, 2);
if (zoom == (HEX_SIDE.length - 1)) {
g.setColor(Color.gray.brighter());
} else {
g.setColor(Color.yellow);
}
g.fillRect(w0 + 3, y0 + 6, 8, 2);
g.fillRect(w0 + 6, y0 + 3, 2, 8);
if (zoom >= MIM_ZOOM_FOR_HEIGHT) {
// the button for displaying heights
int x = BUTTON_HEIGHT;
g.setColor(Color.yellow);
String label = switch (heightDisplayMode) {
case SHOW_NO_HEIGHT -> Messages.getString("Minimap.NoHeightLabel");
case SHOW_GROUND_HEIGHT -> Messages.getString("Minimap.GroundHeightLabel");
case SHOW_BUILDING_HEIGHT -> Messages.getString("Minimap.BuildingHeightLabel");
case SHOW_TOTAL_HEIGHT -> Messages.getString("Minimap.TotalHeightLabel");
default -> "";
};
g.drawString(label, x + 2, y0 + 11);
x += BUTTON_HEIGHT;
g.setColor(Color.black);
g.drawLine(x - 1, y0, x - 1, h);
g.setColor(Color.green.darker());
g.drawLine(x, y0, x, h);
// the button for displaying symbols
g.setColor(Color.yellow);
label = switch (symbolsDisplayMode) {
case SHOW_SYMBOLS -> Messages.getString("Minimap.SymbolsLabel");
case SHOW_NO_SYMBOLS -> Messages.getString("Minimap.NoSymbolsLabel");
default -> "";
};
g.drawString(label, x + 2, y0 + 11);
x += BUTTON_HEIGHT;
g.setColor(Color.black);
g.drawLine(x - 1, y0, x - 1, h);
g.setColor(Color.green.darker());
g.drawLine(x, y0, x, h);
// map size
String mapSize = board.getWidth() + " " + Messages.getString("Minimap.X") + " " + board.getHeight();
g.setColor(Color.yellow);
g.drawString(mapSize, x, y0 + 11);
int width = getFontMetrics(g.getFont()).stringWidth(mapSize);
x += width + 3;
g.setColor(Color.black);
g.drawLine(x - 1, y0, x, h);
g.setColor(Color.green.darker());
g.drawLine(x, y0, x, h);
}
}
}
/** Writes the height value (hex/building/none) in the minimap hexes. */
private void paintHeight(Graphics g, Hex h, int x, int y) {
if ((heightDisplayMode == SHOW_NO_HEIGHT) || (zoom < MIM_ZOOM_FOR_HEIGHT)) {
return;
}
int height = 0;
if ((heightDisplayMode == SHOW_BUILDING_HEIGHT) && h.containsTerrain(BUILDING)) {
height = h.ceiling();
} else if (heightDisplayMode == SHOW_GROUND_HEIGHT) {
height = h.floor();
} else if (heightDisplayMode == SHOW_TOTAL_HEIGHT) {
height = (h.containsAnyTerrainOf(BUILDING, FUEL_TANK)) ? h.ceiling() : h.floor();
}
if (height != 0) {
String sHeight = height + "";
int baseX = coordsXToPixel(x);
int baseY = coordsYtoPixel(y, x);
Font font = new Font(MMConstants.FONT_SANS_SERIF, Font.PLAIN, FONT_SIZE[zoom]);
int fontWidth = getFontMetrics(font).stringWidth(sHeight) / 2;
int fontHeight = getFontMetrics(font).getHeight() / 3;
g.setFont(font);
g.setColor(Color.white);
g.drawString(sHeight, baseX - fontWidth, baseY + fontHeight);
}
}
private int[] xPoints(int x) {
int baseX = (x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin;
int[] xPoints = new int[6];
xPoints[0] = baseX;
xPoints[1] = baseX + HEX_SIDE_BY_SIN30[zoom];
xPoints[2] = xPoints[1] + HEX_SIDE[zoom];
xPoints[3] = xPoints[2] + HEX_SIDE_BY_SIN30[zoom];
xPoints[4] = xPoints[2];
xPoints[5] = xPoints[1];
return xPoints;
}
private int[] yPoints(int x, int y) {
int baseY = (((2 * y) + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
int[] yPoints = new int[6];
yPoints[0] = baseY;
yPoints[1] = baseY + HEX_SIDE_BY_COS30[zoom];
yPoints[2] = yPoints[1];
yPoints[3] = baseY;
yPoints[4] = baseY - HEX_SIDE_BY_COS30[zoom];
yPoints[5] = yPoints[4];
return yPoints;
}
private void paintSingleCoordBorder(Graphics g, int x, int y, Color c) {
g.setColor(c);
((Graphics2D) g).setStroke(new BasicStroke(Math.max(1, zoom / 2f)));
g.drawPolygon(xPoints(x), yPoints(x, y), 6);
}
private void paintEmbeddedBoard(Graphics graphics, int x, int y, Color color) {
graphics.setColor(color);
((Graphics2D) graphics).setStroke(new BasicStroke(Math.max(0.8f, zoom / 3f)));
int baseX = (x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin;
int[] xPoints = new int[6];
xPoints[0] = baseX + HEX_SIDE_BY_SIN30[zoom];
xPoints[1] = xPoints[0] + HEX_SIDE[zoom];
xPoints[2] = xPoints[1];
xPoints[3] = xPoints[0];
int baseY = (((2 * y) + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
int[] yPoints = new int[6];
yPoints[0] = baseY + HEX_SIDE_BY_COS30[zoom];
yPoints[1] = yPoints[0];
yPoints[2] = baseY - HEX_SIDE_BY_COS30[zoom];
yPoints[3] = yPoints[2];
graphics.drawPolygon(xPoints, yPoints, 4);
}
private void paintCoord(Graphics g, int x, int y, boolean border) {
int[] xPoints = xPoints(x);
int[] yPoints = yPoints(x, y);
g.fillPolygon(xPoints, yPoints, 6);
if (border) {
g.setColor(g.getColor().darker());
}
g.drawPolygon(xPoints, yPoints, 6);
}
private void paintLowAtmosphereSkyCoord(Graphics g, int x, int y, boolean paintBorder) {
int[] xPoints = xPoints(x);
int[] yPoints = yPoints(x, y);
int c = 190;
g.setColor(new Color(c / 2, c, c));
g.fillPolygon(xPoints, yPoints, 6);
if (paintBorder) {
c = 170;
g.setColor(new Color(c / 2, c, c));
}
g.drawPolygon(xPoints, yPoints, 6);
}
private void paintSpaceCoord(Graphics g, int x, int y) {
int baseX = (x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin;
int baseY = (((2 * y) + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
int[] xPoints = xPoints(x);
int[] yPoints = yPoints(x, y);
g.fillPolygon(xPoints, yPoints, 6);
// alpha to tone down borders and stars at low zoom so they don't overwhelm the
// image
int alpha = Math.min(250, 20 * HEX_SIDE[zoom]);
g.setColor(new Color(20, 20, 60, alpha));
g.drawPolygon(xPoints, yPoints, 6);
// Drop in a star
int dx = (int) (Math.random() * HEX_SIDE[zoom]);
int dy = (int) ((Math.random() - 0.5) * HEX_SIDE_BY_COS30[zoom]);
int c = (int) (Math.random() * 180);
g.setColor(new Color(c, c, c, alpha));
if (Math.random() < 0.1) {
g.setColor(new Color(c, c / 10, c / 10, alpha)); // red star
} else if (Math.random() < 0.1) {
int factor = (int) (Math.random() * 10) + 1;
g.setColor(new Color(c / factor, c / factor, c, alpha)); // blue star
}
g.fillRect(baseX + dx, baseY + dy, 1, 1);
}
private void paintHighAltCoord(Graphics g, int x, int y) {
int baseX = (x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin;
int baseY = (((2 * y) + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
int[] xPoints = xPoints(x);
int[] yPoints = yPoints(x, y);
int spaceInterfacePosition = BoardHelper.spaceAtmosphereInterfacePosition(game);
// Draw in atmosphere in a high-altitude map (unless planetary conditions say its vacuum)
if (BoardHelper.isAtmosphericRow(game, board, x)) {
int atmosphericRow = BoardHelper.effectiveAtmosphericRowNumber(game, board, x);
// Add atmosphere
int step = 120 / (spaceInterfacePosition - 1);
g.setColor(new Color(75 - step / 2 * atmosphericRow,
150 - step * atmosphericRow, 150 - step * atmosphericRow));
} else if (BoardHelper.isGroundRowHex(board, x)) {
g.setColor(Color.GREEN);
}
g.fillPolygon(xPoints, yPoints, 6);
if (paintBorders && zoom > 1) {
g.setColor(new Color(20, 20, 60));
}
g.drawPolygon(xPoints, yPoints, 6);
if (x > spaceInterfacePosition) {
// Drop in a star
int dx = (int) (Math.random() * HEX_SIDE[zoom]);
int dy = (int) ((Math.random() - 0.5) * HEX_SIDE_BY_COS30[zoom]);
int c = (int) (Math.random() * 180);
g.setColor(new Color(c, c, c));
if (Math.random() < 0.1) {
g.setColor(new Color(c, c / 10, c / 10)); // red star
} else if (Math.random() < 0.1) {
int factor = (int) (Math.random() * 10) + 1;
g.setColor(new Color(c / factor, c / factor, c)); // blue star
}
g.fillRect(baseX + dx, baseY + dy, 1, 1);
}
}
private void paintMoveTrack(Graphics2D g, Line line) {
int baseX1 = (line.x1 * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin + HEX_SIDE[zoom];
int baseY1 = (((2 * line.y1) + 1 + (line.x1 % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
int baseX2 = (line.x2 * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin + HEX_SIDE[zoom];
int baseY2 = (((2 * line.y2) + 1 + (line.x2 % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
g.setColor(line.color);
g.drawLine(baseX1, baseY1, baseX2, baseY2);
}
/**
* Draw a line to represent an attack
*/
private void paintAttack(Graphics g, AttackAction attack) {
Entity source = game.getEntity(attack.getEntityId());
Targetable target = game.getTarget(attack.getTargetType(), attack.getTargetId());
// sanity check...
// cross-board attacks don't get attack arrows (for now, must possibly allow some A2G, O2G, A2A attacks later
// when target/attacker hexes are not really but effectively on the same board)
if ((null == source) || (null == target) || !game.onTheSameBoard(source, target)
|| (target.getBoardId() != boardId)) {
return;
}
if (attack.getTargetType() == Targetable.TYPE_I_NARC_POD) {
// iNarc pods don't have a position
return;
}
if (attack instanceof WeaponAttackAction waa) {
if ((getLocalPlayer() == null) || ((attack.getTargetType() == Targetable.TYPE_HEX_ARTILLERY)
&& (waa.getEntity(game).getOwner().getId() != getLocalPlayer().getId()))) {
return;
}
}
int[] xPoints = new int[4];
int[] yPoints = new int[4];
xPoints[0] = ((source.getPosition().getX() * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]))
+ leftMargin + (HEX_SIDE[zoom])) - 2;
yPoints[0] = (((2 * source.getPosition().getY()) + 1 + (source
.getPosition().getX() % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
xPoints[1] = ((target.getPosition().getX() * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]))
+ leftMargin + (HEX_SIDE[zoom])) - 2;
yPoints[1] = (((2 * target.getPosition().getY()) + 1 + (target
.getPosition().getX() % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
xPoints[2] = xPoints[1] + 2;
xPoints[3] = xPoints[0] + 2;
if (((source.getPosition().getX() > target.getPosition().getX()) && (source
.getPosition().getY() < target.getPosition().getY()))
|| ((source.getPosition().getX() < target.getPosition().getX()) && (source
.getPosition().getY() > target.getPosition().getY()))) {
yPoints[3] = yPoints[0] + 2;
yPoints[2] = yPoints[1] + 2;
} else {
yPoints[3] = yPoints[0] - 2;
yPoints[2] = yPoints[1] - 2;
}
g.setColor(source.getOwner().getColour().getColour());
g.fillPolygon(xPoints, yPoints, 4);
g.setColor(Color.black);
g.drawPolygon(xPoints, yPoints, 4);
// if this is mutual fire, draw a half-and-half line
for (EntityAction action : game.getActionsVector()) {
if (action instanceof AttackAction otherAttack) {
if ((attack.getEntityId() == otherAttack.getTargetId())
&& (otherAttack.getEntityId() == attack.getTargetId())) {
// attackTarget _must_ be an entity since it's shooting back
// (?)
Entity attackTarget = game.getEntity(otherAttack.getEntityId());
if (attackTarget != null) {
Player attackOwner = attackTarget.getOwner();
if (attackOwner != null) {
g.setColor(attackOwner.getColour().getColour());
}
}
xPoints[0] = xPoints[3];
yPoints[0] = yPoints[3];
xPoints[1] = xPoints[2];
yPoints[1] = yPoints[2];
xPoints[2] = xPoints[1] + 2;
xPoints[3] = xPoints[0] + 2;
if (((source.getPosition().getX() > target.getPosition().getX())
&& (source.getPosition().getY() < target.getPosition().getY()))
|| ((source.getPosition().getX() < target.getPosition().getX())
&& (source.getPosition().getY() > target.getPosition().getY()))) {
yPoints[3] = yPoints[0] + 2;
yPoints[2] = yPoints[1] + 2;
} else {
yPoints[3] = yPoints[0] - 2;
yPoints[2] = yPoints[1] - 2;
}
g.fillPolygon(xPoints, yPoints, 4);
g.setColor(Color.black);
g.drawPolygon(xPoints, yPoints, 4);
break;
}
}
}
}
public static Color changeColorForDestroyedUnit(Color color, int alpha) {
color = color.brighter();
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
/** Draws the symbol for a single entity. Checks visibility in double-blind. */
private void paintUnit(Graphics g, Entity entity, boolean removedFromGame) {
int x = entity.getPosition().getX();
int y = entity.getPosition().getY();
int baseX = coordsXToPixel(x);
int baseY = coordsYtoPixel(y, x);
if (EntityVisibilityUtils.onlyDetectedBySensors(getLocalPlayer(), entity) && !removedFromGame) {
// This unit is visible only as a sensor Return
String sensorReturn = "?";
Font font = new Font(MMConstants.FONT_SANS_SERIF, Font.BOLD, FONT_SIZE[zoom]);
int width = getFontMetrics(font).stringWidth(sensorReturn) / 2;
int height = getFontMetrics(font).getHeight() / 2 - 2;
g.setFont(font);
g.setColor(Color.RED);
g.drawString(sensorReturn, baseX - width, baseY + height);
return;
} else if (!EntityVisibilityUtils.detectedOrHasVisual(getLocalPlayer(), game, entity)) {
// This unit is not visible, don't draw it
return;
}
Graphics2D g2 = (Graphics2D) g;
Stroke saveStroke = g2.getStroke();
AffineTransform saveTransform = g2.getTransform();
boolean stratOpsSymbols = GUIP.getMmSymbol();
// Choose player or team color depending on preferences
Color iconColor = entity.getOwner().getColour().getColour(false);
if (GUIP.getTeamColoring() && (client != null)) {
boolean isLocalTeam = (getLocalPlayer() != null) && (entity.getOwner().getTeam()
== getLocalPlayer().getTeam());
boolean isLocalPlayer = entity.getOwner().equals(getLocalPlayer());
if (isLocalPlayer) {
iconColor = GUIP.getMyUnitColor();
} else if (isLocalTeam) {
iconColor = GUIP.getAllyUnitColor();
} else {
iconColor = GUIP.getEnemyUnitColor();
}
}
if (removedFromGame) {
iconColor = changeColorForDestroyedUnit(iconColor.brighter(), DESTROYED_UNIT_ALPHA);
}
// Transform for placement and scaling
var placement = AffineTransform.getTranslateInstance(baseX, baseY);
placement.scale(UNIT_SCALE[zoom] / 100.0d, UNIT_SCALE[zoom] / 100.0d);
g2.transform(placement);
// Add a position shift if multiple units are present in this hex
Coords p = entity.getPosition();
int eStack = multiUnits.getOrDefault(p, 0) + 1;
multiUnits.put(p, eStack);
g2.translate(20 * (eStack - 1), -20 * (eStack - 1));
Path2D form = MinimapUnitSymbols.getForm(entity);
Color borderColor = entity.moved != EntityMovementType.MOVE_NONE && !removedFromGame ?
Color.BLACK :
Color.WHITE;
if (removedFromGame) {
borderColor = changeColorForDestroyedUnit(borderColor.brighter(), DESTROYED_UNIT_ALPHA);
}
Color fontColor = Color.BLACK;
if (removedFromGame) {
fontColor = changeColorForDestroyedUnit(fontColor.brighter(), DESTROYED_UNIT_ALPHA);
}
float outerBorderWidth = 30f;
float innerBorderWidth = 10f;
float formStrokeWidth = 20f;
if (stratOpsSymbols) {
// White border to set off the icon from the background
g2.setStroke(new BasicStroke(outerBorderWidth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
g2.setColor(fontColor);
g2.draw(STRAT_BASE_RECT);
g2.fill(STRAT_BASE_RECT);
g.setColor(fontColor);
// Set a thin brush for filled areas (leave a thick brush for line symbols
if ((entity instanceof Mek) || (entity instanceof ProtoMek)
|| (entity instanceof VTOL) || (entity.isAero())) {
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
} else {
g2.setStroke(new BasicStroke(formStrokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
}
// Fill the form in player color / team color
g.setColor(iconColor);
g2.fill(form);
g2.setColor(fontColor);
if ((entity instanceof ProtoMek) || (entity instanceof Mek) || (entity instanceof Aero)) {
String s = "";
if (entity instanceof ProtoMek) {
s = "P";
} else if ((entity instanceof Mek) && ((Mek) entity).isIndustrial()) {
s = "I";
} else if (entity.getWeightClass() < 6) {
s = STRAT_WEIGHTS[entity.getWeightClass()];
}
if (!s.isBlank()) {
int fontType = Font.BOLD;
if (removedFromGame) {
fontType = Font.PLAIN;
}
var fontContext = new FontRenderContext(null, true, true);
var font = new Font(MMConstants.FONT_SANS_SERIF, fontType, 100);
FontMetrics currentMetrics = getFontMetrics(font);
int stringWidth = currentMetrics.stringWidth(s);
GlyphVector gv = font.createGlyphVector(fontContext, s);
g2.fill(gv.getOutline((int) STRAT_CX - (float) stringWidth / 2,
(float) STRAT_SYMBOL_SIZE.getHeight() / 3.0f));
}
} else if (entity instanceof MekWarrior) {
g2.setColor(fontColor);
g2.fillOval(-25, -25, 50, 50);
}
// Draw the unit icon in black
g2.draw(form);
// Rectangle border for all units
g2.setColor(borderColor);
g2.setStroke(new BasicStroke(innerBorderWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.draw(STRAT_BASE_RECT);
} else {
// Standard symbols
// White border to set off the icon from the background
g2.setStroke(new BasicStroke(outerBorderWidth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
g2.setColor(fontColor);
g2.draw(form);
// Fill the form in player color / team color
g2.setColor(iconColor);
g2.fill(form);
// Black border
g2.setColor(borderColor);
g2.setStroke(new BasicStroke(innerBorderWidth / 2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
g2.draw(form);
if (removedFromGame) {
g2.draw(STRAT_DESTROYED);
g2.fill(STRAT_DESTROYED);
}
}
if (GUIP.showUnitDisplayNamesOnMinimap()) {
// write unit ID and name to the minimap:
g2.setColor(fontColor);
int fontType = Font.BOLD;
if (removedFromGame) {
fontType = Font.PLAIN;
}
g2.setStroke(new BasicStroke(innerBorderWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
String s = entity.getShortName();
var fontContext = new FontRenderContext(null, true, true);
var font = new Font(MMConstants.FONT_SANS_SERIF, fontType, 75);
GlyphVector gv = font.createGlyphVector(fontContext, s);
g2.fill(gv.getOutline((float) -STRAT_SYMBOL_SIZE.getWidth() / 3f,
(float) -STRAT_SYMBOL_SIZE.getHeight() / 5 * 4));
}
// If the unit is destroyed, it gets a strike on it.
if (removedFromGame) {
g2.setColor(fontColor);
g2.setStroke(new BasicStroke(formStrokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
if (stratOpsSymbols) {
g2.draw(STRAT_DESTROYED);
} else {
g2.draw(STD_DESTROYED);
}
}
g2.setStroke(new BasicStroke(innerBorderWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
if (GUIP.getDrawFacingArrowsOnMiniMap() && !removedFromGame && !entity.isInfantry()) {
// draw facing arrow
var facing = entity.getFacing();
if (facing > -1) {
g2.setColor(fontColor);
g2.rotate(Math.toRadians(facing * 60));
g2.draw(FACING_ARROW);
g.setColor(iconColor);
g2.fill(FACING_ARROW);
}
}
g2.setTransform(saveTransform);
// Create a colored circle if this is the selected unit
Entity se = (clientGui == null) ?
null :
clientGui instanceof ClientGUI ? ((ClientGUI) clientGui).getDisplayedUnit() : null;
if (entity == se) {
int rad = stratOpsSymbols ? 2 * unitSize - 1 : unitSize + unitSize / 2;
Color color = GUIP.getUnitSelectedColor();
g2.setColor(color.darker());
g2.setStroke(new BasicStroke((float) unitSize / 5 + 1));
g2.drawOval(baseX - rad, baseY - rad, rad * 2, rad * 2);
}
g2.setStroke(saveStroke);
}
/** Draws the symbol for a single entity. Checks visibility in double blind. */
private void paintSensor(Graphics g, Entity entity) {
if (EntityVisibilityUtils.onlyDetectedBySensors(getLocalPlayer(), entity)) {
// This unit is visible only as a sensor Return, we dont know the range of its sensor yet
return;
} else if (!EntityVisibilityUtils.detectedOrHasVisual(getLocalPlayer(), game, entity)) {
// This unit is not visible, don't draw it
return;
}
int maxSensorRange = 0;
int minSensorRange = 0;
int ecmRange = entity.getECMRange();
boolean ecmActive = entity.hasActiveECM();
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_TAC_OPS_SENSORS)) {
int bracket = Compute.getSensorRangeBracket(entity, null, null);
int range = Compute.getSensorRangeByBracket(game, entity, null, null);
maxSensorRange = bracket * range;
minSensorRange = Math.max((bracket - 1) * range, 0);
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_INCLUSIVE_SENSOR_RANGE)) {
minSensorRange = 0;
}
}
// Choose player or team color depending on preferences
Color iconColor = entity.getOwner().getColour().getColour(false);
if (GUIP.getTeamColoring() && (client != null)) {
boolean isLocalTeam = (getLocalPlayer() != null) && (entity.getOwner().getTeam()
== getLocalPlayer().getTeam());
boolean isLocalPlayer = entity.getOwner().equals(getLocalPlayer());
if (isLocalPlayer) {
iconColor = GUIP.getMyUnitColor();
} else if (isLocalTeam) {
iconColor = GUIP.getAllyUnitColor();
} else {
iconColor = GUIP.getEnemyUnitColor();
}
}
Graphics2D g2 = (Graphics2D) g;
Stroke saveStroke = g2.getStroke();
g2.setStroke(new BasicStroke(2));
Color iconColorSemiTransparent = new Color(iconColor.getRed(), iconColor.getGreen(), iconColor.getBlue(), 200);
g2.setColor(iconColorSemiTransparent);
var origin = entity.getPosition();
if (maxSensorRange > 0) {
paintSensorRange(maxSensorRange, true, origin, g2);
}
if (minSensorRange > 0) {
paintSensorRange(minSensorRange, false, origin, g2);
}
if (ecmActive && ecmRange > 0) {
Stroke dashed = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
0, new float[] { 6, 3 }, 3);
g2.setStroke(dashed);
paintSensorRange(ecmRange, true, origin, g2);
}
g2.setStroke(saveStroke);
}
private void paintSensorRange(int sensorRange, boolean offsetOut, Coords origin, Graphics2D g2) {
int xo;
int yo;
var sensor = new Path2D.Double();
var internalOrExternal = offsetOut ? 1 : -1;
for (int i = 0; i < 6; i++) {
var movingCoord = origin.translated(i, sensorRange + internalOrExternal);
xo = coordsXToPixel(movingCoord.getX());
yo = coordsYtoPixel(movingCoord.getY(), movingCoord.getX());
if (i == 0) {
sensor.moveTo(xo, yo);
} else {
sensor.lineTo(xo, yo);
}
}
sensor.closePath();
g2.draw(sensor);
}
private int coordsYtoPixel(int y, int x) {
return (2 * y + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom] + topMargin;
}
private int coordsXToPixel(int x) {
return x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom]) + leftMargin + HEX_SIDE[zoom];
}
/** Draws the road elements previously assembles into the roadHexes list. */
private void paintRoads(Graphics g) {
int exits;
int baseX;
int baseY;
int x;
int y;
int[] xPoints = new int[4];
int[] yPoints = new int[4];
g.setColor(terrainColors[ROAD]);
for (int[] roadEntry : roadHexes) {
x = roadEntry[0];
y = roadEntry[1];
baseX = (x * (HEX_SIDE[zoom] + HEX_SIDE_BY_SIN30[zoom])) + leftMargin + HEX_SIDE[zoom];
baseY = (((2 * y) + 1 + (x % 2)) * HEX_SIDE_BY_COS30[zoom]) + topMargin;
exits = roadEntry[2];
// Is there a North exit?
if (0 != (exits & 1)) {
xPoints[0] = baseX - HALF_ROAD_WIDTH[zoom];
yPoints[0] = baseY;
xPoints[1] = baseX - HALF_ROAD_WIDTH[zoom];
yPoints[1] = baseY - HEX_SIDE_BY_COS30[zoom];
xPoints[2] = baseX + HALF_ROAD_WIDTH[zoom];
yPoints[2] = baseY - HEX_SIDE_BY_COS30[zoom];
xPoints[3] = baseX + HALF_ROAD_WIDTH[zoom];
yPoints[3] = baseY;
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
// Is there a North-East exit?
if (0 != (exits & 2)) {
xPoints[0] = baseX - HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[0] = baseY - HALF_ROAD_WIDTH_BY_COS30[zoom];
xPoints[1] = Math.round((baseX + ((3 * HEX_SIDE[zoom]) / 4.0f)) - HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[1] = Math.round(baseY - (HEX_SIDE_BY_COS30[zoom] / 2.0f) - HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[2] = xPoints[1] + (2 * HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[2] = yPoints[1] + (2 * HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[3] = baseX + HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[3] = baseY + HALF_ROAD_WIDTH_BY_COS30[zoom];
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
// Is there a South-East exit?
if (0 != (exits & 4)) {
xPoints[0] = baseX + HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[0] = baseY - HALF_ROAD_WIDTH_BY_COS30[zoom];
xPoints[1] = Math.round(baseX + ((3 * HEX_SIDE[zoom]) / 4.0f) + HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[1] = Math.round((baseY + (HEX_SIDE_BY_COS30[zoom] / 2.0f)) - HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[2] = xPoints[1] - (2 * HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[2] = yPoints[1] + (2 * HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[3] = baseX - HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[3] = baseY + HALF_ROAD_WIDTH_BY_COS30[zoom];
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
// Is there a South exit?
if (0 != (exits & 8)) {
xPoints[0] = baseX + HALF_ROAD_WIDTH[zoom];
yPoints[0] = baseY;
xPoints[1] = baseX + HALF_ROAD_WIDTH[zoom];
yPoints[1] = baseY + HEX_SIDE_BY_COS30[zoom];
xPoints[2] = baseX - HALF_ROAD_WIDTH[zoom];
yPoints[2] = baseY + HEX_SIDE_BY_COS30[zoom];
xPoints[3] = baseX - HALF_ROAD_WIDTH[zoom];
yPoints[3] = baseY;
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
// Is there a South-West exit?
if (0 != (exits & 16)) {
xPoints[0] = baseX + HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[0] = baseY + HALF_ROAD_WIDTH_BY_COS30[zoom];
xPoints[1] = Math.round((baseX - ((3 * HEX_SIDE[zoom]) / 4.0f)) + HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[1] = Math.round(baseY + (HEX_SIDE_BY_COS30[zoom] / 2.0f) + HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[2] = xPoints[1] - (2 * HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[2] = yPoints[1] - (2 * HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[3] = baseX - HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[3] = baseY - HALF_ROAD_WIDTH_BY_COS30[zoom];
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
// Is there a North-West exit?
if (0 != (exits & 32)) {
xPoints[0] = baseX - HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[0] = baseY + HALF_ROAD_WIDTH_BY_COS30[zoom];
xPoints[1] = Math.round(baseX - ((3 * HEX_SIDE[zoom]) / 4.0f) - HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[1] = Math.round((baseY - (HEX_SIDE_BY_COS30[zoom] / 2.0f)) + HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[2] = xPoints[1] + (2 * HALF_ROAD_WIDTH_BY_SIN30[zoom]);
yPoints[2] = yPoints[1] - (2 * HALF_ROAD_WIDTH_BY_COS30[zoom]);
xPoints[3] = baseX + HALF_ROAD_WIDTH_BY_SIN30[zoom];
yPoints[3] = baseY - HALF_ROAD_WIDTH_BY_COS30[zoom];
g.drawPolygon(xPoints, yPoints, 4);
g.fillPolygon(xPoints, yPoints, 4);
}
}
}
/** If the given hex contains ROAD or BRIDGE, adds an entry to roadHexes. */
private void addRoadElements(Hex hex, int boardX, int boardY) {
if (hex.containsAnyTerrainOf(ROAD, BRIDGE)) {
var terrain = hex.getAnyTerrainOf(ROAD, BRIDGE);
roadHexes.add(new int[] { boardX, boardY, terrain.getExits() });
}
}
private Color terrainColor(Hex hex) {
Color terrColor = terrainColors[0];
if (hex.getLevel() < 0) {
terrColor = SINKHOLE;
}
int terrain = 0;
// Check for Smoke and Fire - this overrides any other colors
if (hex.containsTerrain(SMOKE) && hex.containsTerrain(FIRE)) {
terrColor = SMOKE_AND_FIRE;
// Check for Fire - this overrides any other colors
} else if (hex.containsTerrain(FIRE)) {
terrColor = terrainColors[FIRE];
} else { // Otherwise, color based on terrains - higher valued terrains take color
// precedence
for (int j = terrainColors.length - 1; j >= 0; j--) {
if ((hex.getTerrain(j) != null) && (terrainColors[j] != null)) {
if ((j == ROAD) || (j == BRIDGE)) {
continue;
}
terrColor = terrainColors[j];
terrain = j;
// make heavy woods darker
if (((j == WOODS) || (j == JUNGLE)) && (hex.getTerrain(j).getLevel() == 2)) {
terrColor = HEAVY_WOODS;
}
if (((j == WOODS) || (j == JUNGLE)) && (hex.getTerrain(j).getLevel() > 2)) {
terrColor = ULTRA_HEAVY_WOODS;
}
break;
}
}
}
return switch (terrain) {
case 0, WOODS, JUNGLE, ROUGH, RUBBLE, WATER, PAVEMENT, ICE, FIELDS ->
adjustByLevel(terrColor, Math.abs(hex.floor()));
case FUEL_TANK, BUILDING -> adjustByLevel(terrColor, Math.abs(hex.ceiling()));
default -> terrColor;
};
}
private Color adjustByLevel(Color color, int level) {
if (level > 10) {
level = 10;
}
int r = color.getRed() - (level * 15);
int g = color.getGreen() - (level * 15);
int b = color.getBlue() - (level * 15);
if (r < 0) {
r = 0;
}
if (g < 0) {
g = 0;
}
if (b < 0) {
b = 0;
}
return new Color(r, g, b);
}
/** Returns a Board Coord for a given x and y pixel position. */
private Coords translateCoords(int x, int y) {
int gridX = (x / (HEX_SIDE_BY_SIN30[zoom] + HEX_SIDE[zoom]));
int restX = x % (HEX_SIDE_BY_SIN30[zoom] + HEX_SIDE[zoom]);
int gridY = (y / (2 * HEX_SIDE_BY_COS30[zoom]));
int restY = y % (2 * HEX_SIDE_BY_COS30[zoom]);
boolean evenColumn = (gridX & 1) == 0;
if (restY < HEX_SIDE_BY_COS30[zoom]) {
if (evenColumn) {
if (restX < ((((restY - HEX_SIDE_BY_COS30[zoom])
* HEX_SIDE_BY_SIN30[zoom]) / HEX_SIDE_BY_COS30[zoom]) * -1)) {
gridX--;
gridY--;
}
} else {
if (restX < ((restY * HEX_SIDE_BY_SIN30[zoom]) / HEX_SIDE_BY_COS30[zoom])) {
gridX--;
} else {
gridY--;
}
}
} else {
if (evenColumn) {
if (restX < (((restY - HEX_SIDE_BY_COS30[zoom])
* HEX_SIDE_BY_SIN30[zoom]) / HEX_SIDE_BY_COS30[zoom])) {
gridX--;
}
} else {
if (restX < ((((restY - (2 * HEX_SIDE_BY_COS30[zoom]))
* HEX_SIDE_BY_SIN30[zoom]) / HEX_SIDE_BY_COS30[zoom]) * -1)) {
gridX--;
}
}
}
if (gridX < 0) {
gridX = 0;
}
if (gridY < 0) {
gridY = 0;
}
return new Coords(gridX, gridY);
}
/** Zooms out (smaller hexes), if possible. */
private void zoomOut() {
if (zoom > MIM_ZOOM) {
zoom--;
initializeMap();
GUIP.setMinimapZoom(zoom);
}
}
/** Zooms in (larger hexes), if possible. */
private void zoomIn() {
if (zoom < MAX_ZOOM) {
zoom++;
initializeMap();
GUIP.setMinimapZoom(zoom);
}
}
public void resetZoom() {
zoom = MIM_ZOOM;
initializeMap();
GUIP.setMinimapZoom(zoom);
}
private void processMouseRelease(int x, int y, int modifiers) {
if (!new Rectangle(getSize()).contains(x, y)) {
return;
}
if ((modifiers & InputEvent.CTRL_DOWN_MASK) != 0) {
bv.checkLOS(translateCoords(x - leftMargin, y - topMargin));
}
if (dragging) {
return;
}
if (y <= getSize().height - BUTTON_HEIGHT) {
// This is a click on the map itself
centerOnPos(x, y);
} else {
// This is a click on the green control button bar
if (minimized) {
setSize(getSize().width, heightBuffer);
mapImage = ImageUtil.createAcceleratedImage(getSize().width, heightBuffer);
minimized = false;
initializeMap();
} else {
if (x < BUTTON_HEIGHT) {
zoomOut();
} else if ((x < 2 * BUTTON_HEIGHT) && (zoom >= MIM_ZOOM_FOR_HEIGHT)) {
setHeightDisplay(((++heightDisplayMode) > NBR_HEIGHT_MODES) ? 0 : heightDisplayMode);
} else if ((x < 3 * BUTTON_HEIGHT) && (zoom >= MIM_ZOOM_FOR_HEIGHT)) {
setSymbolsDisplay(((++symbolsDisplayMode) > NBR_SYMBOLS_MODES) ? 0 : symbolsDisplayMode);
} else if (x > (getSize().width - BUTTON_HEIGHT)) {
zoomIn();
} else {
heightBuffer = getSize().height;
setSize(getSize().width, BUTTON_HEIGHT);
mapImage = ImageUtil.createAcceleratedImage(Math.max(1, getSize().width), BUTTON_HEIGHT);
minimized = true;
initializeMap();
}
}
}
}
private void setSensorRangeDisplay(boolean state) {
drawSensorRangeOnMiniMap = state;
GUIP.setDrawSensorRangeOnMiniMap(state);
initializeMap();
}
private void setFacingArrowsDisplay(boolean state) {
drawFacingArrowsOnMiniMap = state;
GUIP.setDrawFacingArrowsOnMiniMap(state);
initializeMap();
}
private void setPaintBordersDisplay(boolean state) {
paintBorders = state;
GUIP.setPaintBorders(state);
initializeMap();
}
private void setSymbolsDisplay(int i) {
symbolsDisplayMode = i;
GUIP.setMiniMapSymbolsDisplayMode(i);
initializeMap();
}
private void setHeightDisplay(int i) {
heightDisplayMode = i;
GUIP.setMinimapHeightDisplayMode(i);
initializeMap();
}
/**
* Changes the currently shown {@link BoardView} to this minimap's own board.
*/
private void ShowThisBoardView() {
if (clientGui instanceof AbstractClientGUI abstractClientGUI) {
abstractClientGUI.showBoardView(boardId);
}
}
/**
* Centers the BoardView connected to the Minimap on x, y in the Minimap's pixel coordinates.
*/
private void centerOnPos(double x, double y) {
ShowThisBoardView();
bv.centerOnPointRel(
((x - leftMargin)) / ((HEX_SIDE_BY_SIN30[zoom] + HEX_SIDE[zoom]) * board.getWidth()),
((y - topMargin)) / (2 * HEX_SIDE_BY_COS30[zoom] * board.getHeight()));
bv.stopSoftCentering();
repaint();
}
private final BoardListener boardListener = new BoardListenerAdapter() {
@Override
public void boardNewBoard(BoardEvent b) {
initializeMap();
}
@Override
public void boardChangedHex(BoardEvent b) {
// This must be tolerant since it might be called without notifying us of the board size first
int x = b.getCoords().getX();
int y = b.getCoords().getY();
if ((x >= dirty.length) || (y >= dirty[x].length)) {
dirtyMap = true;
} else {
dirty[x / 10][y / 10] = true;
}
refreshMap();
}
};
BoardViewListener boardViewListener = new BoardViewListenerAdapter() {
@Override
public void hexCursor(BoardViewEvent b) {
update();
}
@Override
public void hexMoused(BoardViewEvent b) {
repaint();
}
@Override
public void boardHexHighlighted(BoardViewEvent b) {
update();
}
@Override
public void hexSelected(BoardViewEvent b) {
update();
}
@Override
public void firstLOSHex(BoardViewEvent b) {
secondLOS = null;
firstLOS = b.getCoords();
refreshMap();
}
@Override
public void secondLOSHex(BoardViewEvent b) {
secondLOS = b.getCoords();
refreshMap();
}
private void update() {
firstLOS = null;
secondLOS = null;
refreshMap();
}
};
MouseListener mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
if (me.getButton() == MouseEvent.BUTTON1) {
Point mapPoint = SwingUtilities.convertPoint(dialog, me.getX(), me.getY(), MinimapPanel.this);
processMouseRelease(mapPoint.x, mapPoint.y, me.getModifiersEx());
dragging = false;
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
showPopup(me);
} else {
ShowThisBoardView();
}
}
@Override
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger()) {
showPopup(me);
} else {
ShowThisBoardView();
}
}
};
MouseMotionListener mouseMotionListener = new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent me) {
Point mapPoint = SwingUtilities.convertPoint(dialog, me.getX(), me.getY(), MinimapPanel.this);
if (new Rectangle(getSize()).contains(mapPoint.x, mapPoint.y)) {
if (!dragging) {
dragging = true;
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
centerOnPos(mapPoint.x, mapPoint.y);
}
}
};
MouseWheelListener mouseWheelListener = new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent we) {
Point mapPoint = SwingUtilities.convertPoint(dialog, we.getX(), we.getY(), MinimapPanel.this);
if (new Rectangle(getSize()).contains(mapPoint.x, mapPoint.y)) {
if (we.getWheelRotation() > 0 ^ GUIP.getMouseWheelZoomFlip()) {
zoomIn();
} else {
zoomOut();
}
}
}
};
ComponentListener componentListener = new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
refreshMap();
}
};
private void showPopup(MouseEvent me) {
ScalingPopup popup = new ScalingPopup();
JMenu zoomMenu = new JMenu(Messages.getString("Minimap.menu.Zoom", zoom));
zoomMenu.add(menuItem(Messages.getString("Minimap.menu.ZoomIn"),
ACTION_ZOOM_IN,
zoom != MAX_ZOOM,
l -> this.zoomIn(),
false));
zoomMenu.add(menuItem(Messages.getString("Minimap.menu.ZoomOut"),
ACTION_ZOOM_OUT,
zoom != MIM_ZOOM,
l -> this.zoomOut(),
false));
popup.add(zoomMenu);
JMenu heightMenu = new JMenu(Messages.getString("Minimap.menu.ShowHeight"));
heightMenu.add(menuItem(Messages.getString("Minimap.menu.ShowHeightNone"),
ACTION_HEIGHT_NONE,
zoom >= MIM_ZOOM_FOR_HEIGHT,
l -> this.setHeightDisplay(SHOW_NO_HEIGHT),
heightDisplayMode == SHOW_NO_HEIGHT));
heightMenu.add(menuItem(Messages.getString("Minimap.menu.ShowHeightGround"),
ACTION_HEIGHT_GROUND,
zoom >= MIM_ZOOM_FOR_HEIGHT,
l -> this.setHeightDisplay(SHOW_GROUND_HEIGHT),
heightDisplayMode == SHOW_GROUND_HEIGHT));
heightMenu.add(menuItem(Messages.getString("Minimap.menu.ShowHeightBuilding"),
ACTION_HEIGHT_BUILDING,
zoom >= MIM_ZOOM_FOR_HEIGHT,
l -> this.setHeightDisplay(SHOW_BUILDING_HEIGHT),
heightDisplayMode == SHOW_BUILDING_HEIGHT));
heightMenu.add(menuItem(Messages.getString("Minimap.menu.ShowHeightTotal"),
ACTION_HEIGHT_TOTAL,
zoom >= MIM_ZOOM_FOR_HEIGHT,
l -> this.setHeightDisplay(SHOW_TOTAL_HEIGHT),
heightDisplayMode == SHOW_TOTAL_HEIGHT));
popup.add(heightMenu);
JMenu symbolsMenu = new JMenu(Messages.getString("Minimap.menu.ShowSymbols"));
symbolsMenu.add(menuItem(Messages.getString("Minimap.menu.ShowSymbolsNoSymbols"),
ACTION_SYMBOLS_NO,
true,
l -> this.setSymbolsDisplay(SHOW_NO_SYMBOLS),
symbolsDisplayMode == SHOW_NO_SYMBOLS));
symbolsMenu.add(menuItem(Messages.getString("Minimap.menu.ShowSymbolsSymbols"),
ACTION_SYMBOLS_SHOW,
true,
l -> this.setSymbolsDisplay(SHOW_SYMBOLS),
symbolsDisplayMode == SHOW_SYMBOLS));
JCheckBoxMenuItem toggleDrawSensor = new JCheckBoxMenuItem(Messages.getString(
"Minimap.menu.ToggleShowSensorRange"));
toggleDrawSensor.addActionListener(l -> setSensorRangeDisplay(!drawSensorRangeOnMiniMap));
toggleDrawSensor.setSelected(drawSensorRangeOnMiniMap);
symbolsMenu.add(toggleDrawSensor);
JCheckBoxMenuItem toggleDrawFacing = new JCheckBoxMenuItem(Messages.getString(
"Minimap.menu.ToggleDrawFacingArrows"));
toggleDrawFacing.addActionListener(l -> setFacingArrowsDisplay(!drawFacingArrowsOnMiniMap));
toggleDrawFacing.setSelected(drawFacingArrowsOnMiniMap);
symbolsMenu.add(toggleDrawFacing);
JCheckBoxMenuItem togglePaintBorders = new JCheckBoxMenuItem(Messages.getString(
"Minimap.menu.ToggleDrawHexBorder"));
togglePaintBorders.addActionListener(l -> setPaintBordersDisplay(!paintBorders));
togglePaintBorders.setSelected(paintBorders);
symbolsMenu.add(togglePaintBorders);
popup.add(symbolsMenu);
popup.show(this, me.getX(), me.getY());
}
public JCheckBoxMenuItem menuItem(String text, String cmd, boolean enabled,
ActionListener listener, boolean checked) {
JCheckBoxMenuItem result = new JCheckBoxMenuItem(text);
result.setActionCommand(cmd);
result.addActionListener(listener);
result.setEnabled(enabled);
result.setSelected(checked);
return result;
}
@Override
public void preferenceChange(PreferenceChangeEvent e) {
if (e.getName().equals(GUIPreferences.MM_SYMBOL)
|| e.getName().equals(GUIPreferences.TEAM_COLORING)) {
refreshMap();
}
}
}
| 412 | 0.938384 | 1 | 0.938384 | game-dev | MEDIA | 0.679102 | game-dev,desktop-app | 0.756277 | 1 | 0.756277 |
TheFlyingFoool/DuckGameRebuilt | 2,547 | DuckGame/src/DuckGame/Stuff/SpringLeft.cs | namespace DuckGame
{
[EditorGroup("Stuff|Springs")]
[BaggedProperty("isInDemo", false)]
[BaggedProperty("previewPriority", false)]
public class SpringLeft : Spring
{
public override bool flipHorizontal
{
get => _flipHorizontal;
set
{
_flipHorizontal = value;
offDir = _flipHorizontal ? (sbyte)-1 : (sbyte)1;
if (!_flipHorizontal)
{
center = new Vec2(8f, 7f);
collisionOffset = new Vec2(0f, -8f);
collisionSize = new Vec2(8f, 16f);
angle = -1.5708f;
hugWalls = WallHug.Right;
}
else
{
center = new Vec2(8f, 7f);
collisionOffset = new Vec2(-8f, -8f);
collisionSize = new Vec2(8f, 16f);
angle = 1.5708f;
hugWalls = WallHug.Left;
}
}
}
public SpringLeft(float xpos, float ypos)
: base(xpos, ypos)
{
UpdateSprite();
center = new Vec2(8f, 7f);
collisionOffset = new Vec2(0f, -8f);
collisionSize = new Vec2(8f, 16f);
depth = -0.5f;
_editorName = "Spring Left";
editorTooltip = "Can't reach a high platform or want to get somewhere fast? That's why we built springs.";
physicsMaterial = PhysicsMaterial.Metal;
editorCycleType = typeof(SpringUpLeft);
angle = -1.5708f;
hugWalls = WallHug.Right;
}
public override void Touch(MaterialThing with)
{
if (with.isServerForObject && with.Sprung(this))
{
if (!_flipHorizontal)
{
if (with.hSpeed > -12f * _mult)
with.hSpeed = -12f * _mult;
}
else if (with.hSpeed < 12f * _mult)
with.hSpeed = 12f * _mult;
if (with is Gun)
(with as Gun).PressAction();
if (with is Duck)
{
(with as Duck).jumping = false;
DoRumble(with as Duck);
}
with.lastHSpeed = with._hSpeed;
with.lastVSpeed = with._vSpeed;
}
SpringUp();
}
public override void Draw() => base.Draw();
}
}
| 412 | 0.893385 | 1 | 0.893385 | game-dev | MEDIA | 0.931783 | game-dev | 0.920329 | 1 | 0.920329 |
armando-genis/Autonomous_Navigation_System | 2,824 | target_waypoint_index/include/target_waypoint_index_node.h | #ifndef TARGET_WAYPOINT_INDEX_NODE_H
#define TARGET_WAYPOINT_INDEX_NODE_H
#include <rclcpp/rclcpp.hpp>
#include <geometry_msgs/msg/point_stamped.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs/msg/pose_with_covariance_stamped.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <nav_msgs/msg/occupancy_grid.hpp>
#include <nav_msgs/msg/path.hpp>
#include <geometry_msgs/msg/polygon.hpp>
#include <geometry_msgs/msg/point32.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
#include <std_msgs/msg/int32.hpp>
#include <tf2/time.h>
#include <Eigen/Dense>
using namespace std;
class target_waypoint_index_node : public rclcpp::Node
{
private:
// colors for the terminal
string green = "\033[1;32m";
string red = "\033[1;31m";
string blue = "\033[1;34m";
string yellow = "\033[1;33m";
string purple = "\033[1;35m";
string reset = "\033[0m";
// Variables from parameters
double lookahead_min = 0.0; // [m]
double lookahead_max = 0.0; // [m]
double mps_alpha = 0.0; // [m/s]
double mps_beta = 0.0; // [m/s]
// Variables of the car position
double current_yaw_ = 0.0; // [rad]
double current_x_ = 0.0; // [m]
double current_y_ = 0.0; // [m]
double current_z_ = 0.0;
double current_velocity_ = 0; // [m/s]
// tf2 buffer & listener
tf2_ros::Buffer tf2_buffer;
tf2_ros::TransformListener tf2_listener;
// Waypoints
vector<Eigen::VectorXd> waypoints; // [x, y, z, yaw]
// waypoints variable for the computation
bool waypoints_in_loop = false;
int closest_waypoint = 0;
int average_distance_count = 0;
float average_distance = 0.0;
float maximum_distance = 0.0;
size_t target_waypoint = 0;
rclcpp::Time last_time_;
// Subscriptions & Publishers
rclcpp::TimerBase::SharedPtr timer_;
// rclcpp::Subscription<visualization_msgs::msg::MarkerArray>::SharedPtr waypoints_subscription_;
rclcpp::Subscription<nav_msgs::msg::Path>::SharedPtr waypoints_subscription_;
// for debugging
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr target_waypoint_pub_;
void marketTargetWaypoint();
// functions
void pub_callback();
void getCurrentRobotState();
void waypoints_callback(const nav_msgs::msg::Path::SharedPtr msg);
double getDistance(Eigen::VectorXd point1, Eigen::VectorXd point2);
double LookAheadDistance();
double getDistanceFromOdom(Eigen::VectorXd wapointPoint);
void waypointsComputation();
public:
target_waypoint_index_node(/* args */);
~target_waypoint_index_node();
};
#endif // TARGET_WAYPOINT_INDEX_NODE_H | 412 | 0.764753 | 1 | 0.764753 | game-dev | MEDIA | 0.268102 | game-dev | 0.672293 | 1 | 0.672293 |
enderneko/Cell | 24,861 | Locales/zhTW.lua | if not LOCALE_zhTW then return end
local L = select( 2, ...).L
L["%s in Utilities must be enabled to make this indicator work."] = "要使用此指示器,必須先啟用工具標籤頁面中的 %s 功能。"
L["%s is required"] = "需要%s"
L["%s lock %s on %s."] = "%s將%s鎖定在%s。"
L["%s unlock %s from %s."] = "%s將%s從%s解鎖。"
L["[Alt+Left-Click] to edit"] = "[Alt+左鍵] 修改"
L["[Ctrl+Left-Click] to reset these settings"] = "[Ctrl+左鍵] 重置這些設定"
L["|cff1Aff1AYes|r - Overwrite"] = "|cff1Aff1A是|r - 取代原有的"
L["|cffff1A1ANo|r - Create New"] = "|cffff1A1A否|r - 建立新的"
L["|cffffb5c5Left-Click:|r cast the spell"] = "|cffffb5c5左鍵:|r 施放技能"
L["|cffffb5c5Right-Click:|r report unaffected"] = "|cffffb5c5左鍵:|r 報告缺少該增益的玩家"
L["+ Stack"] = "層數增加時"
L["+ Stack & Duration"] = "層數與持續時間增加時"
L["A 0-40 integer is required."] = "需要 0 ~ 40 的整數。"
L["A positive integer is required."] = "需要正整數。"
L["A UI reload is required.\nDo it now?"] = [=[需要重新載入介面。
是否要現在立即重新載入?]=]
L["About"] = "關於"
L["ABOUT"] = [=[Cell 團隊框架的靈感來主要來自 CompactRaid 與 Grid2,同時也稍微參考了 Aptechka 和 VuhDo。
Cell 不輕量,也並非全能,其目標是提供良好的用戶體驗。]=]
L["ACCEPTED"] = "已接受"
L["Action"] = "動作"
L["Add"] = "新增"
L["Add new spell"] = "加入新法術"
L["Added |T%d:0|t|cFFFF3030%s(%d)|r into debuff blacklist."] = "已將 |T%d:0|t|cFFFF3030%s(%d)|r 加入減益黑名單。"
L["AFK"] = "暫離"
L["Aggro (bar)"] = "仇恨 (條)"
L["Aggro (blink)"] = "仇恨 (閃爍)"
L["Aggro (border)"] = "仇恨 (邊框)"
L["ALL"] = "全部"
L["all"] = "全部"
L["All Bosses"] = "所有首領"
L["All indicators of %s will be replaced with those in %s"] = "%s 版面配置的所有指示器都將會被替換成 %s 版面配置中的"
L["All snippets have been disabled, due to the version update"] = "由於版本更新,所有程式碼片段都已被停用。"
L["Allow smaller value"] = "允許更小的值"
L["Alpha"] = "透明度"
L["Always"] = "總是"
L["Always Targeting"] = "總是選取目標"
L["Always Update Auras"] = "總是更新增益/減益"
L["Anchor Point"] = "自己的"
L["Anchor To"] = "對齊到"
L["Anchored To"] = "對齊到"
L["Animation"] = "動畫"
L["Any Spells"] = "所有法術"
L["Anyone"] = "任何人"
L["AoE Healing"] = "範圍治療 (團補)"
L["Appearance"] = "外觀"
L["Apply Recommended Scale"] = "套用建議的縮放大小"
L["Arena"] = "競技場"
L["assist"] = "協助"
L["Assist"] = "協助"
L["Aura Icon Options"] = "光環圖示選項"
L["Author"] = "作者"
L["Autorun will be disabled for all code snippets"] = "將停用所有程式碼片段的自動執行"
L["Available slash commands"] = "可用的聊天指令"
L["Background Alpha"] = "背景透明度"
L["Background Color"] = "背景顏色"
L["BACKUP_TIPS"] = "備份並不總是可靠,尤其當它們的年代過於久遠時。建議時常做備份。分享設定檔時,這些備份不包含在內。"
L["BACKUP_TIPS2"] = "各種經典版的玩家請注意:備份不包含其他角色的滑鼠點擊施法與版面自動切換"
L["Backups"] = "備份"
L["Bar"] = "進度條"
L["Bar Animation"] = "條列動畫"
L["Bar Orientation"] = "條列方向"
L["Bars"] = "進度條"
L["Battle Res Timer"] = "戰復計時器"
L["Beat"] = "跳動"
L["BG 1-15"] = "戰場 1-15"
L["BG 16-40"] = "戰場 16-40"
L["Big Debuffs"] = "放大顯示減益"
L["Blacklist Target Player"] = "將目標加入黑名單"
L["Bleed"] = "流血"
L["Blink"] = "閃爍"
L["Blizzard Frames"] = "遊戲內建框架"
L["Block"] = "色塊"
L["Blocks"] = "色塊組"
L["Border"] = "邊框"
L["Border Color"] = "邊框顏色"
L["Boss Name"] = "首領名稱"
L["Boss1 Target"] = "首領1 的目標"
L["Both"] = "全部"
L["BOTTOM"] = "下"
L["BOTTOMLEFT"] = "左下"
L["BOTTOMRIGHT"] = "右下"
L["bottom-to-top"] = "從下到上"
L["Bounce"] = "彈跳"
L["BR"] = "戰復"
L["Buff"] = "增益"
L["Buff List"] = "增益清單"
L["Buff Tracker"] = "增益監控"
L["Buff Tracker icon size is set to %d."] = "將增益監控的圖示大小設為 %d。"
L["buffByMe"] = "只顯示我能施放的增益"
L["Buffs"] = "增益"
L["Buffs Tracker"] = "增益監控"
L["Bug Report & Suggestion"] = "回報 Bug & 建議"
L["Built-in Spells"] = "內建法術"
L["built-in(s)"] = "內建"
L["Button"] = "按鈕"
L["C"] = "職業"
L["Cancel"] = "取消"
L["Can't change options in combat"] = "無法在戰鬥中更改設定"
L["Cast By"] = "來源"
L["cast Inner spell"] = "施放內圈法術"
L["cast Outer spell"] = "施放外圈法術"
L["castByMe"] = "只顯示我施放的增益"
L["Casts"] = "施法"
L["Cell settings will be overwritten!"] = "Cell 的設定會被覆蓋掉!"
L["Cell will report all deaths during a raid encounter."] = "團隊首領戰時,Cell 會通報全部的死亡訊息。"
L["Cell will report first %d deaths during a raid encounter."] = "團隊首領戰時,Cell 會通報前 %d 個死亡訊息。"
L["CENTER"] = "中"
L["change mode / apply changes"] = "切換模式 / 套用變更"
L["Change Over Time"] = "隨時間變化"
L["change the order"] = "調整順序"
L["Changelogs"] = "更新資訊"
L["Check all visible enemy nameplates."] = "檢查所有看得見的敵方血條。"
L["Check If Exists"] = "檢查增益是否存在"
L["Check if your group members need some raid buffs"] = "檢查隊友是否需要某些團隊增益"
L["circledStackNums"] = "用圓圈數字顯示層數"
L["Class Color"] = "職業顏色"
L["Class Color (dark)"] = "職業顏色 (暗)"
L["Class Filter"] = "依職業"
L["Clear"] = "清除"
L["clear"] = "清除"
L["clear unit"] = "清空單位"
L["cleuAurasTips"] = "通過戰鬥記錄事件找出看不到的法術效果"
L["Click to preview"] = "點一下預覽"
L["Click-Castings"] = "滑鼠點擊施法"
L["Close"] = "關閉"
L["Code Snippets"] = "程式碼片段"
L["Color"] = "顏色"
L["Color By"] = "著色"
L["Color Duration Text"] = "著色持續時間文字"
L["Color Thresholds"] = "顏色閥值"
L["Columns"] = "列數"
L["Combat Icon"] = "戰鬥圖示"
L["Combine Groups"] = "合併隊伍"
L["Common"] = "共用"
L["Condition"] = "條件"
L["Confirm"] = "確認"
L["Conflicts Detected!"] = "發現衝突!"
L["Consumables"] = "消耗品"
L["Contains"] = "包含"
L["Copy"] = "複製"
L["Copy indicators from one layout to another"] = "將指示器從一個版面配置複製到另一個版面配置"
L["Create"] = "建立"
L["create a \"Healers\" indicator"] = "建立 \"Healers\" 指示器"
L["Create Backup"] = "建立備份"
L["Create new debuff (id)"] = "建立新的減益 (法術 ID)"
L["Create new indicator"] = "建立新的指示器"
L["Create new layout"] = "建立新的版面配置"
L["Create several buttons for quick casting and buff monitoring"] = "建立幾個快速施法按鈕,並具有簡單的增益監控功能"
L["Crowd Controls"] = "群體控制"
L["Current"] = "目前為"
L["Current Boss"] = "當前首領"
L["Current Profile"] = "目前設定檔"
L["Current Season"] = "當前賽季"
L["Curse"] = "詛咒"
L["Cursor"] = "滑鼠游標"
L["Cursor Left"] = "滑鼠游標左側"
L["Cursor Right"] = "滑鼠游標右側"
L["Custom"] = "自訂"
L["Custom Color"] = "自訂顏色"
L["Custom indicators will not be overwritten, even with same name"] = "即使名稱相同,自訂指示器也不會被覆蓋掉"
L["Custom Nicknames"] = "自訂暱稱"
L["custom(s)"] = "自訂"
L["Data transfer failed..."] = "資料傳輸失敗..."
L["DEAD"] = "死亡"
L["Death Report"] = "死亡通報"
L["Debuff"] = "減益"
L["Debuff already exists."] = "已有這個減益。"
L["Debuff Filter (blacklist)"] = "過濾減益 (黑名單)"
L["Debuff List"] = "減益清單"
L["Debuff Type"] = "減益類型"
L["Debuff Type Color"] = "減益類型顏色"
L["Debuffs"] = "減益"
L["Debug Mode"] = "除錯模式"
L["DECLINED"] = "已拒絕"
L["Default layout"] = "預設版面配置"
L["Defensive Cooldowns"] = "減傷 (自身)"
L["Delete"] = "刪除"
L["Delete backup"] = "刪除備份"
L["Delete debuff?"] = "是否確定要刪除減益?"
L["Delete indicator"] = "是否確定要刪除指示器"
L["Delete layout"] = "是否確定要刪除版面配置"
L["Delete spell?"] = "是否要刪除法術?"
L["Delimiter"] = "分隔符號"
L["Detached"] = "分離"
L["Disabled"] = "停用"
L["Disabled in battlegrounds and arenas"] = "戰場和競技場停用"
L["Discard"] = "取消"
L["discard changes"] = "放棄變更"
L["Disease"] = "疾病"
L["DISPEL"] = "驅散"
L["Dispel Request"] = "請求驅散"
L["Dispellable By Me"] = "只有我能驅散時"
L["dispellableByMe"] = "只顯示我能驅散的減益"
L["Dispels"] = "驅散"
L["Display a gradient texture when the unit receives a heal from your certain healing spells."] = "當單位受到你的特定治療法術的治療時,顯示漸層材質。"
L["Display elapsed time since debuff applied"] = "顯示得到減益後經過的時間"
L["Display One Decimal Place When"] = "圖示持續時間顯示一位小數於"
L["Displayed Per Line"] = "每行/列顯示數量"
L["Do nothing if requested spell/buff already exists on requester"] = "若增益已存在於請求者身上,則不發光"
L["DRINKING"] = "喝水"
L["Due to restrictions of the private aura system, this indicator can only use Blizzard style."] = "由於個人光環系統的限制,該指示器只能使用暴雪樣式。"
L["durationFont"] = "持續時間字體"
L["Edit"] = "編輯"
L["Edit spell"] = "修改法術"
L["Effective"] = "有效"
L["En"] = "英"
L["Enable"] = "啟用"
L["Enable Color Gradient"] = "啟用漸層色"
L["Enable Death Color"] = "啟用死亡顏色"
L["Enable Full Health Color"] = "啟用滿血顏色"
L["Enable Spotlight Frame"] = "啟用特別關注框架"
L["enableBlacklistShortcut"] = "黑名單: Alt+Ctrl+右鍵"
L["Enabled"] = "啟用"
L["enableHighlight"] = "顯著標示單位按鈕"
L["Enter: apply\nESC: discard"] = [=[Enter: 套用
ESC: 取消]=]
L["Entire"] = "整個"
L["Error"] = "錯誤"
L["Even if disabled, the settings below affect \"Externals + Defensives\" indicator"] = "就算被停用,下列的設定也會對 \"減傷 (全部)\" 指示器生效"
L["Export"] = "匯出"
L["External Cooldowns"] = "減傷 (來自他人)"
L["Externals + Defensives"] = "減傷 (全部)"
L["Externals + Defensives, no need to enable all of them"] = "包含了來自他人與自身的減傷,不必將它們全都啟用"
L["Extra Action Button"] = "使用額外快捷鍵"
L["Fade Out Menu"] = "淡出選單"
L["Fade out menu buttons on mouseout"] = "滑鼠移開時淡出選單按鈕"
L["Fade Out These Buttons"] = "淡出這些按鈕"
L["fadeOut"] = "隨時間淡出"
L["Faster Health Updates"] = "更快的血量更新頻率"
L["Filter Auto Switch"] = "過濾自動切換"
L["first %d"] = "前 %d 個"
L["Flash"] = "閃光"
L["Focus"] = "專注"
L["focus"] = "專注目標"
L["Focus Target"] = "專注目標的目標"
L["Font"] = "字體"
L["Font Outline"] = "文字樣式"
L["Font Size"] = "文字大小"
L["Format"] = "格式"
L["Frame Level"] = "框架層級"
L["Frame priorities for LibGetFrame"] = "指定 LibGetFrame 取得單位按鈕的優先順序"
L["Free Cooldown Only"] = "只有當法術不在冷卻中時"
L["Frequency"] = "速度"
L["Friendly NPC Frame"] = "友方 NPC 框架"
L["From"] = "從"
L["From: "] = "來自:"
L["General"] = "一般"
L["GHOST"] = "鬼魂"
L["Glow"] = "發光"
L["Glow Buffs"] = "增益發光"
L["Glow Casts"] = "施法發光"
L["Glow Color"] = "發光顏色"
L["Glow is only available to the spells in the list below"] = "發光只對列表中的法術有效"
L["Glow Options"] = "發光選項"
L["Glow Type"] = "發光類型"
L["Glow unit button when a group member sends a %s request"] = "當隊伍成員請求%s時,顯著標示他的單位按鈕"
L["Glows"] = "發光"
L["Gradient"] = "漸層"
L["Gradient Colors"] = "漸層色"
L["Group Columns"] = "隊伍列數"
L["Group Filters"] = "過濾隊伍"
L["Group Rows"] = "隊伍行數"
L["Group Spacing"] = "隊伍間距"
L["H"] = "英雄"
L["Half"] = "半高"
L["Heal Absorb"] = "治療吸收"
L["Heal Absorbs"] = "治療吸收"
L["Heal Prediction"] = "治療預估"
L["Health"] = "血量"
L["Health Bar"] = "血量條"
L["Health Bar Alpha"] = "血量條透明度"
L["Health Bar Color"] = "血量條顏色"
L["Health Loss Alpha"] = "損失血量透明度"
L["Health Loss Color"] = "損失血量顏色"
L["Health Text"] = "血量文字"
L["Health Thresholds"] = "血量臨界值"
L["Height"] = "高度"
L["Hide"] = "隱藏"
L["Hide Blizzard Frames"] = "隱藏遊戲內建框架"
L["Hide Blizzard Party"] = "隱藏遊戲內建隊伍框架"
L["Hide Blizzard Raid"] = "隱藏遊戲內建團隊框架"
L["hide icon animation"] = "隱藏圖示動畫"
L["Hide in Combat"] = "戰鬥中隱藏"
L["Hide Placeholder Frames"] = "隱藏佔位框"
L["Hide Raid Manager"] = "隱藏團隊管理員面板"
L["Hide Self"] = "隱藏自己"
L["Hide tooltips for units"] = "隱藏單位的浮動提示資訊"
L["hideDamager"] = "隱藏傷害輸出"
L["hideIfEmptyOrFull"] = "當值為滿或空時隱藏"
L["hideInCombat"] = "戰鬥中隱藏"
L["HIGH CPU USAGE"] = "高 CPU 使用量"
L["Highlight Filter (blacklist)"] = "過濾顯著標示 (黑名單)"
L["Highlight Size"] = "顯著標示粗細"
L["Highlight Type"] = "顯著標示類型"
L["Horizontal"] = "水平"
L["Horizontal Gradient"] = "水平漸層"
L["Icon"] = "圖示"
L["Icon Options"] = "圖示選項"
L["Icon Style"] = "圖示樣式"
L["Icons"] = "圖示群組"
L["IDs separated by whitespaces"] = "用空格分隔多個法術ID"
L["If disabled, no check, no reply, just glow"] = "停用時,不檢查冷卻,也不回覆密語,只顯示發光。"
L["If you are a paladin or warrior, and the unit has no buffs from you, a %s icon will be displayed."] = "如果你是聖騎士或戰士,且該單位沒有來自你的增益時,將會顯示%s圖示。"
L["Ignore UNIT_AURA payloads"] = "無視 UNIT_AURA 事件的負載"
L["Import"] = "匯入"
L["Import & Export All Settings"] = "匯入與匯出所有設定"
L["Include Character Settings"] = "包含角色設定"
L["Include Nickname Settings"] = "包含暱稱設定"
L["Incompatible Version"] = "不相容的版本"
L["Indicator Settings"] = "指示器設定"
L["Indicator settings are part of Layout settings which are account-wide."] = "指示器設定是版面配置設定的一部分,是帳號共用的。"
L["Indicator Sync"] = "指示器同步"
L["Indicators"] = "指示器"
L["Inherit: "] = "繼承:"
L["Inner Buff"] = "內圈增益"
L["Input spell id"] = "請輸入法術 ID"
L["instakill"] = "秒殺"
L["Instance Name"] = "副本名稱"
L["Instant Mode"] = "即時模式"
L["Invalid"] = "無效"
L["Invalid layout name."] = "無效的版面配置名稱。"
L["Invalid spell id."] = "無效的法術 ID。"
L["Invalid unit."] = "無效單位。"
L["INVERT"] = "反向選擇"
L["Invert Color"] = "使用反色"
L["It will be renamed if this layout name already exists"] = "如果該版面配置名稱已經存在,將自動重新命名"
L["Item"] = "物品"
L["Known Spells Only"] = "只限已學會的法術"
L["Layout"] = "版面配置"
L["Layout added: %s."] = "已建立版面配置: %s。"
L["Layout Auto Switch"] = "自動切換版面配置"
L["Layout deleted: %s."] = "已刪除版面配置: %s"
L["Layout imported: %s."] = "已匯入版面配置: %s。"
L["Layout renamed: %s to %s."] = "已重新命名版面配置: %s 為 %s。"
L["Layout Setup"] = "版面配置設定"
L["Layouts"] = "版面配置"
L["Leader Icon"] = "隊長圖示"
L["LEFT"] = "左"
L["Left"] = "左"
L["Left Spell"] = "左鍵法術"
L["Left-Click"] = "左鍵"
L["Left-Drag"] = "左鍵拖曳"
L["left-to-right"] = "從左到右"
L["Length"] = "長度"
L["LibHealComm needs to be installed"] = "需要自行安裝 LibHealComm"
L["Lines"] = "線條數"
L["Links"] = "連結"
L["Lock"] = "鎖定"
L["Lock Cell Frames"] = "鎖定 Cell 團隊框架的位置"
L["Macro"] = "巨集"
L["Magic"] = "魔法"
L["Main"] = "主框架"
L["many"] = "很多"
L["Marks Bar"] = "標記工具列"
L["marksTips"] = [=[
|r目標標記
左鍵: |cffffffff在目標上設置標記|r
右鍵: |cffffffff將標記鎖定在目標上 (在你的隊伍中)|r]=]
L["Max Buttons"] = "按鈕數量"
L["Max Columns"] = "最大列數"
L["Max Displayed"] = "最大顯示數量"
L["Max Rows"] = "最大行數"
L["Me"] = "我"
L["menu"] = "選單"
L["Menu"] = "選單"
L["Menu Position"] = "選單位置"
L["Middle"] = "中鍵"
L["mine"] = "我的"
L["Misc"] = "其他"
L["Missing Buff"] = "缺少增益"
L["Missing Buffs"] = "缺少增益"
L["MODERATE CPU USAGE"] = "中等 CPU 使用量"
L["Monochrome"] = "單色"
L["Mouseover Highlight Color"] = "滑鼠指向顯著標示顏色"
L["move"] = "移動"
L["Mover"] = "拖曳我"
L["My Nickname"] = "我的暱稱"
L["Name Color"] = "名字顏色"
L["Name Filter"] = "依名字"
L["Name List"] = "名字列表"
L["Name or Name-Server"] = "角色ID 或 角色ID-伺服器名稱"
L["Name Text"] = "名字"
L["Name Width / UnitButton Width"] = "名字寬度 / 單位按鈕寬度"
L["Name: "] = "名字:"
L["Never"] = "永不"
L["New"] = "新增"
L["New version found (%s). Please visit %s to get the latest version."] = "已有新版本 (%s)。 請到 %s 下載最新版本。"
L["Nickname"] = "暱稱"
L["Nickname Blacklist"] = "暱稱黑名單"
L["Nickname Options"] = "暱稱選項"
L["Nickname Sync"] = "與他人同步暱稱"
L["No"] = "否"
L["No custom debuffs to export!"] = "沒有能夠匯出的自訂減益!"
L["No guarantee of the order of members in each subgroup"] = "不保證每個小隊成員的順序"
L["No Spec"] = "沒有專精"
L["No support for rearrangement of members within a same subgroup"] = "不支援新重新排序同小隊內的成員"
L["None"] = "無"
L["Non-En"] = "中"
L["Normal"] = "一般"
L["Normal + Combat Res"] = "一般 + 戰復"
L["not in combat"] = "非戰鬥中"
L["OFF"] = "關"
L["Offensives Tracker"] = "爆發監控"
L["OFFLINE"] = "離線"
L["ON"] = "開"
L["Only affects duration text"] = "只影響持續時間文字"
L["Only available for Spells"] = "只對法術有效"
L["only in group"] = "只有在隊伍中時"
L["Only one threshold is displayed at a time"] = "同時間只會顯示一個臨界值"
L["Only show during encounter or in mythic+"] = "只在首領戰或 M+ 顯示"
L["Only show when you have permission to do this"] = "只在你有權限這樣做時才會顯示"
L["Only visible to me"] = "只對我自己顯示"
L["onlyEnableNotInCombat"] = "只有當我不在戰鬥中時"
L["onlyShowOvershields"] = "只顯示超過血量上限的護盾"
L["onlyShowTopGlow"] = "只有優先順序最高的減益會發光"
L["Options"] = "選項"
L["Options UI Accent Color"] = "選項介面強調色"
L["Options UI Font Size"] = "設定選項介面文字大小"
L["Orientation"] = "方向"
L["Others"] = "其他人"
L["Out of Range Alpha"] = "超出範圍透明度"
L["Outdoor"] = "野外"
L["Outer Buff"] = "外圈增益"
L["Outline"] = "外框"
L["Overlay"] = "疊層"
L["Overshield Texture"] = "超過血量上限的護盾材質"
L["Overwrite Click-Casting"] = "覆蓋點擊施法"
L["Overwrite Layout"] = "取代版面配置"
L["P"] = "PvP"
L["Particles"] = "粒子數"
L["Party"] = "隊伍"
L["Party Assignment Icon"] = "角色職責圖示"
L["PENDING"] = "等候"
L["Percentage"] = "百分比"
L["Pet"] = "寵物"
L["PET"] = "寵物"
L["Pets"] = "寵物"
L["Pixel"] = "像素"
L["Pixel Perfect"] = "完美細緻模式"
L["Play animation when the unit uses a specific spell/item. The list is global shared, not layout-specific."] = "當單位使用特定的法術/物品時,播放動畫。這個清單是整體共用的,而非每個版面配置專用。"
L["Play Icon Animation When"] = "播放圖示動畫於"
L["Poison"] = "中毒"
L["Position"] = "位置"
L["Power Bar Filters"] = "能量條過濾方式"
L["Power Color"] = "能量顏色"
L["Power Color (dark)"] = "能量顏色 (暗)"
L["Power Size"] = "能量條大小"
L["Power Text"] = "能量文字"
L["Premade Mode"] = "預先建立模式"
L["Press Key to Bind"] = "按下要綁定的按鍵"
L["Preview"] = "預覽"
L["Primary Talents"] = "主要天賦"
L["Private Auras"] = "個人光環"
L["Profile imported successfully."] = "已成功匯入設定檔。"
L["Profiles"] = "設定檔"
L["Pull"] = "倒數"
L["Pull in %d sec"] = "開怪還有 %d 秒"
L["Pull timer cancelled"] = "開怪計時器已取消"
L["pullTimerTips"] = [=[
|r開怪倒數
左鍵: |cffffffff開始倒數計時|r
右鍵: |cffffffff取消倒數計時|r]=]
L["PW:S"] = "真言術:盾"
L["Quick Assist"] = "快速協助"
L["Quick Cast"] = "快速施法"
L["Raid"] = "團隊"
L["Raid Debuffs"] = "副本減益"
L["Raid Debuffs updated: %s."] = "已更新團隊減益: %s。"
L["Raid Icon (player)"] = "團隊圖示 (玩家)"
L["Raid Icon (target)"] = "團隊圖示 (目標)"
L["Raid Tools"] = "團隊工具"
L["RAID_DEBUFFS_TIPS"] = "提示: [拖曳] 減益可以調整順序 [點兩下] 副本名稱可以打開冒險指南 [Shift+左鍵] 副本或首領名稱可以分享減益清單 [Alt+左鍵] 副本或首領名稱可以重置減益清單。一般減益的優先順序比首領減益的優先順序更高。"
L["raidRosterTips"] = "[右鍵] 助理,[Alt+右鍵] 移除。"
L["Ready"] = "團確"
L["Ready Check Icon"] = "準備確認圖示"
L["ReadyCheck and PullTimer buttons"] = "準備確認和開怪倒數按鈕"
L["readyCheckTips"] = [=[
|r準備確認
左鍵: |cffffffff準備確認|r
右鍵: |cffffffff角色職責確認|r
]=]
L["Rect"] = "矩形"
L["refresh unit buttons"] = "重新整理單位按鈕"
L["Refreshing unit buttons (%s)..."] = "正在重新整理單位按鈕 (%s)..."
L["Relative Point"] = "相對對齊點"
L["Relative To"] = "相對於"
L["Remaining Time"] = "剩餘時間"
L["Remember to backup your profile"] = "請記得備份你的設定檔"
L["Remove"] = "移除"
L["Rename"] = "更名"
L["Rename indicator"] = "重新命名指示器"
L["Rename layout"] = "重新名命版面配置"
L["Replace click-castings of Spell type with resurrection spells on dead units"] = "對於掛掉的傢伙,將法術類型的點擊施法替換為複活法術"
L["Reply After Cast"] = "施放技能後發送密語"
L["Reply With Cooldown"] = "回覆剩餘冷卻時間"
L["Report deaths to group"] = "向隊伍通報死亡訊息"
L["Request"] = "請求"
L["Require font support"] = "需要字體支援"
L["Require reload of the UI"] = "需要重新載入介面"
L["Reset"] = "重置"
L["RESET"] = "從非常舊的版本更新之後,需要重置 Cell"
L["Reset All"] = "全部重置"
L["reset all Cell settings"] = "重置 Cell 的全部設定"
L["reset all Click-Castings"] = "重置滑鼠點擊施法的全部設定"
L["reset all Code Snippets"] = "重置所有程式碼片段"
L["reset all Layouts and Indicators"] = "重置版面配置和指示器的全部設定"
L["reset all Raid Debuffs"] = "重置全部的團隊減益"
L["reset Cell position"] = "重置 Cell 的位置"
L["Reset debuffs?"] = "是否要重置減益?"
L["Reset Offensive Spells"] = "重置爆發法術"
L["reset Quick Assist for current spec"] = "重置快速協助 (當前專精)"
L["RESET_CHARACTER"] = "從過舊的版本更新,需要重置角色設定檔"
L["RESET_INCLUDES"] = "只包括滑鼠點擊施法和自動切換版面配置"
L["RESET_YES_NO"] = [=[|cff22ff22是|r - 重置 Cell
|cffff2222否|r - 我自己搞定]=]
L["Respond to all dispellable debuffs"] = "回應所有的可驅散減益"
L["Respond to all requests from group members"] = "回應所有隊伍成員的請求"
L["Respond to requests that are only sent to me"] = "只回應對我發送的請求"
L["Respond to specific dispellable debuffs"] = "只回應指定的可驅散減益"
L["Respond to whispers"] = "回應密語"
L["Response Type"] = "回應類型"
L["Restore backup"] = "還原備份"
L["Reverse Fill"] = "反向填充"
L["Right"] = "右"
L["RIGHT"] = "右"
L["Right-Click"] = "右鍵"
L["Right-Drag"] = "右鍵拖曳"
L["right-to-left"] = "從右到左"
L["Role"] = "角色職責"
L["Role Filter"] = "依職責"
L["Role Icon"] = "角色職責圖示"
L["Rotate Texture"] = "旋轉材質"
L["Rotation"] = "旋轉"
L["Round Up Duration Text"] = "四捨五入持續時間文字"
L["Rows"] = "行數"
L["Run"] = "執行"
L["S"] = "專精"
L["Save"] = "儲存"
L["Scale"] = "縮放大小"
L["ScrollDown"] = "滾輪往下"
L["ScrollUp"] = "滾輪往上"
L["sec"] = "秒"
L["Secondary Talents"] = "次要天賦"
L["Separate NPC Frame"] = "分離 NPC 框架"
L["Set Bar Max Value"] = "設定進度條最大值"
L["set unit"] = "設定單位"
L["set unit's name"] = "設為目標單位的名字"
L["set unit's pet"] = "設為目標單位的寵物"
L["Setup"] = "設定"
L["Shadow"] = "陰影"
L["Shape"] = "形狀"
L["Share"] = "分享"
L["Shield Bar"] = "護盾條"
L["Shield Texture"] = "護盾材質"
L["shieldByMe"] = "只顯示我施放的真言術:盾"
L["Shields"] = "護盾"
L["shields"] = "護盾"
L["Shift+Enter: add a new line"] = "Shift+Enter: 增加一行"
L["Shine"] = "閃耀"
L["Show All"] = "全部顯示"
L["show Cell options frame"] = "打開 Cell 設定選項"
L["Show countdown number"] = "顯示冷卻時間數字"
L["Show countdown swipe"] = "顯示冷卻轉圈動畫"
L["Show Current Instance"] = "顯示當前副本"
L["Show friendly NPCs in a separate frame"] = "將友方 NPC 顯示在一個獨立的框架中"
L["Show NPC Frame"] = "顯示 NPC 框架"
L["Show Party"] = "5人隊伍時要顯示"
L["Show Party/Arena Pets"] = "顯示隊伍/競技場寵物"
L["Show pets in a separate frame"] = "將寵物顯示在單獨的視窗中"
L["Show Raid"] = "團隊時要顯示"
L["Show Raid Pets"] = "顯示團隊寵物"
L["Show Solo"] = "單人時要顯示"
L["Show Solo Pet"] = "顯示單人寵物"
L["Show units you care about more in a separate frame"] = "在單獨的框架中顯示您更關心的單位"
L["Show while in a party"] = "在隊伍中時顯示"
L["Show while in a raid"] = "在團隊中時顯示"
L["Show while not in a group"] = "不在隊伍中時顯示"
L["showAllSpells"] = "顯示所有法術"
L["showAnimation"] = "顯示動畫效果"
L["showBackground"] = "顯示背景"
L["showDuration"] = "顯示持續時間文字"
L["showGroupNumber"] = "顯示隊伍編號"
L["Shows only one spell request on a unit button at a time"] = "每個單位按鈕同時間只能顯示一個法術請求"
L["showStack"] = "顯示層數文字"
L["showTimer"] = "顯示計時器"
L["showTooltip"] = "顯示光環的浮動提示資訊"
L["Size"] = "大小"
L["Size (Big)"] = "大小 (放大的)"
L["Slash Commands"] = "聊天指令"
L["Smart Resurrection"] = "不智能複活"
L["Smooth"] = "平滑"
L["smooth"] = "平滑"
L["SNIPPETS_TIPS"] = "[點兩下]重新名命。[Shift+左鍵]刪除。所有已勾選的程式碼片段將會在 Cell 初始化階段的最後自動執行 (即 ADDON_LOADED 事件中)。"
L["Solid"] = "單色"
L["Solo"] = "單人"
L["Sort By Role"] = "依職責排序"
L["Spacing"] = "間距"
L["Spec"] = "專精"
L["Spec Filter"] = "依專精"
L["Special Thanks"] = "特別感謝"
L["Spell"] = "法術"
L["SPELL"] = "法術"
L["Spell already exists."] = "法術已存在。"
L["Spell List"] = "法術清單"
L["Spell Request"] = "法術請求"
L["SpellId and BuffId are the same in most cases"] = "大部分情況下法術ID與增益ID是相同的"
L["Spells"] = "法術"
L["Spotlight"] = "特別關注"
L["Spotlight Frame"] = "特別關注框架"
L["Spotlight frames are not supported"] = "不支援特別關注框架"
L["stackFont"] = "層數字體"
L["Status Icon"] = "狀態圖示"
L["Status Text"] = "狀態文字"
L["Status Text Position"] = "狀態文字位置"
L["Strata"] = "層級"
L["Style"] = "樣式"
L["Supporters"] = "感謝贊助"
L["Sync Status"] = "同步狀態"
L["Sync With"] = "同步"
L["syncTips"] = "在這裡設置主要版面配置\n附屬的版面配置的所有指示器將與主要版面配置完全同步\n這種同步是雙向的,但在設定主要版面配置時會導致附屬的版面配置的所有指示器遺失"
L["T"] = "天賦"
L["Tank Active Mitigation"] = "坦克主動減傷"
L["Target"] = "目標"
L["target"] = "選為目標"
L["Target a player to autofill the name"] = "選取玩家可以自動填入名字"
L["Target Counter"] = "目標數量"
L["Target Highlight Color"] = "選取目標顯著標示顏色"
L["Target Marks"] = "目標標記"
L["Target of Target"] = "目標的目標"
L["Targeted Spells"] = "被法術選中"
L["Text"] = "文字"
L["Text Options"] = "文字選項"
L["Text Width"] = "文字寬度"
L["Texture"] = "材質"
L["The priority of spells decreases from top to bottom."] = "法術的優先順序是從上到下降低。"
L["The spell is required to apply a buff on the target"] = "要求增加的法術能夠在目標上施加增益效果"
L["The spells list of a icons indicator is unordered (no priority)."] = "圖示指示器的法術清單是不排序的 (無優先順序)。"
L["Then create a PR or submit a ticket on GitHub"] = "然後在 GitHub 上提交 PR 或 Issue 就可以啦"
L["These \"reset\" commands below affect all your characters in this account"] = "以下的 \"重置\" 指令會影響此帳號中的所有角色"
L["These settings are spec-specific"] = "這些設定是每個專精專用的"
L["Thickness"] = "粗細"
L["This may help solve issues of indicators not updating correctly"] = "可能有助於解決指示器不能正確更新的問題"
L["This may overwrite built-in indicators"] = "這可能會覆蓋掉內建的指示器"
L["This setting will be ignored, if the %1$s option in %2$s tab is enabled"] = "如果啟用了%2$s標籤頁面中的%1$s選項,此設定將被忽略"
L["This will make these icons not click-through-able"] = "這會讓這些圖示無法點擊穿透"
L["This will not affect aura tooltips"] = "不影響增益/減益的浮動提示資訊"
L["This will overwrite your debuffs"] = "將會取代你的減益"
L["Timeout"] = "超時"
L["Tip: Every layout has its own position setting"] = "提示: 每個版面配置都有各自的位置設定。"
L["Tip: right-click to delete"] = "提示: 點右鍵刪除"
L["To"] = "到"
L["To HealthBar's"] = "對齊到血條的"
L["To open options frame, use /cell options"] = "輸入 /cell options 打開設定選項"
L["To show shield value, |cffff2727Glyph of Power Word: Shield|r is required"] = "需要有|cffff2727真言術:盾雕紋|r才能顯示護盾值"
L["To transfer across realm, you need to be in the same group"] = "必須在同一個隊伍中才能垮伺服器傳輸。"
L["To UnitButton's"] = "對齊到單位按鈕的"
L["toggle"] = "切換"
L["togglemenu"] = "選單"
L["togglemenu_nocombat"] = "選單 (非戰鬥中)"
L["Tooltips"] = "浮動提示資訊"
L["Tooltips need to be enabled in General tab"] = "需要先啟用一般標籤頁面中的浮動提示資訊功能"
L["TOP"] = "上"
L["TOPLEFT"] = "左上"
L["TOPRIGHT"] = "右上"
L["top-to-bottom"] = "從上到下"
L["Track by ID"] = "符合法術 ID"
L["trackByName"] = "根據名稱追蹤"
L["Translators"] = "翻譯"
L["Translit Cyrillic to Latin"] = "將俄文轉換成英文"
L["Type"] = "類型"
L["Type: "] = "類型:"
L["Unaffected"] = "未獲得此增益"
L["Uncategorized"] = "未分類"
L["Unit"] = "單位"
L["Unit Button"] = "單位按鈕"
L["Unit Button Style"] = "單位按鈕樣式"
L["Unit buttons refreshed (%s)."] = "單位按鈕已重新整理完成 (%s)。"
L["Unit Filter"] = "單位過濾"
L["Unit Spacing"] = "單位間距"
L["Unit's Name"] = "指定單位的名字"
L["Units Per Column"] = "每列單位數"
L["Units Per Row"] = "每行單位數"
L["Unit's Pet"] = "單位的寵物"
L["Unit's Target"] = "指定單位的目標"
L["Unlimited"] = "無限制"
L["Unlock"] = "解鎖"
L["unnamed"] = "未命名"
L["Unselected settings will remain"] = "未選取的設定將會和現在保持一致"
L["Use %s addon"] = "用這個插件 %s"
L["Use |cFFFFB5C5/cell buff X|r to set icon size"] = "輸入 |cFFFFB5C5/cell buff X|r 來設定圖示大小"
L["Use |cFFFFB5C5/cell report X|r to set the number of reports during a raid encounter"] = "輸入 |cFFFFB5C5/cell report X|r 來設定團隊首領戰時要通報的死亡訊息數量"
L["Use CLEU events to increase health update rate"] = "使用戰鬥記錄事件來增加血條的更新頻率"
L["Use common profile"] = "使用共用設定檔"
L["Use Elapsed Time"] = "存在時間"
L["Use Same Arrangement As Main"] = "使用與主框架相同的排列"
L["Use Same Size As Main"] = "使用與主框架相同的大小"
L["use separate profile for current spec"] = "當前專精使用獨立的設定檔"
L["Use separate profile for each spec"] = "每個專精使用不同的設定檔"
L["Utilities"] = "工具"
L["VEHICLE"] = "載具"
L["vehicle name"] = "載具名稱"
L["Vehicle Name Position"] = "載具名稱位置"
L["Vertical"] = "垂直"
L["Vertical Gradient"] = "垂直漸層"
L["Visibility"] = "顯示"
L["Waiting for combat to end..."] = "等待戰鬥結束..."
L["Want to help improve Raid Debuffs?"] = "想要幫忙完善副本減益嗎?"
L["Width"] = "寬度"
L["World Marks"] = "世界標記"
L["Would you like Cell to create a \"Healers\" indicator (icons)?"] = "是否需要 Cell 為你建立治療用的 \"Healers\" 指示器 (圖示群組)?"
L["X Offset"] = "水平位置偏移"
L["Y Offset"] = "垂直位置偏移"
L["Yes"] = "是"
L["You"] = "你"
L["You can config debuffs in %s"] = "你可以在 %s 中設定減益法術"
L["You can move it in Preview mode"] = "可以在 \"預覽\" 模式中移動它"
L["You can't do that while in combat."] = "你不可以在戰鬥中這麼做。"
L["You don't have permission to do this"] = "你沒有權限這樣做" | 412 | 0.708258 | 1 | 0.708258 | game-dev | MEDIA | 0.816864 | game-dev | 0.625557 | 1 | 0.625557 |
ThePaperLuigi/The-Stars-Above | 4,393 | Projectiles/Magic/RadGun/RadRound.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.Audio;
namespace StarsAbove.Projectiles.Magic.RadGun
{
public class RadRound : ModProjectile
{
public override void SetStaticDefaults()
{
// DisplayName.SetDefault("Rad Gun"); //The English name of the projectile
}
public override void SetDefaults()
{
Projectile.width = 20; //The width of projectile hitbox
Projectile.height = 20; //The height of projectile hitbox
Projectile.aiStyle = 1; //The ai style of the projectile, please reference the source code of Terraria
Projectile.friendly = true; //Can the projectile deal damage to enemies?
Projectile.hostile = false; //Can the projectile deal damage to the player?
Projectile.DamageType = DamageClass.Ranged; //Is the projectile shoot by a ranged weapon?
Projectile.penetrate = 1; //How many monsters the projectile can penetrate. (OnTileCollide below also decrements penetrate for bounces as well)
Projectile.timeLeft = 600; //The live time for the projectile (60 = 1 second, so 600 is 10 seconds)
Projectile.alpha = 255; //The transparency of the projectile, 255 for completely transparent. (aiStyle 1 quickly fades the projectile in) Make sure to delete this if you aren't using an aiStyle that fades in. You'll wonder why your projectile is invisible.
Projectile.ignoreWater = true; //Does the projectile's speed be influenced by water?
Projectile.tileCollide = true; //Can the projectile collide with tiles?
Projectile.extraUpdates = 1; //Set to above 0 if you want the projectile to update multiple time in a frame
AIType = ProjectileID.Bullet; //Act exactly like default Bullet
}
public override bool OnTileCollide(Vector2 oldVelocity)
{
//If collide with tile, reduce the penetrate.
//So the projectile can reflect at most 5 times
Projectile.penetrate--;
if (Projectile.penetrate <= 0)
{
Projectile.Kill();
}
else
{
Collision.HitTiles(Projectile.position + Projectile.velocity, Projectile.velocity, Projectile.width, Projectile.height);
SoundEngine.PlaySound(SoundID.Item10, Projectile.position);
if (Projectile.velocity.X != oldVelocity.X)
{
Projectile.velocity.X = -oldVelocity.X;
}
if (Projectile.velocity.Y != oldVelocity.Y)
{
Projectile.velocity.Y = -oldVelocity.Y;
}
}
return false;
}
public override void AI()
{
base.AI();
}
public override bool PreDraw(ref Color lightColor)
{
//Redraw the projectile with the color not influenced by light
Vector2 drawOrigin = new Vector2(TextureAssets.Projectile[Projectile.type].Width() * 0.5f, Projectile.height * 0.5f);
for (int k = 0; k < Projectile.oldPos.Length; k++)
{
Vector2 drawPos = Projectile.oldPos[k] - Main.screenPosition + drawOrigin + new Vector2(0f, Projectile.gfxOffY);
Color color = Projectile.GetAlpha(lightColor) * ((Projectile.oldPos.Length - k) / (float)Projectile.oldPos.Length);
Main.EntitySpriteDraw((Texture2D)TextureAssets.Projectile[Projectile.type], drawPos, null, color, Projectile.rotation, drawOrigin, Projectile.scale, SpriteEffects.None, 0);
}
return true;
}
public override void OnKill(int timeLeft)
{
// This code and the similar code above in OnTileCollide spawn dust from the tiles collided with. SoundID.Item10 is the bounce sound you hear.
Collision.HitTiles(Projectile.position + Projectile.velocity, Projectile.velocity, Projectile.width, Projectile.height);
SoundEngine.PlaySound(SoundID.Item10, Projectile.position);
}
}
}
| 412 | 0.743944 | 1 | 0.743944 | game-dev | MEDIA | 0.99374 | game-dev | 0.770835 | 1 | 0.770835 |
bnoordhuis/v8-cmake | 2,412 | v8/test/mjsunit/global-proxy-this.js | // Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
%PrepareFunctionForOptimization(foo);
assertSame(foo(), foo);
%OptimizeFunctionOnNextCall(foo);
assertSame(foo(), foo);
}
// detachGlobal, old map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
%PrepareFunctionForOptimization(foo);
assertSame(foo(), foo);
Realm.detachGlobal(realm);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
// navigate, old map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
%PrepareFunctionForOptimization(foo);
assertSame(foo(), foo);
Realm.navigate(realm);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
// detachGlobal, new map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
assertSame(foo(), foo);
Realm.detachGlobal(realm);
%PrepareFunctionForOptimization(foo);
assertThrows(foo);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
// navigate, new map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
assertSame(foo(), foo);
Realm.navigate(realm);
%PrepareFunctionForOptimization(foo);
assertThrows(foo);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
// detachGlobal, old and new map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
%PrepareFunctionForOptimization(foo);
assertSame(foo(), foo);
Realm.detachGlobal(realm);
assertThrows(foo);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
// navigate, old and new map
{
const realm = Realm.createAllowCrossRealmAccess();
const foo = Realm.eval(realm, "function foo() { return this.foo }; foo");
%PrepareFunctionForOptimization(foo);
assertSame(foo(), foo);
Realm.navigate(realm);
assertThrows(foo);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo);
}
| 412 | 0.740802 | 1 | 0.740802 | game-dev | MEDIA | 0.275041 | game-dev | 0.521973 | 1 | 0.521973 |
oneiric/vld | 24,191 | lib/gtest/include/gtest/internal/gtest-param-util.h | // Copyright 2008 Google Inc.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Type and function utilities for implementing parameterized tests.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#include <iterator>
#include <utility>
#include <vector>
// scripts/fuse_gtest.py depends on gtest's own header being #included
// *unconditionally*. Therefore these #includes cannot be moved
// inside #if GTEST_HAS_PARAM_TEST.
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h"
#if GTEST_HAS_PARAM_TEST
namespace testing {
namespace internal {
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Outputs a message explaining invalid registration of different
// fixture class for the same test case. This may happen when
// TEST_P macro is used to define two tests with the same name
// but in different namespaces.
GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name,
const char* file, int line);
template <typename> class ParamGeneratorInterface;
template <typename> class ParamGenerator;
// Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>.
template <typename T>
class ParamIteratorInterface {
public:
virtual ~ParamIteratorInterface() {}
// A pointer to the base generator instance.
// Used only for the purposes of iterator comparison
// to make sure that two iterators belong to the same generator.
virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
// Advances iterator to point to the next element
// provided by the generator. The caller is responsible
// for not calling Advance() on an iterator equal to
// BaseGenerator()->End().
virtual void Advance() = 0;
// Clones the iterator object. Used for implementing copy semantics
// of ParamIterator<T>.
virtual ParamIteratorInterface* Clone() const = 0;
// Dereferences the current iterator and provides (read-only) access
// to the pointed value. It is the caller's responsibility not to call
// Current() on an iterator equal to BaseGenerator()->End().
// Used for implementing ParamGenerator<T>::operator*().
virtual const T* Current() const = 0;
// Determines whether the given iterator and other point to the same
// element in the sequence generated by the generator.
// Used for implementing ParamGenerator<T>::operator==().
virtual bool Equals(const ParamIteratorInterface& other) const = 0;
};
// Class iterating over elements provided by an implementation of
// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
// and implements the const forward iterator concept.
template <typename T>
class ParamIterator {
public:
typedef T value_type;
typedef const T& reference;
typedef ptrdiff_t difference_type;
// ParamIterator assumes ownership of the impl_ pointer.
ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
ParamIterator& operator=(const ParamIterator& other) {
if (this != &other)
impl_.reset(other.impl_->Clone());
return *this;
}
const T& operator*() const { return *impl_->Current(); }
const T* operator->() const { return impl_->Current(); }
// Prefix version of operator++.
ParamIterator& operator++() {
impl_->Advance();
return *this;
}
// Postfix version of operator++.
ParamIterator operator++(int /*unused*/) {
ParamIteratorInterface<T>* clone = impl_->Clone();
impl_->Advance();
return ParamIterator(clone);
}
bool operator==(const ParamIterator& other) const {
return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
}
bool operator!=(const ParamIterator& other) const {
return !(*this == other);
}
private:
friend class ParamGenerator<T>;
explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
scoped_ptr<ParamIteratorInterface<T> > impl_;
};
// ParamGeneratorInterface<T> is the binary interface to access generators
// defined in other translation units.
template <typename T>
class ParamGeneratorInterface {
public:
typedef T ParamType;
virtual ~ParamGeneratorInterface() {}
// Generator interface definition
virtual ParamIteratorInterface<T>* Begin() const = 0;
virtual ParamIteratorInterface<T>* End() const = 0;
};
// Wraps ParamGeneratorInterface<T> and provides general generator syntax
// compatible with the STL Container concept.
// This class implements copy initialization semantics and the contained
// ParamGeneratorInterface<T> instance is shared among all copies
// of the original object. This is possible because that instance is immutable.
template<typename T>
class ParamGenerator {
public:
typedef ParamIterator<T> iterator;
explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
ParamGenerator& operator=(const ParamGenerator& other) {
impl_ = other.impl_;
return *this;
}
iterator begin() const { return iterator(impl_->Begin()); }
iterator end() const { return iterator(impl_->End()); }
private:
linked_ptr<const ParamGeneratorInterface<T> > impl_;
};
// Generates values from a range of two comparable values. Can be used to
// generate sequences of user-defined types that implement operator+() and
// operator<().
// This class is used in the Range() function.
template <typename T, typename IncrementT>
class RangeGenerator : public ParamGeneratorInterface<T> {
public:
RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin), end_(end),
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
virtual ~RangeGenerator() {}
virtual ParamIteratorInterface<T>* Begin() const {
return new Iterator(this, begin_, 0, step_);
}
virtual ParamIteratorInterface<T>* End() const {
return new Iterator(this, end_, end_index_, step_);
}
private:
class Iterator : public ParamIteratorInterface<T> {
public:
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {}
virtual ~Iterator() {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
return base_;
}
virtual void Advance() {
value_ = value_ + step_;
index_++;
}
virtual ParamIteratorInterface<T>* Clone() const {
return new Iterator(*this);
}
virtual const T* Current() const { return &value_; }
virtual bool Equals(const ParamIteratorInterface<T>& other) const {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
const int other_index =
CheckedDowncastToActualType<const Iterator>(&other)->index_;
return index_ == other_index;
}
private:
Iterator(const Iterator& other)
: ParamIteratorInterface<T>(),
base_(other.base_), value_(other.value_), index_(other.index_),
step_(other.step_) {}
// No implementation - assignment is unsupported.
void operator=(const Iterator& other);
const ParamGeneratorInterface<T>* const base_;
T value_;
int index_;
const IncrementT step_;
}; // class RangeGenerator::Iterator
static int CalculateEndIndex(const T& begin,
const T& end,
const IncrementT& step) {
int end_index = 0;
for (T i = begin; i < end; i = i + step)
end_index++;
return end_index;
}
// No implementation - assignment is unsupported.
void operator=(const RangeGenerator& other);
const T begin_;
const T end_;
const IncrementT step_;
// The index for the end() iterator. All the elements in the generated
// sequence are indexed (0-based) to aid iterator comparison.
const int end_index_;
}; // class RangeGenerator
// Generates values from a pair of STL-style iterators. Used in the
// ValuesIn() function. The elements are copied from the source range
// since the source can be located on the stack, and the generator
// is likely to persist beyond that stack frame.
template <typename T>
class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
public:
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {}
virtual ~ValuesInIteratorRangeGenerator() {}
virtual ParamIteratorInterface<T>* Begin() const {
return new Iterator(this, container_.begin());
}
virtual ParamIteratorInterface<T>* End() const {
return new Iterator(this, container_.end());
}
private:
typedef typename ::std::vector<T> ContainerType;
class Iterator : public ParamIteratorInterface<T> {
public:
Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {}
virtual ~Iterator() {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
return base_;
}
virtual void Advance() {
++iterator_;
value_.reset();
}
virtual ParamIteratorInterface<T>* Clone() const {
return new Iterator(*this);
}
// We need to use cached value referenced by iterator_ because *iterator_
// can return a temporary object (and of type other then T), so just
// having "return &*iterator_;" doesn't work.
// value_ is updated here and not in Advance() because Advance()
// can advance iterator_ beyond the end of the range, and we cannot
// detect that fact. The client code, on the other hand, is
// responsible for not calling Current() on an out-of-range iterator.
virtual const T* Current() const {
if (value_.get() == NULL)
value_.reset(new T(*iterator_));
return value_.get();
}
virtual bool Equals(const ParamIteratorInterface<T>& other) const {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
return iterator_ ==
CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
}
private:
Iterator(const Iterator& other)
// The explicit constructor call suppresses a false warning
// emitted by gcc when supplied with the -Wextra option.
: ParamIteratorInterface<T>(),
base_(other.base_),
iterator_(other.iterator_) {}
const ParamGeneratorInterface<T>* const base_;
typename ContainerType::const_iterator iterator_;
// A cached value of *iterator_. We keep it here to allow access by
// pointer in the wrapping iterator's operator->().
// value_ needs to be mutable to be accessed in Current().
// Use of scoped_ptr helps manage cached value's lifetime,
// which is bound by the lifespan of the iterator itself.
mutable scoped_ptr<const T> value_;
}; // class ValuesInIteratorRangeGenerator::Iterator
// No implementation - assignment is unsupported.
void operator=(const ValuesInIteratorRangeGenerator& other);
const ContainerType container_;
}; // class ValuesInIteratorRangeGenerator
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Stores a parameter value and later creates tests parameterized with that
// value.
template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase {
public:
typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter) :
parameter_(parameter) {}
virtual Test* CreateTest() {
TestClass::SetParam(¶meter_);
return new TestClass();
}
private:
const ParamType parameter_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// TestMetaFactoryBase is a base class for meta-factories that create
// test factories for passing into MakeAndRegisterTestInfo function.
template <class ParamType>
class TestMetaFactoryBase {
public:
virtual ~TestMetaFactoryBase() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// TestMetaFactory creates test factories for passing into
// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
// ownership of test factory pointer, same factory object cannot be passed
// into that method twice. But ParameterizedTestCaseInfo is going to call
// it for each Test/Parameter value combination. Thus it needs meta factory
// creator class.
template <class TestCase>
class TestMetaFactory
: public TestMetaFactoryBase<typename TestCase::ParamType> {
public:
typedef typename TestCase::ParamType ParamType;
TestMetaFactory() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) {
return new ParameterizedTestFactory<TestCase>(parameter);
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseInfoBase is a generic interface
// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
// accumulates test information provided by TEST_P macro invocations
// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
// and uses that information to register all resulting test instances
// in RegisterTests method. The ParameterizeTestCaseRegistry class holds
// a collection of pointers to the ParameterizedTestCaseInfo objects
// and calls RegisterTests() on each of them when asked.
class ParameterizedTestCaseInfoBase {
public:
virtual ~ParameterizedTestCaseInfoBase() {}
// Base part of test case name for display purposes.
virtual const string& GetTestCaseName() const = 0;
// Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const = 0;
// UnitTest class invokes this method to register tests in this
// test case right before running them in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single
// instance of a ParameterizedTestCaseInfoBase derived class.
virtual void RegisterTests() = 0;
protected:
ParameterizedTestCaseInfoBase() {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
// macro invocations for a particular test case and generators
// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
// test case. It registers tests with all values generated by all
// generators when asked.
template <class TestCase>
class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
public:
// ParamType and GeneratorCreationFunc are private types but are required
// for declarations of public methods AddTestPattern() and
// AddTestCaseInstantiation().
typedef typename TestCase::ParamType ParamType;
// A function that returns an instance of appropriate generator type.
typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
explicit ParameterizedTestCaseInfo(const char* name)
: test_case_name_(name) {}
// Test case base name for display purposes.
virtual const string& GetTestCaseName() const { return test_case_name_; }
// Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); }
// TEST_P macro uses AddTestPattern() to record information
// about a single test in a LocalTestInfo structure.
// test_case_name is the base name of the test case (without invocation
// prefix). test_base_name is the name of an individual test without
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test case base name and DoBar is test base name.
void AddTestPattern(const char* test_case_name,
const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory) {
tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name,
test_base_name,
meta_factory)));
}
// INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
// about a generator.
int AddTestCaseInstantiation(const string& instantiation_name,
GeneratorCreationFunc* func,
const char* /* file */,
int /* line */) {
instantiations_.push_back(::std::make_pair(instantiation_name, func));
return 0; // Return value used only to run this method in namespace scope.
}
// UnitTest class invokes this method to register tests in this test case
// test cases right before running tests in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single
// instance of a ParameterizedTestCaseInfoBase derived class.
// UnitTest has a guard to prevent from calling this method more then once.
virtual void RegisterTests() {
for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) {
linked_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end();
++gen_it) {
const string& instantiation_name = gen_it->first;
ParamGenerator<ParamType> generator((*gen_it->second)());
string test_case_name;
if ( !instantiation_name.empty() )
test_case_name = instantiation_name + "/";
test_case_name += test_info->test_case_base_name;
int i = 0;
for (typename ParamGenerator<ParamType>::iterator param_it =
generator.begin();
param_it != generator.end(); ++param_it, ++i) {
Message test_name_stream;
test_name_stream << test_info->test_base_name << "/" << i;
MakeAndRegisterTestInfo(
test_case_name.c_str(),
test_name_stream.GetString().c_str(),
NULL, // No type parameter.
PrintToString(*param_it).c_str(),
GetTestCaseTypeId(),
TestCase::SetUpTestCase,
TestCase::TearDownTestCase,
test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it
} // for gen_it
} // for test_it
} // RegisterTests
private:
// LocalTestInfo structure keeps information about a single test registered
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_case_base_name,
const char* a_test_base_name,
TestMetaFactoryBase<ParamType>* a_test_meta_factory) :
test_case_base_name(a_test_case_base_name),
test_base_name(a_test_base_name),
test_meta_factory(a_test_meta_factory) {}
const string test_case_base_name;
const string test_base_name;
const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
};
typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer;
// Keeps pairs of <Instantiation name, Sequence generator creation function>
// received from INSTANTIATE_TEST_CASE_P macros.
typedef ::std::vector<std::pair<string, GeneratorCreationFunc*> >
InstantiationContainer;
const string test_case_name_;
TestInfoContainer tests_;
InstantiationContainer instantiations_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo);
}; // class ParameterizedTestCaseInfo
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
// macros use it to locate their corresponding ParameterizedTestCaseInfo
// descriptors.
class ParameterizedTestCaseRegistry {
public:
ParameterizedTestCaseRegistry() {}
~ParameterizedTestCaseRegistry() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
delete *it;
}
}
// Looks up or creates and returns a structure containing information about
// tests and instantiations of a particular test case.
template <class TestCase>
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
const char* test_case_name,
const char* file,
int line) {
ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL;
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
if ((*it)->GetTestCaseName() == test_case_name) {
if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
// Complain about incorrect usage of Google Test facilities
// and terminate the program since we cannot guaranty correct
// test case setup and tear-down in this case.
ReportInvalidTestCaseType(test_case_name, file, line);
posix::Abort();
} else {
// At this point we are sure that the object we found is of the same
// type we are looking for, so we downcast it to that type
// without further checks.
typed_test_info = CheckedDowncastToActualType<
ParameterizedTestCaseInfo<TestCase> >(*it);
}
break;
}
}
if (typed_test_info == NULL) {
typed_test_info = new ParameterizedTestCaseInfo<TestCase>(test_case_name);
test_case_infos_.push_back(typed_test_info);
}
return typed_test_info;
}
void RegisterTests() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
(*it)->RegisterTests();
}
}
private:
typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer;
TestCaseInfoContainer test_case_infos_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry);
};
} // namespace internal
} // namespace testing
#endif // GTEST_HAS_PARAM_TEST
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
| 412 | 0.936028 | 1 | 0.936028 | game-dev | MEDIA | 0.199295 | game-dev | 0.932027 | 1 | 0.932027 |
Mickey-snow/SuperEngine | 6,548 | src/modules/module_obj.hpp | // -*- Mode: C++; tab-width:2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi:tw=80:et:ts=2:sts=2
//
// -----------------------------------------------------------------------
//
// This file is part of RLVM, a RealLive virtual machine clone.
//
// -----------------------------------------------------------------------
//
// Copyright (C) 2006 Elliot Glaysher
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// -----------------------------------------------------------------------
#pragma once
#include "machine/rloperation.hpp"
#include "utilities/lazy_array.hpp"
#include <functional>
class GraphicsObject;
class ParameterManager;
// -----------------------------------------------------------------------
void EnsureIsParentObject(GraphicsObject& parent, int size);
GraphicsObject& GetGraphicsObject(RLMachine& machine, RLOperation* op, int obj);
LazyArray<GraphicsObject>& GetGraphicsObjects(RLMachine& machine,
RLOperation* op);
// -----------------------------------------------------------------------
// Special adapter to make any of obj* and objBg* operation structs
// into an objRange* or objRangeBg* struct.
//
// We extract the first two expression pieces from the incoming
// command and assume that they are integers and are the bounds on the
// object number. We then construct a set of parameters to pass to the
// real implementation.
//
// This is certainly not the most efficient way to do it, but it cuts
// down on a duplicated operation struct for each obj* and objBg*
// function, alowing us to just use this adapter with the already
// defined operations.
class ObjRangeAdapter : public RLOp_SpecialCase {
public:
explicit ObjRangeAdapter(std::unique_ptr<RLOperation> in);
virtual void operator()(RLMachine& machine,
const libreallive::CommandElement& ff) final;
private:
std::unique_ptr<RLOperation> handler;
};
// Mapping function for a MappedRLModule which turns operation op into
// a ranged operation.
//
// The wrapper takes ownership of the incoming op pointer, and the
// caller takes ownership of the resultant RLOperation.
std::shared_ptr<RLOperation> RangeMappingFun(std::unique_ptr<RLOperation> op);
// -----------------------------------------------------------------------
// An adapter that changes a normal object operation into one that operates on
// an object's child objects.
class ChildObjAdapter : public RLOp_SpecialCase {
public:
explicit ChildObjAdapter(std::unique_ptr<RLOperation> in);
virtual ~ChildObjAdapter();
virtual void operator()(RLMachine& machine,
const libreallive::CommandElement& ff) final;
private:
std::unique_ptr<RLOperation> handler;
};
std::shared_ptr<RLOperation> ChildObjMappingFun(
std::unique_ptr<RLOperation> op);
// -----------------------------------------------------------------------
// An adapter that ranges over children of a certain parent object.
class ChildObjRangeAdapter : public RLOp_SpecialCase {
public:
explicit ChildObjRangeAdapter(std::unique_ptr<RLOperation> in);
virtual ~ChildObjRangeAdapter();
virtual void operator()(RLMachine& machine,
const libreallive::CommandElement& ff) final;
private:
std::unique_ptr<RLOperation> handler;
};
// The combo form of rangeMappingFun and childObjMappingFun. Used for
// operations that start with (parent object num, first child num, last child
// num).
std::shared_ptr<RLOperation> ChildRangeMappingFun(
std::unique_ptr<RLOperation> op);
// -----------------------------------------------------------------------
// Calls a function on an object.
//
class Obj_CallFunction : public RLOpcode<IntConstant_T> {
public:
typedef void (GraphicsObject::*Function)();
explicit Obj_CallFunction(Function f);
virtual ~Obj_CallFunction();
virtual void operator()(RLMachine& machine, int buf) final;
private:
Function function_;
};
// -----------------------------------------------------------------------
// Specialized form of Op_SetToIncomingInt to deal with looking up
// object from the Obj* helper templates; since a lot of Object
// related functions simply call a setter.
//
// This template magic saves having to write out 25 - 30 operation
// structs.
class Obj_SetOneIntOnObj : public RLOpcode<IntConstant_T, IntConstant_T> {
public:
using Setter = std::function<void(ParameterManager&, int)>;
explicit Obj_SetOneIntOnObj(Setter s);
virtual ~Obj_SetOneIntOnObj();
virtual void operator()(RLMachine& machine, int buf, int incoming) final;
private:
// The setter function to call on Op_SetToIncoming::reference when
// called.
Setter setter;
};
// -----------------------------------------------------------------------
// Specialized form of Op_SetToIncomingInt to deal with looking up object from
// the Obj* helper templates; since a lot of Object related functions simply
// call a setter.
class Obj_SetTwoIntOnObj
: public RLOpcode<IntConstant_T, IntConstant_T, IntConstant_T> {
public:
using Setter = std::function<void(ParameterManager&, int)>;
Obj_SetTwoIntOnObj(Setter one, Setter two);
virtual ~Obj_SetTwoIntOnObj();
virtual void operator()(RLMachine& machine,
int buf,
int incoming_one,
int incoming_two) final;
private:
Setter setter_one_;
Setter setter_two_;
};
// -----------------------------------------------------------------------
class Obj_SetRepnoIntOnObj
: public RLOpcode<IntConstant_T, IntConstant_T, IntConstant_T> {
public:
using Setter = std::function<void(ParameterManager&, int, int)>;
Obj_SetRepnoIntOnObj(Setter setter);
virtual ~Obj_SetRepnoIntOnObj();
virtual void operator()(RLMachine& machine, int buf, int idx, int val) final;
private:
Setter setter;
};
| 412 | 0.938203 | 1 | 0.938203 | game-dev | MEDIA | 0.572851 | game-dev | 0.771674 | 1 | 0.771674 |
minio/minio | 9,401 | internal/event/targetlist.go | // Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// 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/>.
package event
import (
"context"
"fmt"
"maps"
"runtime"
"sync"
"sync/atomic"
"github.com/minio/minio/internal/logger"
"github.com/minio/minio/internal/store"
"github.com/minio/pkg/v3/workers"
)
const (
logSubsys = "notify"
// The maximum allowed number of concurrent Send() calls to all configured notifications targets
maxConcurrentAsyncSend = 50000
)
// Target - event target interface
type Target interface {
ID() TargetID
IsActive() (bool, error)
Save(Event) error
SendFromStore(store.Key) error
Close() error
Store() TargetStore
}
// TargetStore is a shallow version of a target.Store
type TargetStore interface {
Len() int
}
// Stats is a collection of stats for multiple targets.
type Stats struct {
TotalEvents int64 // Deprecated
EventsSkipped int64
CurrentQueuedCalls int64 // Deprecated
EventsErrorsTotal int64 // Deprecated
CurrentSendCalls int64 // Deprecated
TargetStats map[TargetID]TargetStat
}
// TargetStat is the stats of a single target.
type TargetStat struct {
CurrentSendCalls int64 // CurrentSendCalls is the number of concurrent async Send calls to all targets
CurrentQueue int // Populated if target has a store.
TotalEvents int64
FailedEvents int64 // Number of failed events per target
}
// TargetList - holds list of targets indexed by target ID.
type TargetList struct {
// The number of concurrent async Send calls to all targets
currentSendCalls atomic.Int64
totalEvents atomic.Int64
eventsSkipped atomic.Int64
eventsErrorsTotal atomic.Int64
sync.RWMutex
targets map[TargetID]Target
queue chan asyncEvent
ctx context.Context
statLock sync.RWMutex
targetStats map[TargetID]targetStat
}
type targetStat struct {
// The number of concurrent async Send calls per targets
currentSendCalls int64
// The number of total events per target
totalEvents int64
// The number of failed events per target
failedEvents int64
}
func (list *TargetList) getStatsByTargetID(id TargetID) (stat targetStat) {
list.statLock.RLock()
defer list.statLock.RUnlock()
return list.targetStats[id]
}
func (list *TargetList) incCurrentSendCalls(id TargetID) {
list.statLock.Lock()
defer list.statLock.Unlock()
stats, ok := list.targetStats[id]
if !ok {
stats = targetStat{}
}
stats.currentSendCalls++
list.targetStats[id] = stats
}
func (list *TargetList) decCurrentSendCalls(id TargetID) {
list.statLock.Lock()
defer list.statLock.Unlock()
stats, ok := list.targetStats[id]
if !ok {
// should not happen
return
}
stats.currentSendCalls--
list.targetStats[id] = stats
}
func (list *TargetList) incFailedEvents(id TargetID) {
list.statLock.Lock()
defer list.statLock.Unlock()
stats, ok := list.targetStats[id]
if !ok {
stats = targetStat{}
}
stats.failedEvents++
list.targetStats[id] = stats
}
func (list *TargetList) incTotalEvents(id TargetID) {
list.statLock.Lock()
defer list.statLock.Unlock()
stats, ok := list.targetStats[id]
if !ok {
stats = targetStat{}
}
stats.totalEvents++
list.targetStats[id] = stats
}
type asyncEvent struct {
ev Event
targetSet TargetIDSet
}
// Add - adds unique target to target list.
func (list *TargetList) Add(targets ...Target) error {
list.Lock()
defer list.Unlock()
for _, target := range targets {
if _, ok := list.targets[target.ID()]; ok {
return fmt.Errorf("target %v already exists", target.ID())
}
list.targets[target.ID()] = target
}
return nil
}
// Exists - checks whether target by target ID exists or not.
func (list *TargetList) Exists(id TargetID) bool {
list.RLock()
defer list.RUnlock()
_, found := list.targets[id]
return found
}
// TargetIDResult returns result of Remove/Send operation, sets err if
// any for the associated TargetID
type TargetIDResult struct {
// ID where the remove or send were initiated.
ID TargetID
// Stores any error while removing a target or while sending an event.
Err error
}
// Remove - closes and removes targets by given target IDs.
func (list *TargetList) Remove(targetIDSet TargetIDSet) {
list.Lock()
defer list.Unlock()
for id := range targetIDSet {
target, ok := list.targets[id]
if ok {
target.Close()
delete(list.targets, id)
}
}
}
// Targets - list all targets
func (list *TargetList) Targets() []Target {
if list == nil {
return []Target{}
}
list.RLock()
defer list.RUnlock()
targets := []Target{}
for _, tgt := range list.targets {
targets = append(targets, tgt)
}
return targets
}
// List - returns available target IDs.
func (list *TargetList) List() []TargetID {
list.RLock()
defer list.RUnlock()
keys := []TargetID{}
for k := range list.targets {
keys = append(keys, k)
}
return keys
}
func (list *TargetList) get(id TargetID) (Target, bool) {
list.RLock()
defer list.RUnlock()
target, ok := list.targets[id]
return target, ok
}
// TargetMap - returns available targets.
func (list *TargetList) TargetMap() map[TargetID]Target {
list.RLock()
defer list.RUnlock()
ntargets := make(map[TargetID]Target, len(list.targets))
maps.Copy(ntargets, list.targets)
return ntargets
}
// Send - sends events to targets identified by target IDs.
func (list *TargetList) Send(event Event, targetIDset TargetIDSet, sync bool) {
if sync {
list.sendSync(event, targetIDset)
} else {
list.sendAsync(event, targetIDset)
}
}
func (list *TargetList) sendSync(event Event, targetIDset TargetIDSet) {
var wg sync.WaitGroup
for id := range targetIDset {
target, ok := list.get(id)
if !ok {
continue
}
wg.Add(1)
go func(id TargetID, target Target) {
list.currentSendCalls.Add(1)
list.incCurrentSendCalls(id)
list.incTotalEvents(id)
defer list.decCurrentSendCalls(id)
defer list.currentSendCalls.Add(-1)
defer wg.Done()
if err := target.Save(event); err != nil {
list.eventsErrorsTotal.Add(1)
list.incFailedEvents(id)
reqInfo := &logger.ReqInfo{}
reqInfo.AppendTags("targetID", id.String())
logger.LogOnceIf(logger.SetReqInfo(context.Background(), reqInfo), logSubsys, err, id.String())
}
}(id, target)
}
wg.Wait()
list.totalEvents.Add(1)
}
func (list *TargetList) sendAsync(event Event, targetIDset TargetIDSet) {
select {
case list.queue <- asyncEvent{
ev: event,
targetSet: targetIDset.Clone(),
}:
case <-list.ctx.Done():
list.eventsSkipped.Add(int64(len(list.queue)))
return
default:
list.eventsSkipped.Add(1)
err := fmt.Errorf("concurrent target notifications exceeded %d, configured notification target is too slow to accept events for the incoming request rate", maxConcurrentAsyncSend)
for id := range targetIDset {
reqInfo := &logger.ReqInfo{}
reqInfo.AppendTags("targetID", id.String())
logger.LogOnceIf(logger.SetReqInfo(context.Background(), reqInfo), logSubsys, err, id.String())
}
return
}
}
// Stats returns stats for targets.
func (list *TargetList) Stats() Stats {
t := Stats{}
if list == nil {
return t
}
t.CurrentSendCalls = list.currentSendCalls.Load()
t.EventsSkipped = list.eventsSkipped.Load()
t.TotalEvents = list.totalEvents.Load()
t.CurrentQueuedCalls = int64(len(list.queue))
t.EventsErrorsTotal = list.eventsErrorsTotal.Load()
list.RLock()
defer list.RUnlock()
t.TargetStats = make(map[TargetID]TargetStat, len(list.targets))
for id, target := range list.targets {
var currentQueue int
if st := target.Store(); st != nil {
currentQueue = st.Len()
}
stats := list.getStatsByTargetID(id)
t.TargetStats[id] = TargetStat{
CurrentSendCalls: stats.currentSendCalls,
CurrentQueue: currentQueue,
FailedEvents: stats.failedEvents,
TotalEvents: stats.totalEvents,
}
}
return t
}
func (list *TargetList) startSendWorkers(workerCount int) {
if workerCount == 0 {
workerCount = runtime.GOMAXPROCS(0)
}
wk, err := workers.New(workerCount)
if err != nil {
panic(err)
}
for range workerCount {
wk.Take()
go func() {
defer wk.Give()
for {
select {
case av := <-list.queue:
list.sendSync(av.ev, av.targetSet)
case <-list.ctx.Done():
return
}
}
}()
}
wk.Wait()
}
var startOnce sync.Once
// Init initialize target send workers.
func (list *TargetList) Init(workers int) *TargetList {
startOnce.Do(func() {
go list.startSendWorkers(workers)
})
return list
}
// NewTargetList - creates TargetList.
func NewTargetList(ctx context.Context) *TargetList {
list := &TargetList{
targets: make(map[TargetID]Target),
queue: make(chan asyncEvent, maxConcurrentAsyncSend),
targetStats: make(map[TargetID]targetStat),
ctx: ctx,
}
return list
}
| 412 | 0.919619 | 1 | 0.919619 | game-dev | MEDIA | 0.237526 | game-dev | 0.846942 | 1 | 0.846942 |
manisha-v/Unity3D | 1,621 | Part2 - 3D Object Intraction/Codes/Library/PackageCache/com.unity.test-framework@1.1.29/UnityEngine.TestRunner/Utils/AttributeHelper.cs | using System;
using System.IO;
using System.Linq;
namespace UnityEngine.TestTools
{
internal static class AttributeHelper
{
internal static Type GetTargetClassFromName(string targetClassName, Type attributeInterface)
{
Type targetClass = null;
foreach (var assemblyName in ScriptingRuntime.GetAllUserAssemblies())
{
// we need to pass the assembly name without the .dll extension, so removing that first
var name = Path.GetFileNameWithoutExtension(assemblyName);
targetClass = Type.GetType(targetClassName + "," + name);
if (targetClass != null)
break;
}
if (targetClass == null)
{
Debug.LogWarningFormat("Class type not found: " + targetClassName);
return null;
}
ValidateTargetClass(targetClass, attributeInterface);
return targetClass;
}
private static void ValidateTargetClass(Type targetClass, Type attributeInterface)
{
var constructorInfos = targetClass.GetConstructors();
if (constructorInfos.All(constructor => constructor.GetParameters().Length != 0))
{
Debug.LogWarningFormat("{0} does not implement default constructor", targetClass.Name);
}
if (!attributeInterface.IsAssignableFrom(targetClass))
{
Debug.LogWarningFormat("{0} does not implement {1}", targetClass.Name, attributeInterface.Name);
}
}
}
}
| 412 | 0.595521 | 1 | 0.595521 | game-dev | MEDIA | 0.407212 | game-dev | 0.586746 | 1 | 0.586746 |
DruidMech/UE4-CPP-Shooter-Series | 17,825 | Source Code Per Lesson/Section 10 - Outline and Glow Effects/183 Play Equip Sound When Swapping/ShooterCharacter.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "AmmoType.h"
#include "ShooterCharacter.generated.h"
UENUM(BlueprintType)
enum class ECombatState : uint8
{
ECS_Unoccupied UMETA(DisplayName = "Unoccupied"),
ECS_FireTimerInProgress UMETA(DisplayName = "FireTimerInProgress"),
ECS_Reloading UMETA(DisplayName = "Reloading"),
ECS_Equipping UMETA(DisplayName = "Equipping"),
ECS_NAX UMETA(DisplayName = "DefaultMAX")
};
USTRUCT(BlueprintType)
struct FInterpLocation
{
GENERATED_BODY()
// Scene component to use for its location for interping
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
USceneComponent* SceneComponent;
// Number of items interping to/at this scene comp location
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
int32 ItemCount;
};
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FEquipItemDelegate, int32, CurrentSlotIndex, int32, NewSlotIndex);
UCLASS()
class SHOOTER_API AShooterCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AShooterCharacter();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
/** Called for forwards/backwards input */
void MoveForward(float Value);
/** Called for side to side input */
void MoveRight(float Value);
/**
* Called via input to turn at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void TurnAtRate(float Rate);
/**
* Called via input to look up/down at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired rate
*/
void LookUpAtRate(float Rate);
/**
* Rotate controller based on mouse X movement
* @param Value The input value from mouse movement
*/
void Turn(float Value);
/**
* Rotate controller based on mouse Y movement
* @param Value The input value from mouse movement
*/
void LookUp(float Value);
/** Called when the Fire Button is pressed */
void FireWeapon();
bool GetBeamEndLocation(const FVector& MuzzleSocketLocation, FVector& OutBeamLocation);
/** Set bAiming to true or false with button press */
void AimingButtonPressed();
void AimingButtonReleased();
void CameraInterpZoom(float DeltaTime);
/** Set BaseTurnRate and BaseLookUpRate based on aiming */
void SetLookRates();
void CalculateCrosshairSpread(float DeltaTime);
void StartCrosshairBulletFire();
UFUNCTION()
void FinishCrosshairBulletFire();
void FireButtonPressed();
void FireButtonReleased();
void StartFireTimer();
UFUNCTION()
void AutoFireReset();
/** Line trace for items under the crosshairs */
bool TraceUnderCrosshairs(FHitResult& OutHitResult, FVector& OutHitLocation);
/** Trace for items if OverlappedItemCount > 0 */
void TraceForItems();
/** Spawns a default weapon and equips it */
class AWeapon* SpawnDefaultWeapon();
/** Takes a weapon and attaches it to the mesh */
void EquipWeapon(AWeapon* WeaponToEquip);
/** Detach weapon and let it fall to the ground */
void DropWeapon();
void SelectButtonPressed();
void SelectButtonReleased();
/** Drops currently equipped Weapon and Equips TraceHitItem */
void SwapWeapon(AWeapon* WeaponToSwap);
/** Initialize the Ammo Map with ammo values */
void InitializeAmmoMap();
/** Check to make sure our weapon has ammo */
bool WeaponHasAmmo();
/** FireWeapon functions */
void PlayFireSound();
void SendBullet();
void PlayGunfireMontage();
/** Bound to the R key and Gamepad Face Button Left */
void ReloadButtonPressed();
/** Handle reloading of the weapon */
void ReloadWeapon();
/** Checks to see if we have ammo of the EquippedWeapon's ammo type */
bool CarryingAmmo();
/** Called from Animation Blueprint with Grab Clip notify */
UFUNCTION(BlueprintCallable)
void GrabClip();
/** Called from Animation Blueprint with Release Clip notify */
UFUNCTION(BlueprintCallable)
void ReleaseClip();
void CrouchButtonPressed();
virtual void Jump() override;
/** Interps capsule half height when crouching/standing */
void InterpCapsuleHalfHeight(float DeltaTime);
void Aim();
void StopAiming();
void PickupAmmo(class AAmmo* Ammo);
void InitializeInterpLocations();
void FKeyPressed();
void OneKeyPressed();
void TwoKeyPressed();
void ThreeKeyPressed();
void FourKeyPressed();
void FiveKeyPressed();
void ExchangeInventoryItems(int32 CurrentItemIndex, int32 NewItemIndex);
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
private:
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;
/** Camera that follows the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final turn rate */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float BaseLookUpRate;
/** Turn rate while not aiming */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float HipTurnRate;
/** Look up rate when not aiming */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float HipLookUpRate;
/** Turn rate when aiming */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float AimingTurnRate;
/** Look up rate when aiming */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
float AimingLookUpRate;
/** Scale factor for mouse look sensitivity. Turn rate when not aiming. */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float MouseHipTurnRate;
/** Scale factor for mouse look sensitivity. Look up rate when not aiming. */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float MouseHipLookUpRate;
/** Scale factor for mouse look sensitivity. Turn rate when aiming. */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float MouseAimingTurnRate;
/** Scale factor for mouse look sensitivity. Look up rate when aiming. */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float MouseAimingLookUpRate;
/** Randomized gunshot sound cue */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
class USoundCue* FireSound;
/** Flash spawned at BarrelSocket */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
class UParticleSystem* MuzzleFlash;
/** Montage for firing the weapon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
class UAnimMontage* HipFireMontage;
/** Particles spawned upon bullet impact */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
UParticleSystem* ImpactParticles;
/** Smoke trail for bullets */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
UParticleSystem* BeamParticles;
/** True when aiming */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
bool bAiming;
/** Default camera field of view value */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
float CameraDefaultFOV;
/** Field of view value for when zoomed in */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
float CameraZoomedFOV;
/** Current field of view this frame */
float CameraCurrentFOV;
/** Interp speed for zooming when aiming */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
float ZoomInterpSpeed;
/** Determines the spread of the crosshairs */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true"))
float CrosshairSpreadMultiplier;
/** Velocity component for crosshairs spread */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true"))
float CrosshairVelocityFactor;
/** In air component for crosshairs spread */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true"))
float CrosshairInAirFactor;
/** Aim component for crosshairs spread */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true"))
float CrosshairAimFactor;
/** Shooting component for crosshairs spread */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true"))
float CrosshairShootingFactor;
float ShootTimeDuration;
bool bFiringBullet;
FTimerHandle CrosshairShootTimer;
/** Left mouse button or right console trigger pressed */
bool bFireButtonPressed;
/** True when we can fire. False when waiting for the timer */
bool bShouldFire;
/** Rate of automatic gun fire */
float AutomaticFireRate;
/** Sets a timer between gunshots */
FTimerHandle AutoFireTimer;
/** True if we should trace every frame for items */
bool bShouldTraceForItems;
/** Number of overlapped AItems */
int8 OverlappedItemCount;
/** The AItem we hit last frame */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
class AItem* TraceHitItemLastFrame;
/** Currently equipped Weapon */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
AWeapon* EquippedWeapon;
/** Set this in Blueprints for the default Weapon class */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
TSubclassOf<AWeapon> DefaultWeaponClass;
/** The item currently hit by our trace in TraceForItems (could be null) */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
AItem* TraceHitItem;
/** Distance outward from the camera for the interp destination */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
float CameraInterpDistance;
/** Distance upward from the camera for the interp destination */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
float CameraInterpElevation;
/** Map to keep track of ammo of the different ammo types */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
TMap<EAmmoType, int32> AmmoMap;
/** Starting amount of 9mm ammo */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Items, meta = (AllowPrivateAccess = "true"))
int32 Starting9mmAmmo;
/** Starting amount of AR ammo */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Items, meta = (AllowPrivateAccess = "true"))
int32 StartingARAmmo;
/** Combat State, can only fire or reload if Unoccupied */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
ECombatState CombatState;
/** Montage for reload animations */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
UAnimMontage* ReloadMontage;
/** Montage for reload animations */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
UAnimMontage* EquipMontage;
UFUNCTION(BlueprintCallable)
void FinishReloading();
UFUNCTION(BlueprintCallable)
void FinishEquipping();
/** Transform of the clip when we first grab the clip during reloading */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
FTransform ClipTransform;
/** Scene component to attach to the Character's hand during reloading */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
USceneComponent* HandSceneComponent;
/** True when crouching */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
bool bCrouching;
/** Regular movement speed */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
float BaseMovementSpeed;
/** Crouch movement speed */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
float CrouchMovementSpeed;
/** Current half height of the capsule */
float CurrentCapsuleHalfHeight;
/** Half height of the capsule when not crouching */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float StandingCapsuleHalfHeight;
/** Half height of the capsule when crouching */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float CrouchingCapsuleHalfHeight;
/** Ground friction while not crouching */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float BaseGroundFriction;
/** Ground friction while crouching */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float CrouchingGroundFriction;
/** Used for knowing when the aiming button is pressed */
bool bAimingButtonPressed;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* WeaponInterpComp;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp1;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp2;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp3;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp4;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp5;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
USceneComponent* InterpComp6;
/** Array of interp location structs */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
TArray<FInterpLocation> InterpLocations;
FTimerHandle PickupSoundTimer;
FTimerHandle EquipSoundTimer;
bool bShouldPlayPickupSound;
bool bShouldPlayEquipSound;
void ResetPickupSoundTimer();
void ResetEquipSoundTimer();
/** Time to wait before we can play another Pickup Sound */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
float PickupSoundResetTime;
/** Time to wait before we can play another Equip Sound */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true"))
float EquipSoundResetTime;
/** An array of AItems for our Inventory */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true"))
TArray<AItem*> Inventory;
const int32 INVENTORY_CAPACITY{ 6 };
/** Delegate for sending slot information to InventoryBar when equipping */
UPROPERTY(BlueprintAssignable, Category = Delegates, meta = (AllowPrivateAccess = "true"))
FEquipItemDelegate EquipItemDelegate;
public:
/** Returns CameraBoom subobject */
FORCEINLINE USpringArmComponent* GetCameraBoom() const { return CameraBoom; }
/** Returns FollowCamera subobject */
FORCEINLINE UCameraComponent* GetFollowCamera() const { return FollowCamera; }
FORCEINLINE bool GetAiming() const { return bAiming; }
UFUNCTION(BlueprintCallable)
float GetCrosshairSpreadMultiplier() const;
FORCEINLINE int8 GetOverlappedItemCount() const { return OverlappedItemCount; }
/** Adds/subtracts to/from OverlappedItemCount and updates bShouldTraceForItems */
void IncrementOverlappedItemCount(int8 Amount);
// No longer needed; AItem has GetInterpLocation
//FVector GetCameraInterpLocation();
void GetPickupItem(AItem* Item);
FORCEINLINE ECombatState GetCombatState() const { return CombatState; }
FORCEINLINE bool GetCrouching() const { return bCrouching; }
FInterpLocation GetInterpLocation(int32 Index);
// Returns the index in InterpLocations array with the lowest ItemCount
int32 GetInterpLocationIndex();
void IncrementInterpLocItemCount(int32 Index, int32 Amount);
FORCEINLINE bool ShouldPlayPickupSound() const { return bShouldPlayPickupSound; }
FORCEINLINE bool ShouldPlayEquipSound() const { return bShouldPlayEquipSound; }
void StartPickupSoundTimer();
void StartEquipSoundTimer();
};
| 412 | 0.896424 | 1 | 0.896424 | game-dev | MEDIA | 0.923079 | game-dev | 0.634399 | 1 | 0.634399 |
FoxMCTeam/TenacityRecode-master | 1,140 | src/java/net/minecraft/entity/player/EnumPlayerModelParts.java | package net.minecraft.entity.player;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
public enum EnumPlayerModelParts
{
CAPE(0, "cape"),
JACKET(1, "jacket"),
LEFT_SLEEVE(2, "left_sleeve"),
RIGHT_SLEEVE(3, "right_sleeve"),
LEFT_PANTS_LEG(4, "left_pants_leg"),
RIGHT_PANTS_LEG(5, "right_pants_leg"),
HAT(6, "hat");
private final int partId;
private final int partMask;
private final String partName;
private final IChatComponent field_179339_k;
private EnumPlayerModelParts(int partIdIn, String partNameIn)
{
this.partId = partIdIn;
this.partMask = 1 << partIdIn;
this.partName = partNameIn;
this.field_179339_k = new ChatComponentTranslation("options.modelPart." + partNameIn, new Object[0]);
}
public int getPartMask()
{
return this.partMask;
}
public int getPartId()
{
return this.partId;
}
public String getPartName()
{
return this.partName;
}
public IChatComponent func_179326_d()
{
return this.field_179339_k;
}
}
| 412 | 0.541679 | 1 | 0.541679 | game-dev | MEDIA | 0.60651 | game-dev | 0.791269 | 1 | 0.791269 |
ProjectIgnis/CardScripts | 1,601 | rush/c160006052.lua | -- 渡来古討つデカコレーション
--Dekorelic Dessert
-- Scripted by Hatter
local s,id=GetID()
function s.initial_effect(c)
-- Gain ATK and LP
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_RECOVER)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(s.atkcost)
e1:SetTarget(s.atktg)
e1:SetOperation(s.atkop)
c:RegisterEffect(e1)
end
function s.atkcostfilter(c)
return c:IsRace(RACE_PYRO) and c:IsAbleToDeckOrExtraAsCost()
end
function s.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.atkcostfilter,tp,LOCATION_GRAVE,0,4,nil) end
end
function s.atkfilter(c)
return c:IsFaceup() and c:IsRace(RACE_PYRO) and c:IsAttribute(ATTRIBUTE_EARTH)
end
function s.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.atkfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,800)
end
function s.atkop(e,tp,eg,ep,ev,re,r,rp)
-- Requirement
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,s.atkcostfilter,tp,LOCATION_GRAVE,0,4,4,nil)
if #g>0 and Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_COST)>0 then
Duel.ShuffleDeck(tp)
-- Effect
local ag=Duel.GetMatchingGroup(s.atkfilter,tp,LOCATION_MZONE,0,nil)
if #ag<1 then return end
local c=e:GetHandler()
for tc in ag:Iter() do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(800)
e1:SetReset(RESETS_STANDARD_PHASE_END)
tc:RegisterEffect(e1)
end
Duel.Recover(tp,800,REASON_EFFECT)
end
end | 412 | 0.938703 | 1 | 0.938703 | game-dev | MEDIA | 0.970868 | game-dev | 0.976519 | 1 | 0.976519 |
Glitchfiend/BiomesOPlenty | 2,052 | common/src/main/java/biomesoplenty/worldgen/feature/misc/ScrubFeature.java | /*******************************************************************************
* Copyright 2022, the Glitchfiend Team.
* All rights reserved.
******************************************************************************/
package biomesoplenty.worldgen.feature.misc;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.LeavesBlock;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.TreeFeature;
import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration;
public class ScrubFeature extends Feature<NoneFeatureConfiguration>
{
public ScrubFeature(Codec<NoneFeatureConfiguration> deserializer)
{
super(deserializer);
}
@Override
public boolean place(FeaturePlaceContext<NoneFeatureConfiguration> featurePlaceContext)
{
WorldGenLevel world = featurePlaceContext.level();
ChunkGenerator chunkGenerator = featurePlaceContext.chunkGenerator();
RandomSource rand = featurePlaceContext.random();
BlockPos pos = featurePlaceContext.origin();
NoneFeatureConfiguration config = featurePlaceContext.config();
int i = 0;
for(int j = 0; j < 64; ++j)
{
BlockPos blockpos = pos.offset(rand.nextInt(8) - rand.nextInt(8), rand.nextInt(4) - rand.nextInt(4), rand.nextInt(8) - rand.nextInt(8));
if (TreeFeature.isAirOrLeaves(world, blockpos) && world.getBlockState(blockpos.below()).getBlock() == Blocks.GRASS_BLOCK)
{
world.setBlock(blockpos, Blocks.OAK_LEAVES.defaultBlockState().setValue(LeavesBlock.PERSISTENT, true), 2);
++i;
}
}
return i > 0;
}
}
| 412 | 0.587778 | 1 | 0.587778 | game-dev | MEDIA | 0.999494 | game-dev | 0.524523 | 1 | 0.524523 |
savatkinv/VoxelGame | 1,227 | VoxelGame_UnityProject/Assets/Plugins/Zenject/Source/Providers/ComponentProviders/AddToGameObjectComponentProviders/AddToNewGameObjectComponentProvider.cs | #if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Zenject
{
[NoReflectionBaking]
public class AddToNewGameObjectComponentProvider : AddToGameObjectComponentProviderBase
{
readonly GameObjectCreationParameters _gameObjectBindInfo;
public AddToNewGameObjectComponentProvider(
DiContainer container, Type componentType,
IEnumerable<TypeValuePair> extraArguments, GameObjectCreationParameters gameObjectBindInfo,
object concreteIdentifier,
Action<InjectContext, object> instantiateCallback)
: base(container, componentType, extraArguments, concreteIdentifier, instantiateCallback)
{
_gameObjectBindInfo = gameObjectBindInfo;
}
protected override bool ShouldToggleActive
{
get { return true; }
}
protected override GameObject GetGameObject(InjectContext context)
{
if (_gameObjectBindInfo.Name == null)
{
_gameObjectBindInfo.Name = ComponentType.Name;
}
return Container.CreateEmptyGameObject(_gameObjectBindInfo, context);
}
}
}
#endif
| 412 | 0.837176 | 1 | 0.837176 | game-dev | MEDIA | 0.977288 | game-dev | 0.798664 | 1 | 0.798664 |
open-telemetry/opentelemetry-java | 3,036 | exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/SampleMarshaler.java | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.exporter.otlp.profiles;
import io.opentelemetry.exporter.internal.marshal.MarshalerUtil;
import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize;
import io.opentelemetry.exporter.internal.marshal.Serializer;
import io.opentelemetry.proto.profiles.v1development.internal.Sample;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
final class SampleMarshaler extends MarshalerWithSize {
private static final SampleMarshaler[] EMPTY_REPEATED = new SampleMarshaler[0];
private final int stackIndex;
private final List<Long> values;
private final List<Integer> attributeIndices;
private final int linkIndex;
private final List<Long> timestamps;
static SampleMarshaler create(SampleData sampleData) {
return new SampleMarshaler(
sampleData.getStackIndex(),
sampleData.getValues(),
sampleData.getAttributeIndices(),
sampleData.getLinkIndex(),
sampleData.getTimestamps());
}
static SampleMarshaler[] createRepeated(List<SampleData> items) {
if (items.isEmpty()) {
return EMPTY_REPEATED;
}
SampleMarshaler[] sampleMarshalers = new SampleMarshaler[items.size()];
items.forEach(
new Consumer<SampleData>() {
int index = 0;
@Override
public void accept(SampleData sampleData) {
sampleMarshalers[index++] = SampleMarshaler.create(sampleData);
}
});
return sampleMarshalers;
}
private SampleMarshaler(
int stackIndex,
List<Long> values,
List<Integer> attributeIndices,
int linkIndex,
List<Long> timestamps) {
super(calculateSize(stackIndex, values, attributeIndices, linkIndex, timestamps));
this.stackIndex = stackIndex;
this.values = values;
this.attributeIndices = attributeIndices;
this.linkIndex = linkIndex;
this.timestamps = timestamps;
}
@Override
protected void writeTo(Serializer output) throws IOException {
output.serializeInt32(Sample.STACK_INDEX, stackIndex);
output.serializeRepeatedInt64(Sample.VALUES, values);
output.serializeRepeatedInt32(Sample.ATTRIBUTE_INDICES, attributeIndices);
output.serializeInt32(Sample.LINK_INDEX, linkIndex);
output.serializeRepeatedFixed64(Sample.TIMESTAMPS_UNIX_NANO, timestamps);
}
private static int calculateSize(
int stackIndex,
List<Long> values,
List<Integer> attributeIndices,
int linkIndex,
List<Long> timestamps) {
int size;
size = 0;
size += MarshalerUtil.sizeInt32(Sample.STACK_INDEX, stackIndex);
size += MarshalerUtil.sizeRepeatedInt64(Sample.VALUES, values);
size += MarshalerUtil.sizeRepeatedInt32(Sample.ATTRIBUTE_INDICES, attributeIndices);
size += MarshalerUtil.sizeInt32(Sample.LINK_INDEX, linkIndex);
size += MarshalerUtil.sizeRepeatedFixed64(Sample.TIMESTAMPS_UNIX_NANO, timestamps);
return size;
}
}
| 412 | 0.78751 | 1 | 0.78751 | game-dev | MEDIA | 0.325874 | game-dev | 0.530343 | 1 | 0.530343 |
proficiency/ascii_survivors | 10,345 | src/main.rs | mod effects;
mod objects;
mod resources;
mod systems;
use crate::{effects::*, objects::*, resources::*, systems::*};
use bevy::{prelude::*, window::*};
use bevy_ascii_terminal::*;
use std::path::*;
fn main() {
App::new()
.add_plugins((
DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "ASCII Survivors".into(),
visible: false,
present_mode: PresentMode::Fifo,
..default()
}),
..default()
}),
TerminalPlugins,
))
.init_state::<GameState>()
.add_systems(Startup, (setup, setup_resources, list_gamepads).chain())
.add_systems(OnEnter(GameState::Loading), show_window)
.add_systems(
OnEnter(GameState::FadingIn),
(reset_fade_timer, play_start_sound).chain(),
)
.add_systems(OnEnter(GameState::Game), (setup_game, play_theme).chain())
.add_systems(OnEnter(GameState::GameOver), stop_theme_music)
.add_systems(
Update,
(
(loading_render_system, loading_update_system).run_if(in_state(GameState::Loading)),
(menu_input_system, menu_render_system).run_if(in_state(GameState::Menu)),
(fade_in_render_system, fade_in_update_system)
.run_if(in_state(GameState::FadingIn)),
(
player_movement,
spawn_enemies,
(
enemy_ai,
auto_cast,
process_projectiles,
process_collisions,
orb_movement,
process_orb_collection,
)
.chain(),
update_damage_effect,
death_detection_system,
systems::render::draw_scene,
despawn_entities,
)
.chain()
.run_if(in_state(GameState::Game)),
(
game_over_input_system,
despawn_all_entities.run_if(in_state(GameState::GameOver)),
game_over_render_system,
)
.run_if(in_state(GameState::GameOver)),
),
)
.run();
}
fn play_theme(mut sound_manager: ResMut<SoundManager>) {
sound_manager.play_theme(-17.0).unwrap();
}
fn setup_resources(mut commands: Commands) {
commands.insert_resource(EnemySpawnTimer(Timer::from_seconds(
1.25,
TimerMode::Repeating,
)));
commands.insert_resource(ProjectileCooldownTimer(Timer::from_seconds(
2.0,
TimerMode::Once,
)));
commands.insert_resource(PlayerMovementTimer(Timer::from_seconds(
0.1,
TimerMode::Repeating,
)));
commands.insert_resource(EnemyMovementTimer(Timer::from_seconds(
0.35,
TimerMode::Repeating,
)));
commands.insert_resource(DamageEffectTimer(Timer::from_seconds(0.5, TimerMode::Once)));
commands.insert_resource(LoadingTimer(Timer::from_seconds(3.0, TimerMode::Once)));
commands.insert_resource(FadeTimer(Timer::from_seconds(2.0, TimerMode::Once)));
commands.insert_resource(CameraOffset(IVec2::default()));
commands.insert_resource(
SoundManager::new(PathBuf::from("./assets/sfx/")).expect("failed to load manager"),
);
}
fn setup(mut commands: Commands) {
commands.spawn(Terminal::new([80, 50]));
commands.spawn(TerminalCamera::new());
}
fn setup_game(mut commands: Commands) {
commands.spawn((Player::new(IVec2::new(40, 25)), Transform::default()));
}
fn list_gamepads(gamepads: Query<(&Name, &Gamepad)>) {
println!("Looking for gamepads...");
for name in &gamepads {
println!("Found gamepad: {}", name.0);
}
}
fn menu_render_system(mut query: Query<&mut Terminal>) {
if let Ok(mut terminal) = query.single_mut() {
terminal.clear();
let title = "ASCII SURVIVORS";
let title_x = (80 - title.len()) / 2;
terminal.put_string([title_x, 15], title);
let button_text = "[ PLAY ]";
let button_x = (80 - button_text.len()) / 2;
terminal.put_string([button_x, 25], button_text);
let instruction = "Press SPACE or ENTER to start";
let instruction_x = (80 - instruction.len()) / 2;
terminal.put_string([instruction_x, 30], instruction);
}
}
fn menu_input_system(
input: Res<ButtonInput<KeyCode>>,
_mouse_input: Res<ButtonInput<MouseButton>>,
mut next_state: ResMut<NextState<GameState>>,
) {
if input.just_pressed(KeyCode::Space) || input.just_pressed(KeyCode::Enter) {
next_state.set(GameState::FadingIn);
}
}
fn loading_render_system(mut query: Query<&mut Terminal>, loading_timer: Res<LoadingTimer>) {
if let Ok(mut terminal) = query.single_mut() {
terminal.clear();
let title = "ASCII SURVIVORS";
let title_x = (80 - title.len()) / 2;
terminal.put_string([title_x, 20], title);
let loading_text = "Loading...";
let loading_x = (80 - loading_text.len()) / 2;
terminal.put_string([loading_x, 25], loading_text);
let progress = loading_timer.0.fraction();
let bar_width = 40;
let filled_width = (bar_width as f32 * progress) as usize;
let bar_x = (80 - bar_width) / 2;
for i in 0..bar_width {
if i < filled_width {
terminal.put_char([bar_x + i, 27], '█');
} else {
terminal.put_char([bar_x + i, 27], '░');
}
}
let percentage = format!("{}%", (progress * 100.0) as u32);
let percent_x = (80 - percentage.len()) / 2;
terminal.put_string([percent_x, 29], percentage);
}
}
fn loading_update_system(
time: Res<Time>,
mut loading_timer: ResMut<LoadingTimer>,
mut next_state: ResMut<NextState<GameState>>,
) {
loading_timer.0.tick(time.delta());
if loading_timer.0.finished() {
next_state.set(GameState::Menu);
}
}
fn show_window(mut window_query: Query<&mut Window>) {
if let Ok(mut window) = window_query.single_mut() {
window.visible = true;
}
}
fn reset_fade_timer(mut fade_timer: ResMut<FadeTimer>) {
fade_timer.0.reset();
}
fn play_start_sound(mut sound_manager: ResMut<SoundManager>) {
sound_manager
.play_sound(PathBuf::from("./start.wav"), -5.0)
.expect("Failed to play start sound");
}
fn fade_in_render_system(mut query: Query<&mut Terminal>, fade_timer: Res<FadeTimer>) {
if let Ok(mut terminal) = query.single_mut() {
terminal.clear();
let fade_progress = fade_timer.0.fraction();
let terminal_height = 50;
let terminal_width = 80;
let fade_char = if fade_progress < 0.3 {
'█'
} else if fade_progress < 0.6 {
'▓'
} else if fade_progress < 0.9 {
'▒'
} else {
'░'
};
let coverage = 1.0 - fade_progress;
for y in 0..terminal_height {
for x in 0..terminal_width {
let center_x = terminal_width as f32 / 2.0;
let center_y = terminal_height as f32 / 2.0;
let distance =
((x as f32 - center_x).powi(2) + (y as f32 - center_y).powi(2)).sqrt();
let max_distance = (center_x.powi(2) + center_y.powi(2)).sqrt();
let normalized_distance = distance / max_distance;
if normalized_distance < coverage {
terminal.put_char([x, y], fade_char);
}
}
}
if fade_progress < 0.8 {
let starting_text = "Starting...";
let starting_x = (80 - starting_text.len()) / 2;
terminal.put_string([starting_x, 25], starting_text);
}
}
}
fn fade_in_update_system(
time: Res<Time>,
mut fade_timer: ResMut<FadeTimer>,
mut next_state: ResMut<NextState<GameState>>,
) {
fade_timer.0.tick(time.delta());
if fade_timer.0.finished() {
next_state.set(GameState::Game);
}
}
fn death_detection_system(
player_query: Query<&Player>,
mut next_state: ResMut<NextState<GameState>>,
) {
if let Ok(player) = player_query.single()
&& player.health <= 0.0
{
next_state.set(GameState::GameOver);
}
}
fn stop_theme_music(mut sound_manager: ResMut<SoundManager>) {
sound_manager.stop_theme();
}
fn game_over_render_system(mut query: Query<&mut Terminal>) {
if let Ok(mut terminal) = query.single_mut() {
terminal.clear();
let death_message = "YOU DIED!";
let death_x = (80 - death_message.len()) / 2;
terminal.put_string([death_x, 20], death_message);
let restart_message = "Press R to Restart";
let restart_x = (80 - restart_message.len()) / 2;
terminal.put_string([restart_x, 25], restart_message);
let menu_message = "Press ESC to return to Menu";
let menu_x = (80 - menu_message.len()) / 2;
terminal.put_string([menu_x, 27], menu_message);
}
}
fn despawn_all_entities(
mut commands: Commands,
player_query: Query<Entity, With<Player>>,
enemy_query: Query<Entity, With<Enemy>>,
projectile_query: Query<Entity, With<Projectile>>,
orb_query: Query<Entity, With<Orb>>,
) {
for entity in player_query.iter() {
commands.entity(entity).despawn();
}
for entity in enemy_query.iter() {
commands.entity(entity).despawn();
}
for entity in projectile_query.iter() {
commands.entity(entity).despawn();
}
for entity in orb_query.iter() {
commands.entity(entity).despawn();
}
}
fn game_over_input_system(
input: Res<ButtonInput<KeyCode>>,
mut next_state: ResMut<NextState<GameState>>,
mut camera_offset: ResMut<CameraOffset>,
) {
if input.just_pressed(KeyCode::KeyR) {
camera_offset.0 = IVec2::default();
next_state.set(GameState::Game);
} else if input.just_pressed(KeyCode::Escape) {
camera_offset.0 = IVec2::default();
next_state.set(GameState::Menu);
}
}
| 412 | 0.959417 | 1 | 0.959417 | game-dev | MEDIA | 0.955797 | game-dev | 0.979047 | 1 | 0.979047 |
RedpointArchive/Protogame | 8,066 | Protogame/UserInterface/Controller/DefaultUserInterfaceController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Protoinject;
namespace Protogame
{
public class DefaultUserInterfaceController : IUserInterfaceController
{
private readonly IKernel _kernel;
private readonly IHierarchy _hierarchy;
private readonly INode _node;
private readonly UserInterfaceAsset _userInterfaceAsset;
private readonly
Dictionary<string, Dictionary<UserInterfaceBehaviourEvent, UserInterfaceBehaviourHandler<object>>>
_registeredBehaviours;
private readonly Dictionary<object, string[]> _containerBehaviours;
private IGameContext _currentGameContext;
private IUpdateContext _currentUpdateContext;
private bool _loadedUserInterface;
private CanvasEntity _canvasEntity;
private Dictionary<string, XmlNode> _availableFragments;
private HashSet<IContainer> _firedCreatedEventsForContainers;
private bool _enabled;
public DefaultUserInterfaceController(IKernel kernel, IHierarchy hierarchy, INode node, UserInterfaceAsset userInterfaceAsset)
{
_kernel = kernel;
_hierarchy = hierarchy;
_node = node;
_userInterfaceAsset = userInterfaceAsset;
_registeredBehaviours = new Dictionary<string, Dictionary<UserInterfaceBehaviourEvent, UserInterfaceBehaviourHandler<object>>>();
_containerBehaviours = new Dictionary<object, string[]>();
_availableFragments = new Dictionary<string, XmlNode>();
_firedCreatedEventsForContainers = new HashSet<IContainer>();
_enabled = true;
}
public void Update(IGameContext gameContext, IUpdateContext updateContext)
{
_currentGameContext = gameContext;
_currentUpdateContext = updateContext;
if (!_loadedUserInterface)
{
LoadUserInterface(gameContext);
_loadedUserInterface = true;
}
foreach (var kv in _containerBehaviours)
{
var sender = (IContainer)kv.Key;
if (_firedCreatedEventsForContainers.Contains(sender))
{
continue;
}
foreach (var behaviour in kv.Value)
{
if (!_registeredBehaviours.ContainsKey(behaviour))
{
continue;
}
if (!_registeredBehaviours[behaviour].ContainsKey(UserInterfaceBehaviourEvent.Create))
{
continue;
}
_registeredBehaviours[behaviour][UserInterfaceBehaviourEvent.Create](sender, this,
_currentGameContext, _currentUpdateContext);
}
_firedCreatedEventsForContainers.Add(sender);
}
foreach (var kv in _containerBehaviours)
{
var sender = kv.Key;
foreach (var behaviour in kv.Value)
{
if (!_registeredBehaviours.ContainsKey(behaviour))
{
continue;
}
if (!_registeredBehaviours[behaviour].ContainsKey(UserInterfaceBehaviourEvent.GameUpdate))
{
continue;
}
_registeredBehaviours[behaviour][UserInterfaceBehaviourEvent.GameUpdate](sender, this, _currentGameContext, _currentUpdateContext);
}
}
}
private void LoadUserInterface(IGameContext gameContext)
{
var document = new XmlDocument();
document.LoadXml(_userInterfaceAsset.UserInterfaceData);
var childNodes = document.DocumentElement?.ChildNodes;
if (childNodes == null)
{
return;
}
foreach (var element in childNodes.OfType<XmlElement>())
{
if (element.Name == "canvas")
{
if (_canvasEntity == null)
{
var root = ProcessElement(element);
if (root is Canvas)
{
_canvasEntity = _kernel.Get<CanvasEntity>(_hierarchy.Lookup(gameContext.World));
_canvasEntity.Canvas = (Canvas) root;
_canvasEntity.CanvasesEnabled = Enabled;
}
}
else
{
throw new InvalidOperationException("User interface file declares more than one canvas.");
}
}
else if (element.Name == "fragment")
{
_availableFragments[element.GetAttribute("name")] = element;
}
}
}
public IContainer LoadUserFragment(string name)
{
var c = ((CanvasFragment)ProcessElement(_availableFragments[name])).Children[0];
c.Parent = null;
return c;
}
private IContainer ProcessElement(XmlNode xmlNode)
{
var processor = _kernel.TryGet<IUserInterfaceNodeProcessor>(_node, xmlNode.LocalName);
if (processor == null)
{
return null;
}
Action<XmlNode, IContainer> processChild;
var container = processor.Process(xmlNode, HandleEventFromContainer, out processChild);
if (container == null)
{
return null;
}
_containerBehaviours[container] = (xmlNode?.Attributes?["behaviours"]?.Value ?? string.Empty).Split(',');
foreach (var child in xmlNode.ChildNodes.OfType<XmlNode>())
{
var childContainer = ProcessElement(child);
if (childContainer != null)
{
processChild(child, childContainer);
}
}
return container;
}
private void HandleEventFromContainer(UserInterfaceBehaviourEvent ev, object sender)
{
if (!_containerBehaviours.ContainsKey(sender))
{
return;
}
var behaviours = _containerBehaviours[sender];
foreach (var behaviour in behaviours)
{
if (!_registeredBehaviours.ContainsKey(behaviour))
{
continue;
}
if (!_registeredBehaviours[behaviour].ContainsKey(ev))
{
continue;
}
_registeredBehaviours[behaviour][ev](sender, this, _currentGameContext, _currentUpdateContext);
}
}
public void RegisterBehaviour<TContainerType>(string name, UserInterfaceBehaviourEvent @event, UserInterfaceBehaviourHandler<TContainerType> callback)
{
if (!_registeredBehaviours.ContainsKey(name))
{
_registeredBehaviours[name] = new Dictionary<UserInterfaceBehaviourEvent, UserInterfaceBehaviourHandler<object>>();
}
_registeredBehaviours[name][@event] = (o, t, g, u) => { callback((TContainerType) o, t, g, u); };
}
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
if (_loadedUserInterface)
{
_canvasEntity.CanvasesEnabled = value;
}
}
}
public void Dispose()
{
if (_loadedUserInterface)
{
var node = _hierarchy.Lookup(_canvasEntity);
_hierarchy.RemoveNode(node);
}
}
}
}
| 412 | 0.88656 | 1 | 0.88656 | game-dev | MEDIA | 0.395112 | game-dev | 0.6487 | 1 | 0.6487 |
realXtend/tundra | 3,765 | src/Application/JavascriptModule/JavascriptModule.h | /**
* For conditions of distribution and use, see copyright notice in LICENSE
*
* @file JavascriptModule.h
* @brief Enables Javascript execution and scripting by using QtScript.
*/
#pragma once
#include "IModule.h"
#include "AttributeChangeType.h"
#include "AssetFwd.h"
#include "SceneFwd.h"
#include "JavascriptFwd.h"
#include <QVariant>
class JavascriptInstance;
/// Enables Javascript execution and scripting by using QtScript.
class JavascriptModule : public IModule
{
Q_OBJECT
public:
JavascriptModule();
~JavascriptModule();
void Load();
void Initialize();
void Uninitialize();
/// Prepares script instance by registering all needed services to it.
/** If script is part of the scene, i.e. EC_Script component is present, we add some special services.
@param instance Script istance.
@param comp Script component, null by default. */
void PrepareScriptInstance(JavascriptInstance* instance, EC_Script *comp = 0);
public slots:
void DumpScriptInfo();
/// Executes js file.
void RunScript(const QString &scriptFilename);
/// Executes and arbitrary js code string.
void RunString(const QString &codeString, const QVariantMap &context = QVariantMap());
signals:
/// A script engine has been created
/** The purpose of this is to allow dynamic service objects (registered with Framework::RegisterDynamicObject)
to perform further scriptengine initialization, such as registration of new datatypes. The slot
OnScriptEngineCreated() will be invoked on the dynamic service object, if it exists. */
void ScriptEngineCreated(QScriptEngine* engine);
private:
/// Parses the plugin startup configuration file to detect which startup scripts should be run.
/** @return Returns a QStringList of script paths */
QStringList ParseStartupScriptConfig();
/// Startup js scripts specified on the command line via --jsplugin
/** @return List of script paths relative to bin/jsplugins */
QStringList StartupScripts();
/// Stops and deletes startup scripts
void UnloadStartupScripts();
/// Parse the appname and classname from an EC_Script
void ParseAppAndClassName(EC_Script* instance, QString& appName, QString& className);
/// Find a named script application
EC_Script* FindScriptApplication(EC_Script* instance, const QString& appName);
/// Create a script class instance into a script application
void CreateScriptObject(EC_Script* app, EC_Script* instance, const QString& className);
/// Remove a script class instance from an EC_Script
void RemoveScriptObject(EC_Script* instance);
/// Create script class instances for all EC_Scripts depending on this script application
void CreateScriptObjects(EC_Script* app);
/// Remove script class instances for all EC_Scripts depending on this script application
void RemoveScriptObjects(JavascriptInstance* jsInstance);
/// Default engine for console & commandline script execution
QScriptEngine *engine;
/// Engines for executing startup (possibly persistent) scripts
std::vector<JavascriptInstance *> startupScripts_;
private slots:
/// (Re)loads and executes startup scripts.
void LoadStartupScripts();
void ScriptEvaluated();
void ScriptUnloading();
void SceneAdded(const QString &name);
void ComponentAdded(Entity* entity, IComponent* comp, AttributeChange::Type change);
void ComponentRemoved(Entity* entity, IComponent* comp, AttributeChange::Type change);
void ScriptAssetsChanged(const std::vector<ScriptAssetPtr>& newScripts);
void ScriptAppNameChanged(const QString& newAppName);
void ScriptClassNameChanged(const QString& newClassName);
};
| 412 | 0.520295 | 1 | 0.520295 | game-dev | MEDIA | 0.686461 | game-dev | 0.656481 | 1 | 0.656481 |
STForScratch/ScratchTools | 2,465 | features/select-self/script.js | export default async function ({ feature, console }) {
let MENU_TYPES = [
"motion_glideto_menu",
"motion_goto_menu",
"motion_pointtowards_menu",
"sensing_touchingobjectmenu",
"sensing_of_object_menu",
"sensing_distancetomenu",
];
let ORIGINAL_DATA = {
motion_glideto_menu: [
["random position", "_random_"],
["mouse-pointer", "_mouse_"],
],
motion_goto_menu: [
["random position", "_random_"],
["mouse-pointer", "_mouse_"],
],
motion_pointtowards_menu: [["random position", "_random_"]],
sensing_touchingobjectmenu: [
["mouse-pointer", "_mouse_"],
["edge", "_edge_"],
],
sensing_of_object_menu: [["Stage", "_stage_"]],
sensing_distancetomenu: [["mouse-pointer", "_mouse_"]],
};
let blocks = [];
ScratchTools.waitForElements(
"g.blocklyDraggable > g[data-shapes='argument round']",
function (block) {
if (!Blockly) return;
block = Blockly.getMainWorkspace().getBlockById(block.dataset.id);
if (!block) return;
if (MENU_TYPES.includes(block.type)) {
let menu = block.inputList[0].fieldRow[0].menuGenerator_;
if (!blocks.includes(block.id)) {
blocks.push(block.id);
}
updateMenu(block.id);
}
}
);
feature.traps.vm.on("targetsUpdate", function (el) {
for (var i in blocks) {
updateMenu(blocks[i]);
}
});
feature.addEventListener("disabled", function () {
for (var i in blocks) {
updateMenu(blocks[i]);
}
});
feature.addEventListener("enabled", function () {
for (var i in blocks) {
updateMenu(blocks[i]);
}
});
function updateMenu(blockId) {
let SPRITES = [];
let targets = feature.traps.vm.runtime.targets.filter(
(target) => !target.isStage && target.isOriginal
);
for (var i in targets) {
SPRITES.push(targets[i].sprite.name);
}
let block = Blockly.getMainWorkspace().getBlockById(blockId);
if (!block) return;
block.inputList[0].fieldRow[0].menuGenerator_ = function () {
let data = ORIGINAL_DATA[block.type];
for (var i in SPRITES) {
if (
feature.self.enabled ||
feature.traps.vm.runtime._editingTarget?.sprite?.name !== SPRITES[i]
) {
if (!data.find((el) => el[0] === SPRITES[i])) {
data.push([SPRITES[i], SPRITES[i]]);
}
}
}
return data;
};
}
}
| 412 | 0.893586 | 1 | 0.893586 | game-dev | MEDIA | 0.670198 | game-dev | 0.512913 | 1 | 0.512913 |
RigsOfRods/rigs-of-rods | 4,614 | source/main/gameplay/VehicleAI.h | /*
This source file is part of Rigs of Rods
Copyright 2005-2012 Pierre-Michel Ricordel
Copyright 2007-2012 Thomas Fischer
Copyright 2013-2016 Petr Ohlidal
For more information, see http://www.rigsofrods.org/
Rigs of Rods is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as
published by the Free Software Foundation.
Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>.
*/
/// @file
/// @brief Simple waypoint AI
/// @author AnotherFoxGuy
/// @date 03/2016
#pragma once
#ifdef USE_ANGELSCRIPT
#include "Application.h"
#include "RefCountingObject.h"
#include "scriptdictionary/scriptdictionary.h"
#include <string>
namespace RoR {
/**
* Enum with AI events
*/
enum Ai_events
{
AI_HORN,
AI_LIGHTSTOGGLE,
AI_WAIT_SECONDS,
AI_BEACONSTOGGLE
};
/**
* Enum with AI values that can be set.
*/
enum Ai_values
{
AI_SPEED,
AI_POWER
};
class VehicleAI : public RefCountingObject<VehicleAI>
{
// PLEASE maintain the same order as in 'bindings/VehicleAiAngelscript.cpp' and 'doc/../VehicleAIClass.h'
public:
VehicleAI(ActorPtr b);
virtual ~VehicleAI() override;
/**
* Activates/Deactivates the AI.
* @param [in] value Activate or deactivation the AI
*/
void setActive(bool value);
/**
* Returns the status of the AI.
* @return True if the AI is driving
*/
bool isActive();
/**
* Adds one waypoint.
*
* @param [in] id The waypoint ID.
* @param [in] point The coordinates of the waypoint.
*/
void addWaypoint(std::string const& id, Ogre::Vector3 const& point);
/**
* Adds a dictionary with waypoints.
* @param d Dictionary with waypoints (string ID -> vector3 pos)
*/
void addWaypoints(AngelScript::CScriptDictionary& d);
/**
* Adds a event
*
* @param id The waypoint ID.
* @param ev The ID of the event.
*
* @see Ai_events
*/
void addEvent(std::string const& id, int ev);
/**
* Sets a value at a waypoint.
*
* @param id The waypoint ID.
* @param value_id The ID of the value that will be set.
* @param value The value itself.
*
* @see Ai_values
*/
void setValueAtWaypoint(std::string const& id, int value_id, float value);
/**
* Gets offset translation based on vehicle rotation and waypoints
*
* @param offset The offset.
* @param wp The waypoint.
*/
Ogre::Vector3 getTranslation(int offset, unsigned int wp);
// Not exported to script:
/**
* Updates the AI.
*/
void update(float dt, int doUpdate);
private:
/**
* Updates the AI waypoint.
*/
void updateWaypoint();
bool is_waiting=false;//!<
float wait_time=0.f;//!<(seconds) The amount of time the AI has to wait.
float maxspeed = 50;//!<(KM/H) The max speed the AI is allowed to drive.
ActorPtr beam;//!< The verhicle the AI is driving.
bool is_enabled = false;//!< True if the AI is driving.
Ogre::Vector3 current_waypoint = Ogre::Vector3::ZERO;//!< The coordinates of the waypoint that the AI is driving to.
Ogre::Vector3 prev_waypoint = Ogre::Vector3::ZERO;;//!< The coordinates of the previous waypoint.
Ogre::Vector3 next_waypoint = Ogre::Vector3::ZERO;;//!< The coordinates of the next waypoint.
int current_waypoint_id = 0;//!< The curent waypoint ID.
std::map<int, Ogre::Vector3> waypoints;//!< Map with all waypoints.
std::map<std::string, int> waypoint_ids;//!< Map with all waypoint IDs.
std::map<int, std::string> waypoint_names;//!< Map with all waypoint names.
std::map<int, int> waypoint_events;//!< Map with all waypoint events.
std::map<Ogre::String, float> waypoint_speed;//!< Map with all waypoint speeds.
std::map<int, float> waypoint_power;//!< Map with all waypoint engine power.
std::map<int, float> waypoint_wait_time;//!< Map with all waypoint wait times.
int free_waypoints = 0;//!< The amount of waypoints.
float acc_power = 0.8;//!< The engine power.
float init_y = 0;
bool last_waypoint = false;
bool hold = false;
};
} // namespace RoR
#endif // USE_ANGELSCRIPT
| 412 | 0.802196 | 1 | 0.802196 | game-dev | MEDIA | 0.897788 | game-dev | 0.649516 | 1 | 0.649516 |
ProjectIgnis/CardScripts | 1,734 | official/c61190918.lua | --トゥーン・バスター・ブレイダー
--Toon Buster Blader
local s,id=GetID()
function s.initial_effect(c)
--Cannot attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetOperation(s.atklimit)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e3)
--Increase ATK
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetCode(EFFECT_UPDATE_ATTACK)
e4:SetRange(LOCATION_MZONE)
e4:SetValue(s.val)
c:RegisterEffect(e4)
--Direct attack
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_DIRECT_ATTACK)
e5:SetCondition(s.dircon)
c:RegisterEffect(e5)
end
s.listed_names={15259703}
function s.atklimit(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetReset(RESETS_STANDARD_PHASE_END)
e:GetHandler():RegisterEffect(e1)
end
function s.dirfilter1(c)
return c:IsFaceup() and c:IsCode(15259703)
end
function s.dirfilter2(c)
return c:IsFaceup() and c:IsType(TYPE_TOON)
end
function s.dircon(e)
return Duel.IsExistingMatchingCard(s.dirfilter1,e:GetHandlerPlayer(),LOCATION_ONFIELD,0,1,nil)
and not Duel.IsExistingMatchingCard(s.dirfilter2,e:GetHandlerPlayer(),0,LOCATION_MZONE,1,nil)
end
function s.val(e,c)
return Duel.GetMatchingGroupCount(s.filter,c:GetControler(),0,LOCATION_GRAVE|LOCATION_MZONE,nil)*500
end
function s.filter(c)
return c:IsRace(RACE_DRAGON) and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup())
end | 412 | 0.893432 | 1 | 0.893432 | game-dev | MEDIA | 0.981891 | game-dev | 0.819537 | 1 | 0.819537 |
SonicEraZoR/Portal-Base | 1,444 | sp/src/game/server/ai_basehumanoid.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef AI_BASEHUMANOID_H
#define AI_BASEHUMANOID_H
#include "ai_behavior.h"
#include "ai_blended_movement.h"
//-----------------------------------------------------------------------------
// CLASS: CAI_BaseHumanoid
//-----------------------------------------------------------------------------
typedef CAI_BlendingHost< CAI_BehaviorHost<CAI_BaseNPC> > CAI_BaseHumanoidBase;
class CAI_BaseHumanoid : public CAI_BaseHumanoidBase
{
DECLARE_CLASS( CAI_BaseHumanoid, CAI_BaseHumanoidBase );
public:
bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt);
// Tasks
virtual void StartTask( const Task_t *pTask );
virtual void RunTask( const Task_t *pTask );
virtual void BuildScheduleTestBits( );
// Navigation
bool OnMoveBlocked( AIMoveResult_t *pResult );
// Damage
void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator );
// Various start tasks
virtual void StartTaskRangeAttack1( const Task_t *pTask );
// Various run tasks
virtual void RunTaskRangeAttack1( const Task_t *pTask );
// Purpose: check ammo
virtual void CheckAmmo( void );
};
//-----------------------------------------------------------------------------
#endif
| 412 | 0.93312 | 1 | 0.93312 | game-dev | MEDIA | 0.96149 | game-dev | 0.606481 | 1 | 0.606481 |
andrewnakas/OpenBrushVR | 3,185 | IOSTEST/Classes/Native/UnityEngine_UI_UnityEngine_UI_ObjectPool_1_gen1235855446.h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object2689449295.h"
// System.Collections.Generic.Stack`1<System.Object>
struct Stack_1_t3777177449;
// UnityEngine.Events.UnityAction`1<System.Object>
struct UnityAction_1_t4056035046;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.ObjectPool`1<System.Object>
struct ObjectPool_1_t1235855446 : public Il2CppObject
{
public:
// System.Collections.Generic.Stack`1<T> UnityEngine.UI.ObjectPool`1::m_Stack
Stack_1_t3777177449 * ___m_Stack_0;
// UnityEngine.Events.UnityAction`1<T> UnityEngine.UI.ObjectPool`1::m_ActionOnGet
UnityAction_1_t4056035046 * ___m_ActionOnGet_1;
// UnityEngine.Events.UnityAction`1<T> UnityEngine.UI.ObjectPool`1::m_ActionOnRelease
UnityAction_1_t4056035046 * ___m_ActionOnRelease_2;
// System.Int32 UnityEngine.UI.ObjectPool`1::<countAll>k__BackingField
int32_t ___U3CcountAllU3Ek__BackingField_3;
public:
inline static int32_t get_offset_of_m_Stack_0() { return static_cast<int32_t>(offsetof(ObjectPool_1_t1235855446, ___m_Stack_0)); }
inline Stack_1_t3777177449 * get_m_Stack_0() const { return ___m_Stack_0; }
inline Stack_1_t3777177449 ** get_address_of_m_Stack_0() { return &___m_Stack_0; }
inline void set_m_Stack_0(Stack_1_t3777177449 * value)
{
___m_Stack_0 = value;
Il2CppCodeGenWriteBarrier(&___m_Stack_0, value);
}
inline static int32_t get_offset_of_m_ActionOnGet_1() { return static_cast<int32_t>(offsetof(ObjectPool_1_t1235855446, ___m_ActionOnGet_1)); }
inline UnityAction_1_t4056035046 * get_m_ActionOnGet_1() const { return ___m_ActionOnGet_1; }
inline UnityAction_1_t4056035046 ** get_address_of_m_ActionOnGet_1() { return &___m_ActionOnGet_1; }
inline void set_m_ActionOnGet_1(UnityAction_1_t4056035046 * value)
{
___m_ActionOnGet_1 = value;
Il2CppCodeGenWriteBarrier(&___m_ActionOnGet_1, value);
}
inline static int32_t get_offset_of_m_ActionOnRelease_2() { return static_cast<int32_t>(offsetof(ObjectPool_1_t1235855446, ___m_ActionOnRelease_2)); }
inline UnityAction_1_t4056035046 * get_m_ActionOnRelease_2() const { return ___m_ActionOnRelease_2; }
inline UnityAction_1_t4056035046 ** get_address_of_m_ActionOnRelease_2() { return &___m_ActionOnRelease_2; }
inline void set_m_ActionOnRelease_2(UnityAction_1_t4056035046 * value)
{
___m_ActionOnRelease_2 = value;
Il2CppCodeGenWriteBarrier(&___m_ActionOnRelease_2, value);
}
inline static int32_t get_offset_of_U3CcountAllU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(ObjectPool_1_t1235855446, ___U3CcountAllU3Ek__BackingField_3)); }
inline int32_t get_U3CcountAllU3Ek__BackingField_3() const { return ___U3CcountAllU3Ek__BackingField_3; }
inline int32_t* get_address_of_U3CcountAllU3Ek__BackingField_3() { return &___U3CcountAllU3Ek__BackingField_3; }
inline void set_U3CcountAllU3Ek__BackingField_3(int32_t value)
{
___U3CcountAllU3Ek__BackingField_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 412 | 0.521111 | 1 | 0.521111 | game-dev | MEDIA | 0.868591 | game-dev | 0.688526 | 1 | 0.688526 |
czimaginginstitute/MotionCor3 | 2,793 | Util/CMultiGpuBase.cpp | #include "CUtilInc.h"
#include <memory.h>
#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cufft.h>
using namespace MotionCor2::Util;
CMultiGpuBase::CMultiGpuBase(void)
{
m_pStreams = 0L;
m_pForwardFFTs = 0L;
m_pInverseFFTs = 0L;
m_piGpuIDs = 0L;
m_iNumGpus = 0;
}
CMultiGpuBase::~CMultiGpuBase(void)
{
this->mCleanAll();
}
void CMultiGpuBase::mCleanAll(void)
{
this->mDeleteForwardFFTs();
this->mDeleteInverseFFTs();
this->mDeleteStreams();
if(m_piGpuIDs != 0L) delete[] m_piGpuIDs;
m_piGpuIDs = 0L;
}
void CMultiGpuBase::mSetGpus(int* piGpuIDs, int iNumGpus)
{
this->mCleanAll();
//----------------
m_piGpuIDs = new int[iNumGpus];
memcpy(m_piGpuIDs, piGpuIDs, sizeof(int) * iNumGpus);
m_iNumGpus = iNumGpus;
}
void CMultiGpuBase::mCreateStreams(int iStreamsPerGpu)
{
if(m_iNumGpus <= 0) return;
m_iStreamsPerGpu = iStreamsPerGpu;
//--------------------------------
m_pStreams = new cudaStream_t[m_iStreamsPerGpu * m_iNumGpus];
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
int iStart = m_iStreamsPerGpu * i;
for(int j=0; j<m_iStreamsPerGpu; j++)
{ cudaStream_t stream = 0;
cudaStreamCreate(&stream);
m_pStreams[iStart+j] = stream;
}
}
}
void CMultiGpuBase::mDeleteStreams(void)
{
if(m_pStreams == 0L || m_piGpuIDs == 0L) return;
//----------------------------------------------
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
int iStart = m_iStreamsPerGpu * i;
for(int j=0; j<m_iStreamsPerGpu; j++)
{ int iStream = iStart + j;
cudaStreamSynchronize(m_pStreams[iStream]);
cudaStreamDestroy(m_pStreams[iStream]);
}
}
//-----------------------------------------------------
delete[] m_pStreams;
m_pStreams = 0L;
}
void CMultiGpuBase::mCreateForwardFFTs(int* piSize, bool bPad)
{
if(m_iNumGpus <= 0) return;
//-------------------------
m_pForwardFFTs = new CCufft2D[m_iNumGpus];
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
m_pForwardFFTs[i].CreateForwardPlan(piSize, bPad);
}
}
void CMultiGpuBase::mDeleteForwardFFTs(void)
{
if(m_pForwardFFTs == 0L) return;
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
m_pForwardFFTs[i].DestroyPlan();
}
delete[] m_pForwardFFTs;
m_pForwardFFTs = 0L;
}
void CMultiGpuBase::mCreateInverseFFTs(int* piSize, bool bCmp)
{
if(m_iNumGpus <= 0) return;
//-------------------------
m_pInverseFFTs = new CCufft2D[m_iNumGpus];
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
m_pInverseFFTs[i].CreateInversePlan(piSize, bCmp);
}
}
void CMultiGpuBase::mDeleteInverseFFTs(void)
{
if(m_pInverseFFTs == 0L) return;
for(int i=0; i<m_iNumGpus; i++)
{ cudaSetDevice(m_piGpuIDs[i]);
m_pInverseFFTs[i].DestroyPlan();
}
delete[] m_pInverseFFTs;
m_pInverseFFTs = 0L;
}
| 412 | 0.726417 | 1 | 0.726417 | game-dev | MEDIA | 0.487891 | game-dev | 0.648432 | 1 | 0.648432 |
libgdx/libgdx | 8,563 | extensions/gdx-bullet/jni/src/bullet/BulletCollision/CollisionShapes/btTriangleInfoMap.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2010 Erwin Coumans http://bulletphysics.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.
*/
#ifndef _BT_TRIANGLE_INFO_MAP_H
#define _BT_TRIANGLE_INFO_MAP_H
#include "LinearMath/btHashMap.h"
#include "LinearMath/btSerializer.h"
///for btTriangleInfo m_flags
#define TRI_INFO_V0V1_CONVEX 1
#define TRI_INFO_V1V2_CONVEX 2
#define TRI_INFO_V2V0_CONVEX 4
#define TRI_INFO_V0V1_SWAP_NORMALB 8
#define TRI_INFO_V1V2_SWAP_NORMALB 16
#define TRI_INFO_V2V0_SWAP_NORMALB 32
///The btTriangleInfo structure stores information to adjust collision normals to avoid collisions against internal edges
///it can be generated using
struct btTriangleInfo
{
btTriangleInfo()
{
m_edgeV0V1Angle = SIMD_2_PI;
m_edgeV1V2Angle = SIMD_2_PI;
m_edgeV2V0Angle = SIMD_2_PI;
m_flags=0;
}
int m_flags;
btScalar m_edgeV0V1Angle;
btScalar m_edgeV1V2Angle;
btScalar m_edgeV2V0Angle;
};
typedef btHashMap<btHashInt,btTriangleInfo> btInternalTriangleInfoMap;
///The btTriangleInfoMap stores edge angle information for some triangles. You can compute this information yourself or using btGenerateInternalEdgeInfo.
struct btTriangleInfoMap : public btInternalTriangleInfoMap
{
btScalar m_convexEpsilon;///used to determine if an edge or contact normal is convex, using the dot product
btScalar m_planarEpsilon; ///used to determine if a triangle edge is planar with zero angle
btScalar m_equalVertexThreshold; ///used to compute connectivity: if the distance between two vertices is smaller than m_equalVertexThreshold, they are considered to be 'shared'
btScalar m_edgeDistanceThreshold; ///used to determine edge contacts: if the closest distance between a contact point and an edge is smaller than this distance threshold it is considered to "hit the edge"
btScalar m_maxEdgeAngleThreshold; //ignore edges that connect triangles at an angle larger than this m_maxEdgeAngleThreshold
btScalar m_zeroAreaThreshold; ///used to determine if a triangle is degenerate (length squared of cross product of 2 triangle edges < threshold)
btTriangleInfoMap()
{
m_convexEpsilon = 0.00f;
m_planarEpsilon = 0.0001f;
m_equalVertexThreshold = btScalar(0.0001)*btScalar(0.0001);
m_edgeDistanceThreshold = btScalar(0.1);
m_zeroAreaThreshold = btScalar(0.0001)*btScalar(0.0001);
m_maxEdgeAngleThreshold = SIMD_2_PI;
}
virtual ~btTriangleInfoMap() {}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
void deSerialize(struct btTriangleInfoMapData& data);
};
///those fields have to be float and not btScalar for the serialization to work properly
struct btTriangleInfoData
{
int m_flags;
float m_edgeV0V1Angle;
float m_edgeV1V2Angle;
float m_edgeV2V0Angle;
};
struct btTriangleInfoMapData
{
int *m_hashTablePtr;
int *m_nextPtr;
btTriangleInfoData *m_valueArrayPtr;
int *m_keyArrayPtr;
float m_convexEpsilon;
float m_planarEpsilon;
float m_equalVertexThreshold;
float m_edgeDistanceThreshold;
float m_zeroAreaThreshold;
int m_nextSize;
int m_hashTableSize;
int m_numValues;
int m_numKeys;
char m_padding[4];
};
SIMD_FORCE_INLINE int btTriangleInfoMap::calculateSerializeBufferSize() const
{
return sizeof(btTriangleInfoMapData);
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE const char* btTriangleInfoMap::serialize(void* dataBuffer, btSerializer* serializer) const
{
btTriangleInfoMapData* tmapData = (btTriangleInfoMapData*) dataBuffer;
tmapData->m_convexEpsilon = (float)m_convexEpsilon;
tmapData->m_planarEpsilon = (float)m_planarEpsilon;
tmapData->m_equalVertexThreshold =(float) m_equalVertexThreshold;
tmapData->m_edgeDistanceThreshold = (float)m_edgeDistanceThreshold;
tmapData->m_zeroAreaThreshold = (float)m_zeroAreaThreshold;
tmapData->m_hashTableSize = m_hashTable.size();
tmapData->m_hashTablePtr = tmapData->m_hashTableSize ? (int*)serializer->getUniquePointer((void*)&m_hashTable[0]) : 0;
if (tmapData->m_hashTablePtr)
{
//serialize an int buffer
int sz = sizeof(int);
int numElem = tmapData->m_hashTableSize;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_hashTable[i];
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*)&m_hashTable[0]);
}
tmapData->m_nextSize = m_next.size();
tmapData->m_nextPtr = tmapData->m_nextSize? (int*)serializer->getUniquePointer((void*)&m_next[0]): 0;
if (tmapData->m_nextPtr)
{
int sz = sizeof(int);
int numElem = tmapData->m_nextSize;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_next[i];
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*)&m_next[0]);
}
tmapData->m_numValues = m_valueArray.size();
tmapData->m_valueArrayPtr = tmapData->m_numValues ? (btTriangleInfoData*)serializer->getUniquePointer((void*)&m_valueArray[0]): 0;
if (tmapData->m_valueArrayPtr)
{
int sz = sizeof(btTriangleInfoData);
int numElem = tmapData->m_numValues;
btChunk* chunk = serializer->allocate(sz,numElem);
btTriangleInfoData* memPtr = (btTriangleInfoData*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
memPtr->m_edgeV0V1Angle = (float)m_valueArray[i].m_edgeV0V1Angle;
memPtr->m_edgeV1V2Angle = (float)m_valueArray[i].m_edgeV1V2Angle;
memPtr->m_edgeV2V0Angle = (float)m_valueArray[i].m_edgeV2V0Angle;
memPtr->m_flags = m_valueArray[i].m_flags;
}
serializer->finalizeChunk(chunk,"btTriangleInfoData",BT_ARRAY_CODE,(void*) &m_valueArray[0]);
}
tmapData->m_numKeys = m_keyArray.size();
tmapData->m_keyArrayPtr = tmapData->m_numKeys ? (int*)serializer->getUniquePointer((void*)&m_keyArray[0]) : 0;
if (tmapData->m_keyArrayPtr)
{
int sz = sizeof(int);
int numElem = tmapData->m_numValues;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_keyArray[i].getUid1();
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*) &m_keyArray[0]);
}
// Fill padding with zeros to appease msan.
tmapData->m_padding[0] = 0;
tmapData->m_padding[1] = 0;
tmapData->m_padding[2] = 0;
tmapData->m_padding[3] = 0;
return "btTriangleInfoMapData";
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE void btTriangleInfoMap::deSerialize(btTriangleInfoMapData& tmapData )
{
m_convexEpsilon = tmapData.m_convexEpsilon;
m_planarEpsilon = tmapData.m_planarEpsilon;
m_equalVertexThreshold = tmapData.m_equalVertexThreshold;
m_edgeDistanceThreshold = tmapData.m_edgeDistanceThreshold;
m_zeroAreaThreshold = tmapData.m_zeroAreaThreshold;
m_hashTable.resize(tmapData.m_hashTableSize);
int i =0;
for (i=0;i<tmapData.m_hashTableSize;i++)
{
m_hashTable[i] = tmapData.m_hashTablePtr[i];
}
m_next.resize(tmapData.m_nextSize);
for (i=0;i<tmapData.m_nextSize;i++)
{
m_next[i] = tmapData.m_nextPtr[i];
}
m_valueArray.resize(tmapData.m_numValues);
for (i=0;i<tmapData.m_numValues;i++)
{
m_valueArray[i].m_edgeV0V1Angle = tmapData.m_valueArrayPtr[i].m_edgeV0V1Angle;
m_valueArray[i].m_edgeV1V2Angle = tmapData.m_valueArrayPtr[i].m_edgeV1V2Angle;
m_valueArray[i].m_edgeV2V0Angle = tmapData.m_valueArrayPtr[i].m_edgeV2V0Angle;
m_valueArray[i].m_flags = tmapData.m_valueArrayPtr[i].m_flags;
}
m_keyArray.resize(tmapData.m_numKeys,btHashInt(0));
for (i=0;i<tmapData.m_numKeys;i++)
{
m_keyArray[i].setUid1(tmapData.m_keyArrayPtr[i]);
}
}
#endif //_BT_TRIANGLE_INFO_MAP_H
| 412 | 0.94455 | 1 | 0.94455 | game-dev | MEDIA | 0.751697 | game-dev | 0.948436 | 1 | 0.948436 |
TwelveIterationMods/Waystones | 2,444 | common/src/main/java/net/blay09/mods/waystones/item/BlankScrollItem.java | package net.blay09.mods.waystones.item;
import net.blay09.mods.waystones.api.WaystonesAPI;
import net.blay09.mods.waystones.block.entity.WaystoneBlockEntityBase;
import net.blay09.mods.waystones.component.BlankScrollComponent;
import net.blay09.mods.waystones.component.ModComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.TooltipDisplay;
import net.minecraft.world.item.context.UseOnContext;
import java.util.function.Consumer;
public class BlankScrollItem extends Item {
public BlankScrollItem(Properties properties) {
super(properties.stacksTo(64).component(ModComponents.blankScroll.get(), BlankScrollComponent.INSTANCE));
}
@Override
public InteractionResult useOn(UseOnContext context) {
if (!context.getLevel().isClientSide()) {
final var blockEntity = context.getLevel().getBlockEntity(context.getClickedPos());
if (blockEntity instanceof WaystoneBlockEntityBase waystoneBlockEntityBase) {
final var waystone = waystoneBlockEntityBase.getWaystone();
final var boundScrollStack = new ItemStack(ModItems.boundScroll);
WaystonesAPI.setBoundWaystone(boundScrollStack, waystone);
final var player = context.getPlayer();
int emptySlot = player.getInventory().getFreeSlot();
int stackableSlot = player.getInventory().getSlotWithRemainingSpace(boundScrollStack);
if ((emptySlot != -1 || stackableSlot != -1) || (!player.hasInfiniteMaterials() && context.getItemInHand().getCount() == 1)) {
context.getItemInHand().consume(1, player);
if (!player.addItem(boundScrollStack)) {
player.drop(boundScrollStack, false);
}
return InteractionResult.SUCCESS;
}
return InteractionResult.FAIL;
}
}
return super.useOn(context);
}
@Override
public void appendHoverText(ItemStack itemStack, TooltipContext context, TooltipDisplay display, Consumer<Component> list, TooltipFlag flag) {
itemStack.addToTooltip(ModComponents.blankScroll.get(), context, display, list, flag);
}
}
| 412 | 0.893929 | 1 | 0.893929 | game-dev | MEDIA | 0.997991 | game-dev | 0.96675 | 1 | 0.96675 |
magefree/mage | 1,978 | Mage.Sets/src/mage/cards/c/ColossalSkyturtle.java | package mage.cards.c;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect;
import mage.abilities.effects.common.ReturnToHandTargetEffect;
import mage.abilities.keyword.ChannelAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.WardAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.target.common.TargetCardInYourGraveyard;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class ColossalSkyturtle extends CardImpl {
public ColossalSkyturtle(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT, CardType.CREATURE}, "{4}{G}{G}{U}");
this.subtype.add(SubType.TURTLE);
this.power = new MageInt(6);
this.toughness = new MageInt(5);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Ward {2}
this.addAbility(new WardAbility(new ManaCostsImpl<>("{2}"), false));
// Channel — {2}{G}, Discard Colossal Skyturtle: Return target card from your graveyard to your hand.
Ability ability = new ChannelAbility("{2}{G}", new ReturnFromGraveyardToHandTargetEffect());
ability.addTarget(new TargetCardInYourGraveyard());
this.addAbility(ability);
// Channel — {1}{U}, Discard Colossal Skyturtle: Return target creature to its owner's hand.
ability = new ChannelAbility("{1}{U}", new ReturnToHandTargetEffect());
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
}
private ColossalSkyturtle(final ColossalSkyturtle card) {
super(card);
}
@Override
public ColossalSkyturtle copy() {
return new ColossalSkyturtle(this);
}
}
| 412 | 0.901955 | 1 | 0.901955 | game-dev | MEDIA | 0.955627 | game-dev | 0.988579 | 1 | 0.988579 |
jswigart/omni-bot | 30,296 | Installer/Files/et/nav/uje_oasis_xmas.gm | global Map =
{
//set this to true if you want axis to try and dynamite water pump2
//after old city wall is destroyed.
DestroyWaterPumpAfterWall = false,
DispenseAmmoTime = 15,
Ammo_Cabinet_cabinet_ammo = "AMMOCAB_cabinet_ammo",
Health_Cabinet_cabinet_health = "HEALTHCAB_cabinet_health",
Call_Artillery_Flag_13 = "CALLARTILLERY_Flag_13",
Artillery_D_894 = "ARTILLERY_D_894",
Checkpoint_oldcityflag = "CHECKPOINT_oldcityflag",
Build_Allied_Command_Post = "BUILD_Allied_Command_Post",
Build_Axis_Command_Post = "BUILD_Axis_Command_Post",
Build_Axis_Command_Post_1 = "BUILD_Axis_Command_Post_1",
Build_Garrison_MG_Nest = "BUILD_Garrison_MG_Nest",
Build_Oasis_Water_Pump = "BUILD_Oasis_Water_Pump",
Build_Old_City_MG_Nest = "BUILD_Old_City_MG_Nest",
Build_Old_City_Water_Pump = "BUILD_Old_City_Water_Pump",
Plant_Allied_Command_Post = "PLANT_Allied_Command_Post",
Plant_Axis_Command_Post = "PLANT_Axis_Command_Post",
Plant_Axis_Command_Post_1 = "PLANT_Axis_Command_Post_1",
Plant_Garrison_MG_Nest = "PLANT_Garrison_MG_Nest",
Plant_North_Anti_Tank_Gun = "PLANT_North_Anti_Tank_Gun",
Plant_Oasis_Water_Pump = "PLANT_Oasis_Water_Pump",
Plant_Old_City_MG_Nest = "PLANT_Old_City_MG_Nest",
Plant_Old_City_Wall = "PLANT_Old_City_Wall",
Plant_Old_City_Water_Pump = "PLANT_Old_City_Water_Pump",
Plant_South_Anti_Tank_Gun = "PLANT_South_Anti_Tank_Gun",
Mount_Garrison_MG_Nest = "MOUNTMG42_Garrison_MG_Nest",
Mount_Old_City_MG_Nest = "MOUNTMG42_Old_City_MG_Nest",
Repair_Garrison_MG_Nest = "REPAIRMG42_Garrison_MG_Nest",
Repair_Old_City_MG_Nest = "REPAIRMG42_Old_City_MG_Nest",
Mobile_MG42_p1axis_west_courtyard = "MOBILEMG42_p1axis_west_courtyard",
Mobile_MG42_p2axis_north_garrison_entrance_1 = "MOBILEMG42_p2axis_north_garrison_entrance_1",
Snipe_p1axis_behindflagroom = "SNIPE_p1axis_behindflagroom",
Snipe_p1axis_supplyroom = "SNIPE_p1axis_supplyroom",
Snipe_p1axis_valleyledge_1 = "SNIPE_p1axis_valleyledge_1",
Snipe_p1axis_valleyledge_2 = "SNIPE_p1axis_valleyledge_2",
Snipe_p2axis_garrison_barracks = "SNIPE_p2axis_garrison_barracks",
Snipe_p2axis_garrison_canopy = "SNIPE_p2axis_garrison_canopy",
Snipe_p2axis_garrison_southwest_corner = "SNIPE_p2axis_garrison_southwest_corner",
Snipe_p2axis_old_city_oasis = "SNIPE_p2axis_old_city_oasis",
Plant_Mine_p1axis_courtyard_middle = "PLANTMINE_p1axis_courtyard_middle",
Plant_Mine_p1axis_west_of_flagroom = "PLANTMINE_p1axis_west_of_flagroom",
//dyno counters
NorthDyno = 0,
SouthDyno = 0,
WallDyno = 0,
FlagStatus = 0, //no team owns it initially
NorthGunStatus = 0, //intact
SouthGunStatus = 0,
WallStatus = true, //intact
// aggressive defenders will be split into north and south 'teams'
// this will keep them from wandering across the map
Roles =
{
AXIS =
{
DEFENDER1 =
{
numbots = 2,
},
DEFENDER2 =
{
numbots = 2,
},
},
},
// path through for axis throwing a/s over the wall when attempting to reclaim
Airstrike =
{
wall =
{
Enabled = true,
Team = (1<<TEAM.AXIS),
Facing = Vector3(-0.601,-0.392,0.696),
NoPause = true,
},
},
Navigation =
{
quickjump =
{
navigate = function(_this)
{
_this.Bot.PressButton(BTN.JUMP);
sleep(0.25);
},
},
},
Allied_Command_Post_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Allied_Command_Post_Built" );
},
Allied_Command_Post_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Allied_Command_Post_Destroyed" );
},
Axis_Command_Post_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Axis_Command_Post_Built" );
},
Axis_Command_Post_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Axis_Command_Post_Destroyed" );
},
Garrison_MG_Nest_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Garrison_MG_Nest_Built" );
},
Garrison_MG_Nest_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Garrison_MG_Nest_Destroyed" );
},
Old_City_MG_Nest_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Old_City_MG_Nest_Built" );
},
Old_City_MG_Nest_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Old_City_MG_Nest_Destroyed" );
},
Oasis_Water_Pump_Built = function( trigger )
{
if ( TestMap )
{ return; }
SetAvailableMapGoals( TEAM.AXIS, true, "MOBILEMG42_p1axis_west_courtyard" );
SetAvailableMapGoals( TEAM.AXIS, false, "MOBILEMORTAR_waterpump" );
Util.MapDebugPrint( "Oasis_Water_Pump_Built" );
},
Oasis_Water_Pump_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Oasis_Water_Pump_Destroyed" );
},
Old_City_Water_Pump_Built = function( trigger )
{
if ( TestMap )
{ return; }
if ( Map.WallStatus || Map.DestroyWaterPumpAfterWall )
{
SetAvailableMapGoals( TEAM.AXIS, true, Map.Plant_Old_City_Water_Pump );
}
Util.MapDebugPrint( "Old_City_Water_Pump_Built" );
},
Old_City_Water_Pump_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Old_City_Water_Pump );
Util.MapDebugPrint( "Old_City_Water_Pump_Destroyed" );
},
North_Anti_Tank_Gun_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Map.NorthGunStatus = 1;
//don't worry about additional dynos at this point
Map.NorthDyno = 0;
//focus on south defense
SetAvailableMapGoals( TEAM.AXIS, false, "DEFUSE_North_Anti_Tank_Gun.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_North_Gun.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_north_clear.*" );
//hmm might consider staying conservative after one is destroyed
if ( Map.SouthDyno < 1 )
{
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_gun_flex.*" );
}
Util.MapDebugPrint( "North_Anti_Tank_Gun_Destroyed" );
},
North_Plant = function ( trigger )
{
if ( TestMap )
{ return; }
Map.NorthDyno += 1;
//shift defense to support defuse
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_gun_flex.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_north_clear.*" );
Util.MapDebugPrint( "North_Plant" );
},
North_Defuse = function ( trigger )
{
if ( TestMap )
{ return; }
Map.NorthDyno -= 1;
if ( Map.NorthDyno < 1 )
{
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_north_clear.*" );
if ( Map.SouthDyno < 1 ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_gun_flex.*" );
}
}
Util.MapDebugPrint( "North_Defuse" );
},
South_Anti_Tank_Gun_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Map.SouthGunStatus = 1;
//don't worry about additional dynos at this point
Map.SouthDyno = 0;
//focus on north defense
SetAvailableMapGoals( TEAM.AXIS, false, "DEFUSE_South_Anti_Tank_Gun.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_South_Gun.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_south_clear.*" );
if ( Map.NorthDyno < 1 )
{
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_gun_flex.*" );
}
Util.MapDebugPrint( "South_Anti_Tank_Gun_Destroyed" );
},
South_Plant = function ( trigger )
{
if ( TestMap )
{ return; }
Map.SouthDyno += 1;
//shift defense to support defuse
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_gun_flex.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_south_clear.*" );
Util.MapDebugPrint( "South_Plant" );
},
South_Defuse = function ( trigger )
{
if ( TestMap )
{ return; }
Map.SouthDyno -= 1;
if ( Map.SouthDyno < 1 )
{
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_south_clear.*" );
if ( Map.NorthDyno < 1 ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_gun_flex.*" );
}
}
Util.MapDebugPrint( "South_Defuse" );
},
Old_City_Wall_Destroyed = function( trigger )
{
// this region trigger isn't needed anymore
DeleteTriggerRegion("snuckpast");
// and kill the thread watching players that snuck through
if ( Map.WatchPlayerThreadId ) {
threadKill(Map.WatchPlayerThreadId);
}
if ( TestMap )
{ return; }
Map.DispenseAmmoTime = 5;
Map.FlagStatus = 0;
Map.WallDyno = 0;
Map.WallStatus = false;
// Axis goals
SetAvailableMapGoals( TEAM.AXIS, true, "REPAIRMG42_Garrison_MG_Nest" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOUNTMG42_Garrison_MG_Nest" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_South_Gun_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_North_Gun_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_middle_patrol.*" );
SetAvailableMapGoals( TEAM.AXIS, true, ".*_p2axis_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOBILEMG42_rGuns.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "SNIPE_p2axis_garrison_canopy" );
SetAvailableMapGoals( TEAM.AXIS, true, Map.Build_Garrison_MG_Nest );
SetAvailableMapGoals( TEAM.AXIS, true, Map.Build_Axis_Command_Post );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_gun_flex.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_rGuns.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "CALLARTILLERY_rTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "CALLARTILLERY_rSouthEntrance.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ARTILLERY_S_rTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ARTILLERY_S_rSouthEntrance.*" );
// all classes now
SetGoalPriority( "DEFEND_north_clear.*", 0.92 );
SetGoalPriority( "DEFEND_south_clear.*", 0.92 );
// and turn em off if no dyno
if ( Map.NorthDyno < 1 ) {
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_north_clear.*" );
}
if ( Map.SouthDyno < 1 ) {
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_south_clear.*" );
}
// disable the pathrough airstrike at the wall
Map.Airstrike.wall.Enabled = false;
SetAvailableMapGoals( TEAM.AXIS, false, ".*_p1axis_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Ammo_Cabinet_cabinet_ammo );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Health_Cabinet_cabinet_health );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Oasis_Water_Pump );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Old_City_MG_Nest );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Allied_Command_Post );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFUSE_Old_City_Wall.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_Flag_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "CALLARTILLERY_rFirstTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "ARTILLERY_S_rFirstTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "MOBILEMORTAR_waterpump" );
SetAvailableMapGoals( TEAM.AXIS, false, "PLANTMINE_rFlag.*" );
// this one can be enabled sooner
SetAvailableMapGoals( TEAM.ALLIES, true, "MOBILEMORTAR_bGuns.*" );
//optionally keep the waterpump2 dynamite action. problem is, meds will
//leave defensive spots to go revive engineers as they inevitably get killed
//because its so close to allied spawn
if ( !Map.DestroyWaterPumpAfterWall )
{
SetAvailableMapGoals( TEAM.AXIS, false, Map.Plant_Old_City_Water_Pump );
}
// cs: delay it long enough for the blockable status
// this prevents a ton of failed paths for allies
sleep(2.1);
// Allied goals
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_Guns_.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "SMOKEBOMB_bGuns.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_North_Anti_Tank_Gun );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_South_Anti_Tank_Gun );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_Garrison_MG_Nest );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_Axis_Command_Post );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Mount_Old_City_MG_Nest );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Repair_Old_City_MG_Nest );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Health_Cabinet_cabinet_health );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Ammo_Cabinet_cabinet_ammo );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Plant_Old_City_Wall );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_Wall_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Build_Oasis_Water_Pump );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Build_Old_City_MG_Nest );
//SetAvailableMapGoals( TEAM.ALLIES, false, Map.Build_Allied_Command_Post );
SetAvailableMapGoals( TEAM.ALLIES, false, "AIRSTRIKE_bWall.*" );
Util.MapDebugPrint( "Old_City_Wall_Destroyed" );
},
Wall_Plant = function ( trigger )
{
if ( TestMap )
{ return; }
Map.WallDyno += 1;
Util.MapDebugPrint( "Wall Plant" );
},
Wall_Defuse = function ( trigger )
{
if ( TestMap )
{ return; }
Map.WallDyno -= 1;
Util.MapDebugPrint( "Wall Defuse" );
},
oldcityflag_Axis_Captured = function( trigger )
{
if ( TestMap )
{ return; }
Map.FlagStatus = 1;
SetGoalPriority( Map.Plant_Old_City_Wall, 0.91, TEAM.ALLIES, CLASS.ENGINEER );
// Allied goals
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_Wall_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Ammo_Cabinet_cabinet_ammo );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.Health_Cabinet_cabinet_health );
SetAvailableMapGoals( TEAM.ALLIES, false, "AIRSTRIKE_bWall.*" );
// Axis goals
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_Flag_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, ".*_p1axis_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "CALLARTILLERY_rFirstTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ARTILLERY_S_rFirstTunnel.*" );
Util.MapDebugPrint( "oldcityflag_Axis_Captured" );
},
oldcityflag_Allies_Captured = function( trigger )
{
if ( TestMap )
{ return; }
Map.FlagStatus = 2;
SetGoalPriority( Map.Plant_Old_City_Wall, 0.95, TEAM.ALLIES, CLASS.ENGINEER );
// Allied goals
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_Wall_.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Ammo_Cabinet_cabinet_ammo );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Health_Cabinet_cabinet_health );
SetAvailableMapGoals( TEAM.ALLIES, true, "AIRSTRIKE_bWall.*" );
// Axis goals
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_Flag_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, ".*_p1axis_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "CALLARTILLERY_rFirstTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "ARTILLERY_S_rFirstTunnel.*" );
Util.MapDebugPrint( "oldcityflag_Allies_Captured" );
},
WatchPlayerLimbo = function()
{
while(Map.WatchPlayer && !GetEntFlags(Map.WatchPlayer, ENTFLAG.LIMBO)) {
sleep(0.5);
}
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_north_clear.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_south_clear.*" );
Util.MapDebugPrint( "Sneaky player died" );
},
SnuckPast =
{
Name = "snuckpast",
TriggerOnClass = CLASS.ENGINEER,
OnEnter = function(ent)
{
if ( TestMap ) { return; }
team = GetEntTeam(ent);
if ( team != TEAM.ALLIES ) { return; }
// spawn the engineers back (only do this once)
if ( !Map.SpawnedBack ) {
ETUtil.SuicideSpawn( TEAM.AXIS, 1, -1, CLASS.ENGINEER );
Map.SpawnedBack = true;
}
// have the engineers defend the guns
ETUtil.LimitToClass( "DEFEND_north_clear.*", CLASS.ENGINEER );
ETUtil.LimitToClass( "DEFEND_south_clear.*", CLASS.ENGINEER );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_north_clear.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_south_clear.*" );
// and do it until the sneaky player dies
Map.WatchPlayer = ent;
if ( Map.WatchPlayerThreadId ) {
threadKill(Map.WatchPlayerThreadId);
}
Map.WatchPlayerThreadId = thread(Map.WatchPlayerLimbo);
},
OnExit = function(ent)
{
},
},
};
global OnMapLoad = function()
{
Util.SetGoalPosition( 9661.875, 3858.125, -199.875, "PLANT_South_Anti_Tank_Gun" );
Util.SetGoalPosition( 9646.170, 4780.875, -199.875, "PLANT_North_Anti_Tank_Gun" );
Util.SetGoalPosition( 4576.686, 6586.125, -468.781, "PLANT_Old_City_Water_Pump" );
if ( TestMapOn )
{ Util.AutoTestMap(); }
OnTrigger( "Allied Command Post constructed. Charge speed increased!", Map.Allied_Command_Post_Built );
OnTrigger( "Axis Command Post constructed. Charge speed increased!", Map.Axis_Command_Post_Built );
OnTrigger( "The Garrison MG Nest has been constructed!", Map.Garrison_MG_Nest_Built );
OnTrigger( "Allies have built the Oasis Water Pump!", Map.Oasis_Water_Pump_Built );
OnTrigger( "The Old City MG Nest has been constructed!", Map.Old_City_MG_Nest_Built );
OnTrigger( "Allies have built the Old City Water Pump!", Map.Old_City_Water_Pump_Built );
OnTrigger( "Axis team has destroyed the Allied Command Post!", Map.Allied_Command_Post_Destroyed );
OnTrigger( "Allied team has destroyed the Axis Command Post!", Map.Axis_Command_Post_Destroyed );
OnTrigger( "The Garrison MG Nest has been damaged!", Map.Garrison_MG_Nest_Destroyed );
OnTrigger( "Allies have destroyed the North Anti-Tank Gun!", Map.North_Anti_Tank_Gun_Destroyed );
OnTrigger( "Axis have damaged the Oasis Water Pump!", Map.Oasis_Water_Pump_Destroyed );
OnTrigger( "The Old City MG Nest has been damaged!", Map.Old_City_MG_Nest_Destroyed );
OnTrigger( "Allies have breached the Old City wall", Map.Old_City_Wall_Destroyed );
OnTrigger( "Axis have damaged the Old City Water Pump!", Map.Old_City_Water_Pump_Destroyed );
OnTrigger( "Allied team has destroyed the South Anti-Tank Gun!", Map.South_Anti_Tank_Gun_Destroyed );
OnTrigger( "Axis reclaim the Old City!", Map.oldcityflag_Axis_Captured );
OnTrigger( "Allies capture the Old City!", Map.oldcityflag_Allies_Captured );
OnTrigger( "Planted at the North Anti-Tank Gun.", Map.North_Plant );
OnTrigger( "Planted at the South Anti-Tank Gun.", Map.South_Plant );
OnTrigger( "Defused at the North Anti-Tank Gun.", Map.North_Defuse );
OnTrigger( "Defused at the South Anti-Tank Gun.", Map.South_Defuse );
OnTrigger( "Planted at the Old City Wall.", Map.Wall_Plant );
OnTrigger( "Defused at the Old City Wall.", Map.Wall_Defuse );
// detect engineers getting through when wall is still intact
wTunnel2 = OnTriggerRegion(AABB(5731.727,4805.139,-869.945,5983.292,4945.652,-771.262),Map.SnuckPast);
wall = OnTriggerRegion(AABB(5536.597,6820.100,-565.253,5700.429,7872.364,-367.812),Map.SnuckPast);
SetMapGoalProperties( "ATTACK_.*", {MinCampTime=15, MaxCampTime=30});
SetMapGoalProperties( "DEFEND_.*", {MinCampTime=10, MaxCampTime=15});
SetMapGoalProperties( "MOUNTMG42_.*", {MinCampTime=45, MaxCampTime=90});
SetMapGoalProperties( "MOBILEMG42_.*", {MinCampTime=30, MaxCampTime=60});
SetMapGoalProperties( "SNIPE_.*", {MinCampTime=120, MaxCampTime=120});
SetMapGoalProperties( "DEFEND_north_clear.*", {MinCampTime=30, MaxCampTime=35});
SetMapGoalProperties( "DEFEND_south_clear.*", {MinCampTime=30, MaxCampTime=35});
SetMapGoalProperties( "DEFEND_middle_patrol.*", {MinCampTime=1, MaxCampTime=2});
SetGoalPriority( "MOUNTMG42_.*", 0.0, 0, CLASS.MEDIC );
SetGoalPriority( "MOUNTMG42_.*", 0.0, 0, CLASS.ENGINEER );
// don't backtrack to defuse these unless camping
SetGoalPriority( "DEFUSE_Oasis_Water_Pump.*", 0.7, TEAM.ALLIES, CLASS.ENGINEER, true );
SetGoalPriority( "DEFUSE_Allied_Command_Post.*", 0.7, TEAM.ALLIES, CLASS.ENGINEER, true );
// Max users per goal
Util.SetMaxUsersInProgress( 15, Map.Checkpoint_oldcityflag );
Util.SetMaxUsers( 1, "ATTACK_.*" );
Util.SetMaxUsers( 1, "DEFEND_.*" );
Util.SetMaxUsers( 1, "MOUNTMG42_.*" );
Util.SetMaxUsers( 1, "REPAIR_.*" );
Util.SetMaxUsers( 1, "CALLARTILLERY_.*" );
Util.SetMaxUsers( 1, "AIRSTRIKE_.*" );
Util.SetMaxUsers( 1, "MOBILEMG42_.*" );
Util.SetMaxUsersInProgress( 5, "DEFEND_north_clear.*" );
Util.SetMaxUsersInUse( 1, "DEFEND_north_clear.*" );
Util.SetMaxUsersInProgress( 5, "DEFEND_south_clear.*" );
Util.SetMaxUsersInUse( 1, "DEFEND_south_clear.*" );
// Allied goals
SetGoalPriority( Map.Build_Oasis_Water_Pump, 0.94, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Build_Allied_Command_Post, 0.93, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Checkpoint_oldcityflag, 0.92, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Old_City_Wall, 0.91, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Build_Old_City_Water_Pump, 0.90, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Build_Old_City_MG_Nest, 0.89, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_North_Anti_Tank_Gun, 0.81, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_South_Anti_Tank_Gun, 0.81, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Garrison_MG_Nest, 0.0, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Axis_Command_Post, 0.0, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Garrison_MG_Nest, 0.81, TEAM.ALLIES, CLASS.COVERTOPS );
// Axis goals
SetGoalPriority( "PLANTMINE_rFlag.*", 0.91, TEAM.AXIS, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Old_City_Water_Pump, 0.83, TEAM.AXIS, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Oasis_Water_Pump, 0.83, TEAM.AXIS, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Old_City_MG_Nest, 0.0, TEAM.AXIS, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Allied_Command_Post, 0.0, TEAM.AXIS, CLASS.ENGINEER );
SetGoalPriority( Map.Plant_Old_City_MG_Nest, 0.82, TEAM.AXIS, CLASS.COVERTOPS );
SetGoalPriority( Map.Plant_Allied_Command_Post, 0.81, TEAM.AXIS, CLASS.COVERTOPS );
SetGoalPriority( "DEFEND_north_clear.*", 0.92 );
SetGoalPriority( "DEFEND_south_clear.*", 0.92 );
SetGoalPriority( "DEFEND_middle_patrol.*", 0.49 );
SetGoalPriority( "DEFEND_middle_patrol5", 0.55 ); // peak out the back for campers
Util.DisableGoal( ".*", true ); // all but routes
SetAvailableMapGoals( TEAM.ALLIES, true, "REPAIRMG42_Old_City_MG_Nest" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Oasis_Water_Pump" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Old_City_Wall" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Garrison_MG_Nest" );
SetAvailableMapGoals( TEAM.ALLIES, true, "MOUNTMG42_Old_City_MG_Nest" );
SetAvailableMapGoals( TEAM.ALLIES, true, "CHECKPOINT_oldcityflag" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Build_Old_City_Water_Pump );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Build_Allied_Command_Post );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Build_Old_City_MG_Nest );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANTMINE_rFlag.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "AMMOCAB_cabinet_ammo" );
SetAvailableMapGoals( TEAM.AXIS, true, "HEALTHCAB_cabinet_health" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Allied_Command_Post" );
//SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Oasis_Water_Pump" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Old_City_MG_Nest" );
SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Old_City_Water_Pump" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_p1axis_valleyledge_2" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_p1axis_behindflagroom" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_p1axis_supplyroom" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_p1axis_valleyledge_1" );
SetAvailableMapGoals( TEAM.AXIS, true, "CHECKPOINT_oldcityflag" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_Flag_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOBILEMORTAR_waterpump" );
SetAvailableMapGoals( TEAM.AXIS, true, "CALLARTILLERY_rFirstTunnel.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "ARTILLERY_S_rFirstTunnel.*" );
// Routing
MapRoutes =
{
// Alternate Routes
CHECKPOINT_oldcityflag =
{
ROUTE_allyspawn =
{
ROUTE_frontdoor_l = {},
ROUTE_frontdoor_r = {},
ROUTE_leftdoor =
{
Weight = 2,
ROUTE_toproute_a =
{
ROUTE_toproute_b = {},
ROUTE_toproute_c = {},
},
ROUTE_ruins_l =
{
ROUTE_ruins_stairs =
{
ROUTE_flag_l = {},
ROUTE_flag_t = {},
},
},
},
ROUTE_tunnel1 =
{
Weight = 2,
ROUTE_tunnel2 = {},
},
},
ROUTE_cp =
{
ROUTE_ruins_l =
{
ROUTE_ruins_stairs =
{
ROUTE_flag_l = {},
ROUTE_flag_t = {},
},
},
},
ROUTE_leftdoor =
{
Weight = 2,
ROUTE_toproute_a =
{
ROUTE_toproute_b = {},
ROUTE_toproute_c = {},
},
ROUTE_ruins_l =
{
ROUTE_ruins_stairs =
{
ROUTE_flag_l = {},
ROUTE_flag_t = {},
},
},
},
ROUTE_AxisSpawn1 =
{
ROUTE_overwall =
{
ROUTE_walltop = {},
ROUTE_wallfar = {},
},
ROUTE_walldoor = {},
},
ROUTE_AxisSpawn2 =
{
ROUTE_overwall =
{
ROUTE_walltop = {},
ROUTE_wallfar = {},
},
ROUTE_walldoor = {},
},
},
DEFEND_Flag_3 =
{
ROUTE_AxisSpawn1 =
{
ROUTE_overwall =
{
ROUTE_walltop = {},
ROUTE_wallfar = {},
},
ROUTE_walldoor = {},
},
ROUTE_AxisSpawn2 =
{
ROUTE_overwall =
{
ROUTE_walltop = {},
ROUTE_wallfar = {},
},
ROUTE_walldoor = {},
},
},
PLANT_North_Anti_Tank_Gun =
{
ROUTE_FlagSpawn =
{
ROUTE_oc_tunnel =
{
Weight = 3,
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
ROUTE_upper_connection =
{
ROUTE_northentrance1 =
{
ROUTE_cp_split =
{
ROUTE_cp_route = {},
ROUTE_halls = {},
},
},
ROUTE_northentrance2 = {},
ROUTE_ne_corner = { ROUTE_eastentrance = {}, },
ROUTE_westside =
{
ROUTE_sw_corner =
{
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
},
},
ROUTE_lower_connection =
{
ROUTE_northentrance1 =
{
ROUTE_cp_split =
{
ROUTE_cp_route = {},
ROUTE_halls = {},
},
},
ROUTE_northentrance2 = {},
ROUTE_ne_corner = { ROUTE_eastentrance = {}, },
ROUTE_westside =
{
ROUTE_sw_corner =
{
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
},
},
},
},
PLANT_South_Anti_Tank_Gun =
{
ROUTE_FlagSpawn =
{
ROUTE_oc_tunnel =
{
Weight = 3,
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
ROUTE_upper_connection =
{
ROUTE_northentrance1 =
{
ROUTE_cp_split =
{
ROUTE_halls =
{
ROUTE_uppersouth = {},
},
},
ROUTE_lowermg1 = { ROUTE_lowermg2 = {}, },
},
ROUTE_northentrance2 = {},
ROUTE_ne_corner = { ROUTE_eastentrance = {}, },
ROUTE_westside =
{
ROUTE_sw_corner =
{
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
},
},
ROUTE_lower_connection =
{
ROUTE_northentrance1 =
{
ROUTE_cp_split =
{
ROUTE_halls =
{
ROUTE_uppersouth = {},
},
},
ROUTE_lowermg1 = { ROUTE_lowermg2 = {}, },
},
ROUTE_northentrance2 = {},
ROUTE_ne_corner = { ROUTE_eastentrance = {}, },
ROUTE_westside =
{
ROUTE_sw_corner =
{
ROUTE_southentrance = {},
ROUTE_se_corner = { ROUTE_eastentrance = {}, },
},
},
},
},
},
PLANT_Oasis_Water_Pump =
{
ROUTE_FlagSpawn =
{ ROUTE_tunnel2 = { ROUTE_tunnel1 = {}, }, },
},
DEFEND_gun_flex_4 =
{
ROUTE_AxisSpawn1 =
{
ROUTE_gunpatrol2 = { ROUTE_northentrance2 = {}, },
},
ROUTE_AxisSpawn2 =
{
ROUTE_gunpatrol2 = { ROUTE_northentrance2 = {}, },
},
},
//most of the time they should check gun area before taking tunnel to the pump
PLANT_Old_City_Water_Pump =
{
ROUTE_AxisSpawn1 =
{
ROUTE_oc_tunnel = {},
ROUTE_gunpatrol = { ROUTE_oc_tunnel = {}, },
ROUTE_gunpatrol2 =
{
ROUTE_gunpatrol = { ROUTE_oc_tunnel = {}, },
},
},
ROUTE_AxisSpawn2 =
{
ROUTE_oc_tunnel = {},
ROUTE_gunpatrol = { ROUTE_oc_tunnel = {}, },
ROUTE_gunpatrol2 =
{
ROUTE_gunpatrol = { ROUTE_oc_tunnel = {}, },
},
},
},
MOBILEMG42_rGuns1 =
{
// send them this way so they don't have their back to enemy when heading to them
ROUTE_AxisSpawn1 =
{
ROUTE_nTruck = {},
},
ROUTE_AxisSpawn2 =
{
ROUTE_nTruck = {},
},
},
SMOKEBOMB_bGuns_south =
{
ROUTE_FlagSpawn =
{
ROUTE_oc_tunnel =
{
ROUTE_southentrance = {},
},
},
},
SMOKEBOMB_bGuns_north =
{
ROUTE_FlagSpawn =
{
ROUTE_upper_connection = {},
ROUTE_lower_connection = {},
},
},
};
//copy some routes
MapRoutes.DEFEND_Flag_4 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_5 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_6 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_7 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_8 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_9 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_10 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_11 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_12 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_13 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_14 = MapRoutes.DEFEND_Flag_3;
MapRoutes.DEFEND_Flag_15 = MapRoutes.DEFEND_Flag_3;
MapRoutes.PLANT_Garrison_MG_Nest = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.PLANT_Axis_Command_Post = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_1 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_2 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_3 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_4 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_5 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_6 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_7 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_8 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_9 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.ATTACK_Guns_10 = MapRoutes.PLANT_North_Anti_Tank_Gun;
MapRoutes.DEFEND_gun_flex_5 = MapRoutes.DEFEND_gun_flex_4;
MapRoutes.DEFEND_gun_flex_6 = MapRoutes.DEFEND_gun_flex_4;
MapRoutes.MOBILEMG42_rGuns2 = MapRoutes.MOBILEMG42_rGuns1;
Util.Routes(MapRoutes);
Util.MapDebugPrint( "OnMapLoad" );
};
global OnBotJoin = function( bot )
{
//default spawn
bot.ChangeSpawnPoint( 0 );
};
| 412 | 0.873759 | 1 | 0.873759 | game-dev | MEDIA | 0.984004 | game-dev | 0.827667 | 1 | 0.827667 |
RevereInc/alley-practice | 1,381 | src/main/java/dev/revere/alley/feature/party/menu/event/impl/PartyEventSplitMenu.java | package dev.revere.alley.feature.party.menu.event.impl;
import dev.revere.alley.AlleyPlugin;
import dev.revere.alley.library.menu.Button;
import dev.revere.alley.library.menu.Menu;
import dev.revere.alley.feature.queue.QueueService;
import dev.revere.alley.feature.queue.Queue;
import dev.revere.alley.feature.party.menu.event.impl.button.PartyEventSplitButton;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
/**
* @author Emmy
* @project Alley
* @date 08/10/2024 - 18:38
*/
public class PartyEventSplitMenu extends Menu {
protected final AlleyPlugin plugin = AlleyPlugin.getInstance();
@Override
public String getTitle(Player player) {
return "&6&lSelect a kit";
}
@Override
public Map<Integer, Button> getButtons(Player player) {
final Map<Integer, Button> buttons = new HashMap<>();
int slot = 10;
for (Queue queue : AlleyPlugin.getInstance().getService(QueueService.class).getQueues()) {
if (!queue.isRanked() && !queue.isDuos() && queue.getKit().isEnabled()) {
slot = this.skipIfSlotCrossingBorder(slot);
buttons.put(slot++, new PartyEventSplitButton(queue.getKit()));
}
}
this.addGlass(buttons, 15);
return buttons;
}
@Override
public int getSize() {
return 9 * 6;
}
} | 412 | 0.539634 | 1 | 0.539634 | game-dev | MEDIA | 0.821631 | game-dev | 0.831868 | 1 | 0.831868 |
gammu/gammu | 88,083 | libgammu/phone/nokia/nfunc.c | /* (c) 2002-2005 by Marcin Wiacek */
/* based on some work from Ralf Thelen, Gabriele Zappi and MyGnokii */
#include <string.h> /* memcpy only */
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <gammu-nokia.h>
#include "../../gsmstate.h"
#include "../../gsmphones.h"
#include "../../misc/coding/coding.h"
#include "../../misc/locales.h"
#include "../../service/gsmnet.h"
#include "../../service/gsmlogo.h"
#include "../../service/gsmcal.h"
#include "../pfunc.h"
#include "nfunc.h"
unsigned char N71_65_MEMORY_TYPES[] = {
MEM_DC, 0x01,
MEM_MC, 0x02,
MEM_RC, 0x03,
MEM_ME, 0x05,
MEM_SM, 0x06,
MEM_VM, 0x09,
MEM7110_SP, 0x0e,
MEM7110_CG, 0x10,
MEM_ON, 0x17,
MEM6510_CG2, 0x23,
MEM_SL, 0x27,
0x00, 0x00
};
size_t N71_65_PackPBKBlock(GSM_StateMachine *s, int id, size_t size, int no, unsigned char *buf, unsigned char *block)
{
smprintf(s, "Packing phonebook block with ID = %i, block number = %i, block length = %ld\n",
id,
no+1,
(long)size+6);
block[0] = id;
block[1] = 0;
block[2] = (size + 6) / 256;
block[3] = (size + 6) % 256;
block[4] = no + 1;
memcpy(block+5, buf, size);
block[5+size] = 0;
return (size + 6);
}
size_t N71_65_EncodePhonebookFrame(GSM_StateMachine *s, unsigned char *req, GSM_MemoryEntry *entry, size_t *block2, gboolean DCT4, gboolean VoiceTag)
{
int count=0, len, i, block=0, j;
unsigned char string[500];
unsigned char type;
gboolean found;
for (i = 0; i < entry->EntriesNum; i++) {
entry->Entries[i].AddError = ERR_NOTSUPPORTED;
}
memset(string,0,sizeof(string));
found = FALSE;
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_SERIES40_30)) {
for (i = 0; i < entry->EntriesNum; i++) {
if (entry->Entries[i].EntryType == PBK_Text_LastName ||
entry->Entries[i].EntryType == PBK_Text_FirstName) {
if (entry->Entries[i].EntryType==PBK_Text_LastName) {
type = S4030_PBK_LASTNAME;
} else {
type = S4030_PBK_FIRSTNAME;
}
found = TRUE;
entry->Entries[i].AddError = ERR_NONE;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[0] = len*2+2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
}
}
for (i = 0; i < entry->EntriesNum; i++) {
if(entry->Entries[i].EntryType==PBK_Text_Name) {
if (!found) {
entry->Entries[i].AddError = ERR_NONE;
type = N7110_PBK_NAME;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[0] = len*2+2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
found = TRUE;
} else {
entry->Entries[i].AddError = ERR_INVALIDDATA;
}
}
}
} else {
for (i = 0; i < entry->EntriesNum; i++) {
if (entry->Entries[i].EntryType == PBK_Text_LastName ||
entry->Entries[i].EntryType == PBK_Text_FirstName) {
if (UnicodeLength(string+1) > 0) {
string[UnicodeLength(string+1)*2+1] = ' ';
}
CopyUnicodeString(string+UnicodeLength(string+1)*2+1,entry->Entries[i].Text);
entry->Entries[i].AddError = ERR_DATACONVERTED;
found=TRUE;
}
}
if (UnicodeLength(string+1) != 0) {
type = N7110_PBK_NAME;
len = MIN(UnicodeLength(string+1), 126);
string[0] = len*2+2;
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
}
for (i = 0; i < entry->EntriesNum; i++) {
if (entry->Entries[i].EntryType==PBK_Text_Name) {
if (!found) {
entry->Entries[i].AddError = ERR_NONE;
type = N7110_PBK_NAME;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[0] = len*2+2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
found = TRUE;
} else {
entry->Entries[i].AddError = ERR_INVALIDDATA;
}
}
}
}
for (i = 0; i < entry->EntriesNum; i++) {
type = 0;
if (entry->Entries[i].EntryType == PBK_Number_General && entry->Entries[i].Location == PBK_Location_Work) type = N7110_PBK_NUMBER_WORK;
else if (entry->Entries[i].EntryType == PBK_Number_General && entry->Entries[i].Location == PBK_Location_Home) type = N7110_PBK_NUMBER_HOME;
else if (entry->Entries[i].EntryType == PBK_Number_General) type = N7110_PBK_NUMBER_GENERAL;
if (entry->Entries[i].EntryType == PBK_Number_Mobile) type = N7110_PBK_NUMBER_MOBILE;
if (entry->Entries[i].EntryType == PBK_Number_Fax) type = N7110_PBK_NUMBER_FAX;
if (type != 0) {
entry->Entries[i].AddError = ERR_NONE;
string[0] = type;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[1] = 0;
string[2] = 0;
/* DCT 3 */
if (!DCT4) string[2] = entry->Entries[i].VoiceTag;
string[3] = 0;
string[4] = len*2+2;
CopyUnicodeString(string+5,entry->Entries[i].Text);
string[len * 2 + 5] = 0;
count += N71_65_PackPBKBlock(s, N7110_PBK_NUMBER, len*2+6, block++, string, req+count);
/* DCT 4 */
if (DCT4 && VoiceTag) {
block++;
req[count++] = N6510_PBK_VOICETAG_ID;
req[count++] = 0;
req[count++] = 0;
req[count++] = 8;
req[count++] = 0x00;
req[count++] = i+1;
req[count++] = 0x00;
req[count++] = entry->Entries[i].VoiceTag;
}
if (DCT4) {
j = 0;
while (entry->Entries[i].SMSList[j] != 0) {
string[0] = i+1;
string[1] = 0x00;
string[2] = 0x02;
string[3] = 0x00;
string[4] = entry->Entries[i].SMSList[j];
string[5] = 0x00;
count += N71_65_PackPBKBlock(s, N6510_PBK_SMSLIST_ID, 6, block++, string, req+count);
j++;
}
}
continue;
}
smprintf(s, "entry num %i %i\n",i,entry->EntriesNum);
if (entry->Entries[i].EntryType == PBK_Text_Note) type = N7110_PBK_NOTE;
if (entry->Entries[i].EntryType == PBK_Text_Postal) {
if (!GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBKNOPOSTAL)) {
continue;
}
type = N7110_PBK_POSTAL;
}
if (entry->Entries[i].EntryType == PBK_Text_Email) type = N7110_PBK_EMAIL;
if (entry->Entries[i].EntryType == PBK_Text_Email2) type = N7110_PBK_EMAIL;
if (entry->Entries[i].EntryType == PBK_Text_URL) {
entry->Entries[i].AddError = ERR_DATACONVERTED;
type = N7110_PBK_NOTE;
if (DCT4) type = N6510_PBK_URL;
}
if (type != 0) {
if (entry->Entries[i].AddError==ERR_NOTSUPPORTED) entry->Entries[i].AddError = ERR_NONE;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[0] = len*2+2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
continue;
}
if (entry->Entries[i].EntryType == PBK_Caller_Group) {
if (!GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBK35)) {
entry->Entries[i].AddError = ERR_NONE;
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_6230iCALLER)) {
string[0] = 0;
string[1] = 0;
count += N71_65_PackPBKBlock(s, N6510_PBK_GROUP2_ID, 2, block++, string, req + count);
req[count-1] = entry->Entries[i].Number;
} else {
string[0] = entry->Entries[i].Number;
string[1] = 0;
count += N71_65_PackPBKBlock(s, N7110_PBK_GROUP, 2, block++, string, req + count);
}
}
continue;
}
if (entry->Entries[i].EntryType == PBK_RingtoneID) {
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBK35)) {
entry->Entries[i].AddError = ERR_NONE;
string[0] = 0x00;
string[1] = 0x00;
string[2] = entry->Entries[i].Number;
count += N71_65_PackPBKBlock(s, N7110_PBK_RINGTONE_ID, 3, block++, string, req + count);
count --;
req[count-5] = 8;
}
continue;
}
if (entry->Entries[i].EntryType == PBK_PictureID) {
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBKIMG)) {
entry->Entries[i].AddError = ERR_NONE;
string[0] = 0x00;
string[1] = 0x00;
string[2] = 0x00;
string[3] = 0x00;
string[4] = 0x01;
string[5] = entry->Entries[i].Number / 256;
string[6] = entry->Entries[i].Number % 256;
string[7] = 0x00;
string[8] = 0x00;
string[9] = 0x00;
count += N71_65_PackPBKBlock(s, N6510_PBK_PICTURE_ID, 10, block++, string, req + count);
req[count-1] = 0x01;
}
continue;
}
/* Maybe we should use separate feature for these new entries... */
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_SERIES40_30)) {
type = 0;
if (entry->Entries[i].EntryType == PBK_Text_FormalName) type = S4030_PBK_FORMALNAME;
if (entry->Entries[i].EntryType == PBK_Text_JobTitle) type = S4030_PBK_JOBTITLE;
if (entry->Entries[i].EntryType == PBK_Text_Company) type = S4030_PBK_COMPANY;
if (entry->Entries[i].EntryType == PBK_Text_NickName) type = S4030_PBK_NICKNAME;
if (type != 0) {
if (entry->Entries[i].AddError==ERR_NOTSUPPORTED) entry->Entries[i].AddError = ERR_NONE;
len = MIN(UnicodeLength(entry->Entries[i].Text), 126);
string[0] = len*2+2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
string[len*2+1] = 0;
count += N71_65_PackPBKBlock(s, type, len * 2 + 2, block++, string, req + count);
continue;
}
if (entry->Entries[i].EntryType == PBK_Date) {
entry->Entries[i].AddError = ERR_NONE;
NOKIA_EncodeDateTime(s, string + 1, &(entry->Entries[i].Date));
count += N71_65_PackPBKBlock(s, S4030_PBK_BIRTHDAY, 6, block++, string, req + count);
continue;
}
}
if (entry->Entries[i].EntryType == PBK_Text_UserID) {
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBKUSER)) {
entry->Entries[i].AddError = ERR_NONE;
string[0] = UnicodeLength(entry->Entries[i].Text)*2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
count += N71_65_PackPBKBlock(s, N6510_PBK_USER_ID, string[0]+2, block++, string, req+count);
req[count-1]--;
}
continue;
}
if (entry->Entries[i].EntryType == PBK_PushToTalkID) {
entry->Entries[i].AddError = ERR_NONE;
string[0] = UnicodeLength(entry->Entries[i].Text)*2;
CopyUnicodeString(string+1,entry->Entries[i].Text);
count += N71_65_PackPBKBlock(s, N6510_PBK_PUSHTOTALK_ID, string[0]+2, block++, string, req+count);
req[count-1]--;
continue;
}
if (entry->Entries[i].EntryType == PBK_Number_Messaging) {
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_PBKFAVORITEMESSAGE)) {
entry->Entries[i].AddError = ERR_INVALIDDATA;
/* The favorite messaging number is stored as a phone number,
* the phone wants an id to a previously supplied entry, so we search for that.
* In case there was an error in the previous entries, we stop.
* Otherwise we would point past the supplied entries. */
for (j = 0; j < i && entry->Entries[j].AddError == ERR_NONE; j++) {
if (mywstrncmp(entry->Entries[i].Text, entry->Entries[j].Text, -1)) {
string[0] = j + 1;
string[1] = 0x00;
string[2] = 0x00;
count += N71_65_PackPBKBlock(s, N2630_PBK_FAVMESSAGING, 3, block++, string, req + count);
count --;
req[count-5] = 8;
entry->Entries[i].AddError = ERR_NONE;
break;
}
}
}
continue;
}
}
*block2=block;
return count;
}
/**
* Copy string to GSM_MemoryEntry
*
* Return false on failure
*/
static gboolean N71_65_PB_CopyString(GSM_StateMachine *s,
GSM_MemoryEntry *entry,
const unsigned char *src,
unsigned char length)
{
if ((length & 1) != 0) {
smprintf(s, "String length not even\n");
return FALSE;
}
if (length/2 > GSM_PHONEBOOK_TEXT_LENGTH) {
smprintf(s, "Too long text\n");
return FALSE;
}
memcpy(entry->Entries[entry->EntriesNum].Text, src, length);
/* Zero terminate the string */
entry->Entries[entry->EntriesNum].Text[length] = 0;
entry->Entries[entry->EntriesNum].Text[length + 1] = 0;
smprintf(s, " \"%s\"\n",DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
return TRUE;
}
/**
* Decodes nokia phonebook.
*
* \bug Type casting MemoryType to int is ugly.
*/
GSM_Error N71_65_DecodePhonebook(GSM_StateMachine *s,
GSM_MemoryEntry *entry,
GSM_Bitmap *bitmap,
GSM_SpeedDial *speed,
unsigned char *MessageBuffer,
int MessageLength,
gboolean DayMonthReverse)
{
unsigned char *Block;
int length = 0, i, bs = 0;
GSM_EntryType Type;
GSM_EntryLocation Location = PBK_Location_Unknown;
gboolean found=FALSE;
gboolean foundbb5add=FALSE;
gboolean missed_call = FALSE;
int favorite_messaging_numbers[10];
size_t used_favorite_messaging_numbers = 0;
entry->EntriesNum = 0;
if ((int)entry->MemoryType==MEM7110_CG) {
bitmap->Text[0] = 0x00;
bitmap->Text[1] = 0x00;
bitmap->DefaultBitmap = TRUE;
bitmap->DefaultRingtone = TRUE;
bitmap->FileSystemPicture = FALSE;
}
if ((int)entry->MemoryType==MEM6510_CG2 && GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_6230iCALLER)) {
bitmap->DefaultName = FALSE;
bitmap->DefaultBitmap = TRUE;
bitmap->DefaultRingtone = TRUE;
bitmap->FileSystemPicture = FALSE;
}
Block = &MessageBuffer[0];
while (TRUE) {
entry->Entries[entry->EntriesNum].AddError = ERR_NONE;
entry->Entries[entry->EntriesNum].SMSList[0] = 0;
entry->Entries[entry->EntriesNum].VoiceTag = 0;
if (bs != 0) {
length = length + bs;
/* bb5 */
if (length >= MessageLength-1) break;
Block = &Block[bs];
}
bs = 256*Block[2]+Block[3];
if (bs == 0) break;
#ifdef DEBUG
smprintf(s, "Phonebook entry block 0x%02x - length %i\n",
Block[0], bs-6);
if (GSM_GetDI(s)->dl == DL_TEXTALL || GSM_GetDI(s)->dl == DL_TEXTALLDATE)
DumpMessage(&s->di, Block+0, bs-1);
#endif
if (entry->EntriesNum==GSM_PHONEBOOK_ENTRIES) {
smprintf(s, "Too many entries\n");
return ERR_UNKNOWNRESPONSE;
}
Type = 0;
if (Block[0] == S4030_PBK_FIRSTNAME) {
Type = PBK_Text_FirstName; smprintf(s,"First name ");
}
if (Block[0] == S4030_PBK_LASTNAME) {
Type = PBK_Text_LastName; smprintf(s,"Last name ");
}
if (Type != 0) {
found=TRUE;
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
}
}
Block = &MessageBuffer[0];
bs=0;
length=0;
while (TRUE) {
entry->Entries[entry->EntriesNum].AddError = ERR_NONE;
entry->Entries[entry->EntriesNum].SMSList[0] = 0;
entry->Entries[entry->EntriesNum].VoiceTag = 0;
if (bs != 0) {
length = length + bs;
if (length >= MessageLength-1) break;
Block = &Block[bs];
}
bs = 256*Block[2]+Block[3];
smprintf(s, "Phonebook entry block 0x%02x - length %i\n",
Block[0], bs-6);
if (s->di.dl == DL_TEXTALL || s->di.dl == DL_TEXTALLDATE) {
DumpMessage(&s->di, Block+0, bs-1);
}
if (entry->EntriesNum >= GSM_PHONEBOOK_ENTRIES) {
smprintf(s, "Too many entries\n");
return ERR_MOREMEMORY;
}
Type = 0;
if (Block[0] == N7110_PBK_NAME) {
if (found) continue;
Type = PBK_Text_Name; smprintf(s,"Name ");
}
if (Block[0] == S4030_PBK_FIRSTNAME) continue;
if (Block[0] == S4030_PBK_LASTNAME) continue;
if (Block[0] == N7110_PBK_EMAIL) {
Type = PBK_Text_Email; smprintf(s,"Email ");
}
if (Block[0] == N7110_PBK_POSTAL) {
Type = PBK_Text_Postal; smprintf(s,"Postal ");
}
if (Block[0] == N7110_PBK_NOTE) {
Type = PBK_Text_Note; smprintf(s,"Text note ");
}
if (Block[0] == N6510_PBK_URL) {
Type = PBK_Text_URL; smprintf(s,"URL ");
}
if (Block[0] == N6510_PBK_USER_ID) {
Type = PBK_Text_UserID; smprintf(s,"User ID:");
}
if (Type != 0) {
if (Block[5]/2>GSM_PHONEBOOK_TEXT_LENGTH) {
smprintf(s, "Too long text\n");
return ERR_UNKNOWNRESPONSE;
}
/* No text? */
if (Block[5] < 2) {
entry->Entries[entry->EntriesNum].Text[0] = 0;
entry->Entries[entry->EntriesNum].Text[1] = 0;
} else {
memcpy(entry->Entries[entry->EntriesNum].Text,Block+6,Block[5]);
/* Zero terminate the string */
entry->Entries[entry->EntriesNum].Text[Block[5]] = 0;
entry->Entries[entry->EntriesNum].Text[Block[5] + 1] = 0;
}
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
smprintf(s, " \"%s\"\n",DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
if (Block[0] == N7110_PBK_NAME) {
if ((int)entry->MemoryType == MEM7110_CG || (int)entry->MemoryType == MEM6510_CG2) {
/* No text? */
if (Block[5] < 2) {
bitmap->Text[0] = 0;
bitmap->Text[1] = 0;
} else {
memcpy(bitmap->Text,Block+6,Block[5]);
}
}
}
entry->EntriesNum ++;
continue;
}
if (Block[0] == N7110_PBK_DATETIME) {
entry->Entries[entry->EntriesNum].EntryType=PBK_Date;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
NOKIA_DecodeDateTime(s, Block+6, &entry->Entries[entry->EntriesNum].Date, TRUE, DayMonthReverse);
if (CheckDate(&entry->Entries[entry->EntriesNum].Date) &&
CheckDate(&entry->Entries[entry->EntriesNum].Date)) {
entry->EntriesNum ++;
} else {
smprintf(s, "Datetime seems to be invalid, ignoring!\n");
}
continue;
}
if (Block[0] == N6510_PBK_PICTURE_ID) {
if ((int)entry->MemoryType==MEM6510_CG2) {
bitmap->FileSystemPicture = TRUE;
smprintf(s, "Picture ID \"%i\"\n",Block[10]*256+Block[11]);
bitmap->PictureID = Block[10]*256+Block[11];
} else {
entry->Entries[entry->EntriesNum].EntryType=PBK_PictureID;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
smprintf(s, "Picture ID \"%i\"\n",Block[10]*256+Block[11]);
entry->Entries[entry->EntriesNum].Number=Block[10]*256+Block[11];
entry->EntriesNum ++;
}
continue;
}
if (Block[0] == N7110_PBK_NUMBER) {
if (Block[5] == 0x00) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
/* Not assigned dialed number */
if (Block[5] == 0x01) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
if (Block[5] == 0x0B) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
/* In many firmwares 0x55 visible after using
* Save from Call Register menu and saving number
* to existing phonebook entry */
if (Block[5] == 0x55) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
/* Yet another unknown General number */
if (Block[5] == 0x08) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
if (Block[5] == N7110_PBK_NUMBER_GENERAL) {
Type = PBK_Number_General; smprintf(s,"General number ");
}
if (Block[5] == N7110_PBK_NUMBER_WORK) {
Type = PBK_Number_General; Location = PBK_Location_Work; smprintf(s,"Work number ");
}
if (Block[5] == N7110_PBK_NUMBER_FAX) {
Type = PBK_Number_Fax; smprintf(s,"Fax number ");
}
if (Block[5] == N7110_PBK_NUMBER_MOBILE) {
Type = PBK_Number_Mobile; smprintf(s,"Mobile number ");
}
if (Block[5] == N7110_PBK_NUMBER_HOME) {
Type = PBK_Number_General; Location = PBK_Location_Home; smprintf(s,"Home number ");
}
if (Type == 0x00) {
smprintf(s, "Unknown number type %02x\n",Block[5]);
return ERR_UNKNOWNRESPONSE;
}
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = Location;
if (! N71_65_PB_CopyString(s, entry, Block+10, Block[9]))
return ERR_UNKNOWNRESPONSE;
/* DCT3 phones like 6210 */
entry->Entries[entry->EntriesNum].VoiceTag = Block[7];
#ifdef DEBUG
if (entry->Entries[entry->EntriesNum].VoiceTag != 0) smprintf(s, "Voice tag %i assigned\n",Block[7]);
#endif
entry->Entries[entry->EntriesNum].SMSList[0] = 0;
entry->EntriesNum ++;
continue;
}
/* to checking */
if (Block[0] == S4030_PBK_CALLLENGTH) {
entry->Entries[entry->EntriesNum].CallLength = Block[9]*256*256+Block[10]*256+Block[11];
entry->Entries[entry->EntriesNum].EntryType=PBK_CallLength;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_POSTAL) {
if (Block[5] == S4030_PBK_POSTAL_EXTADDRESS) {
Type = PBK_Text_Custom1; smprintf(s,"Address extension ? ");
}
if (Block[5] == S4030_PBK_POSTAL_STREET) {
Type = PBK_Text_StreetAddress; smprintf(s,"Street ");
}
if (Block[5] == S4030_PBK_POSTAL_CITY) {
Type = PBK_Text_City; smprintf(s,"City ");
}
if (Block[5] == S4030_PBK_POSTAL_STATE) {
Type = PBK_Text_State; smprintf(s,"State ");
}
if (Block[5] == S4030_PBK_POSTAL_POSTAL) {
Type = PBK_Text_Postal; smprintf(s,"Postal ");
}
if (Block[5] == S4030_PBK_POSTAL_COUNTRY) {
Type = PBK_Text_Country; smprintf(s,"Country ");
}
if ((Type == 0x00) && (Block[7]>0)) {
smprintf(s, "Found new bb5 style address\n");
foundbb5add=TRUE;
continue;
}
if (Type == 0x00) {
smprintf(s, "Unknown address type %02x\n",Block[5]);
return ERR_UNKNOWNRESPONSE;
}
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
if (! N71_65_PB_CopyString(s, entry, Block+10, Block[9]))
return ERR_UNKNOWNRESPONSE;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_EXTADDRESS) && (foundbb5add==TRUE)) {
Type = PBK_Text_Custom1; smprintf(s,"Address extension ? ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_STREET) && (foundbb5add==TRUE)) {
Type = PBK_Text_StreetAddress; smprintf(s,"Street ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_CITY) && (foundbb5add==TRUE)) {
Type = PBK_Text_City; smprintf(s,"City ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_STATE) && (foundbb5add==TRUE)) {
Type = PBK_Text_State; smprintf(s,"State ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_POSTAL) && (foundbb5add==TRUE)) {
Type = PBK_Text_Postal; smprintf(s,"Postal ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if ((Block[0] == S4030_PBK_POSTAL_COUNTRY) && (foundbb5add==TRUE)) {
Type = PBK_Text_Country; smprintf(s,"Country ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_FORMALNAME) {
Type = PBK_Text_FormalName; smprintf(s,"FormalName ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_JOBTITLE) {
Type = PBK_Text_JobTitle; smprintf(s,"JobTitle ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_COMPANY) {
Type = PBK_Text_Company; smprintf(s,"Company ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_NICKNAME) {
Type = PBK_Text_NickName; smprintf(s,"NickName ");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=Type;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == S4030_PBK_BIRTHDAY) {
entry->Entries[entry->EntriesNum].EntryType=PBK_Date;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
NOKIA_DecodeDateTime(s, Block+6, &entry->Entries[entry->EntriesNum].Date, FALSE, DayMonthReverse);
entry->EntriesNum ++;
continue;
}
if (Block[0] == N7110_PBK_RINGTONE_ID) {
if ((int)entry->MemoryType==MEM7110_CG) {
bitmap->RingtoneID=Block[5];
if (Block[5] == 0x00) bitmap->RingtoneID=Block[7];
smprintf(s, "Ringtone ID : %i\n",bitmap->RingtoneID);
bitmap->DefaultRingtone = FALSE;
bitmap->FileSystemRingtone = FALSE;
} else {
entry->Entries[entry->EntriesNum].EntryType=PBK_RingtoneID;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
smprintf(s, "Ringtone ID \"%i\"\n",Block[7]);
entry->Entries[entry->EntriesNum].Number=Block[7];
entry->EntriesNum ++;
}
continue;
}
if (Block[0] == N7110_PBK_LOGOON) {
if ((int)entry->MemoryType==MEM7110_CG) {
bitmap->BitmapEnabled=(Block[5]==0x00 ? FALSE : TRUE);
smprintf(s, "Logo : %s\n", bitmap->BitmapEnabled==TRUE ? "enabled":"disabled");
} else {
return ERR_UNKNOWNRESPONSE;
}
continue;
}
if (Block[0] == N7110_PBK_GROUPLOGO) {
if ((int)entry->MemoryType==MEM7110_CG) {
smprintf(s, "Caller logo\n");
PHONE_DecodeBitmap(GSM_NokiaCallerLogo, Block+10, bitmap);
bitmap->DefaultBitmap = FALSE;
} else {
return ERR_UNKNOWNRESPONSE;
}
continue;
}
if (Block[0] == N7110_PBK_GROUP) {
entry->Entries[entry->EntriesNum].EntryType=PBK_Caller_Group;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
smprintf(s, "Caller group \"%i\"\n",Block[5]);
entry->Entries[entry->EntriesNum].Number=Block[5];
if (Block[5]!=0) entry->EntriesNum ++;
continue;
}
if (Block[0] == N6510_PBK_VOICETAG_ID) {
smprintf(s, "Entry %i has voice tag %i\n",Block[5]-1,Block[7]);
entry->Entries[entry->EntriesNum].VoiceTag = Block[7];
continue;
}
/* 6210 5.56, SIM speed dials or ME with 1 number */
if (Block[0] == N7110_PBK_SIM_SPEEDDIAL) {
if ((int)entry->MemoryType==MEM7110_SP) {
#ifdef DEBUG
smprintf(s, "location %i\n",(Block[6]*256+Block[7]));
#endif
speed->MemoryType = MEM_ME;
if (Block[8] == 0x06) speed->MemoryType = MEM_SM;
speed->MemoryLocation = (Block[6]*256+Block[7]);
speed->MemoryNumberID = 2;
} else {
return ERR_UNKNOWNRESPONSE;
}
continue;
}
if (Block[0] == N7110_PBK_SPEEDDIAL) {
if ((int)entry->MemoryType==MEM7110_SP) {
#ifdef DEBUG
switch (Block[12]) {
case 0x05: smprintf(s, "ME\n"); break;
case 0x06: smprintf(s, "SM\n"); break;
default : smprintf(s, "%02x\n",Block[12]);
}
smprintf(s, "location %i, number %i in location\n",
(Block[6]*256+Block[7])-1,Block[14]);
#endif
switch (Block[12]) {
case 0x05: speed->MemoryType = MEM_ME; break;
case 0x06: speed->MemoryType = MEM_SM; break;
}
speed->MemoryLocation = (Block[6]*256+Block[7])-1;
speed->MemoryNumberID = Block[14];
} else {
return ERR_UNKNOWNRESPONSE;
}
continue;
}
if (Block[0] == N6510_PBK_RINGTONEFILE_ID) {
smprintf(s, "Ringtone ID with possibility of using filesystem\n");
if ((int)entry->MemoryType==MEM7110_CG) {
if (Block[9] == 0x01) {
smprintf(s, "Filesystem ringtone ID: %02x\n",Block[10]*256+Block[11]);
bitmap->FileSystemRingtone = TRUE;
} else {
smprintf(s, "Internal ringtone ID: %02x\n",Block[10]*256+Block[11]);
bitmap->FileSystemRingtone = FALSE;
}
bitmap->RingtoneID = Block[10]*256+Block[11];
bitmap->DefaultRingtone = FALSE;
} else if ((int)entry->MemoryType==MEM6510_CG2) {
/* FIXME */
smprintf(s, "Internal ringtone ID: %02x\n",Block[10]*256+Block[11]);
bitmap->FileSystemRingtone = FALSE;
bitmap->RingtoneID = Block[10]*256+Block[11];
bitmap->DefaultRingtone = FALSE;
} else {
/* series 40 3.0 */
smprintf(s, "Filesystem ringtone ID: %02x\n",Block[10]*256+Block[11]);
entry->Entries[entry->EntriesNum].EntryType=PBK_RingtoneID;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->Entries[entry->EntriesNum].Number=Block[10]*256+Block[11];
entry->EntriesNum ++;
}
continue;
}
if (Block[0] == N6510_PBK_SMSLIST_ID) {
smprintf(s, "Entry %i is assigned to SMS list %i\n",Block[5]-1,Block[9]);
i = 0;
while(entry->Entries[Block[5]-1].SMSList[i] != 0) i++;
entry->Entries[Block[5]-1].SMSList[i+1] = 0;
entry->Entries[Block[5]-1].SMSList[i] = Block[9];
continue;
}
if (Block[0] == N7110_PBK_MISSED) {
missed_call = TRUE;
smprintf(s,"Unknown entry type 0x%02x data length %d\n", Block[0], bs-6);
continue;
}
if (Block[0] == N7110_PBK_UNKNOWN2
|| Block[0] == N7110_PBK_UNKNOWN3
|| Block[0] == N3600_PBK_UNKNOWN1
|| Block[0] == N6303_PBK_UNKNOWN1
|| Block[0] == N6303_PBK_UNKNOWN2) {
smprintf(s,"Unknown entry type 0x%02x data length %d\n", Block[0], bs-6);
continue;
}
if (Block[0] == N6510_PBK_UNKNOWN2) {
smprintf(s,"Unknown entry - probably ID for conversation list\n");
continue;
}
if (Block[0] == N6510_PBK_UNKNOWN3) {
smprintf(s,"Unknown entry - probably ID for Instant Messaging service list\n");
continue;
}
if (Block[0] == N6510_PBK_UNKNOWN4) {
smprintf(s,"Unknown entry - probably ID for presence list\n");
continue;
}
if (Block[0] == N6510_PBK_PUSHTOTALK_ID) {
smprintf(s,"SIP Address (Push to Talk address)\n");
if (! N71_65_PB_CopyString(s, entry, Block+6, Block[5]))
return ERR_UNKNOWNRESPONSE;
entry->Entries[entry->EntriesNum].EntryType=PBK_PushToTalkID;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
entry->EntriesNum ++;
continue;
}
if (Block[0] == N6510_PBK_UNKNOWN5) {
smprintf(s,"Unknown entry\n");
continue;
}
if (Block[0] == N6510_PBK_GROUP2_ID) {
smprintf(s,"Group ID (6230i or later)\n");
entry->Entries[entry->EntriesNum].EntryType=PBK_Caller_Group;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
smprintf(s, "Caller group \"%i\"\n",Block[7]);
entry->Entries[entry->EntriesNum].Number=Block[7];
entry->EntriesNum ++;
continue;
}
if (Block[0] == N2630_PBK_FAVMESSAGING) {
if (used_favorite_messaging_numbers >= sizeof(favorite_messaging_numbers) / sizeof(int)) {
smprintf(s, "Too many favorite messaging numbers!\n");
return ERR_MOREMEMORY;
}
favorite_messaging_numbers[used_favorite_messaging_numbers] = (int)Block[5];
used_favorite_messaging_numbers++;
continue;
}
smprintf(s, "ERROR: unknown pbk entry 0x%02x\n",Block[0]);
return ERR_UNKNOWNRESPONSE;
}
if (entry->EntriesNum == 0) {
if (missed_call) {
smprintf(s, "Empty entry with missed call reference, adding blank number!\n");
entry->Entries[entry->EntriesNum].EntryType = PBK_Number_General;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
EncodeUnicode(entry->Entries[entry->EntriesNum].Text, "", 0);
} else {
return ERR_EMPTY;
}
}
/* Process favorite messaging numbers */
for (i = 0; i < (int)used_favorite_messaging_numbers; i++) {
if (entry->EntriesNum >= GSM_PHONEBOOK_ENTRIES) {
smprintf(s, "Too many entries\n");
return ERR_MOREMEMORY;
}
/* The phone sends an entry id. We store it as phone number because
* entry->Entries doesn't retain order. */
entry->Entries[entry->EntriesNum].EntryType = PBK_Number_Messaging;
entry->Entries[entry->EntriesNum].Location = PBK_Location_Unknown;
CopyUnicodeString(entry->Entries[entry->EntriesNum].Text,entry->Entries[favorite_messaging_numbers[i] - 1].Text);
smprintf(s,"Marked entry #%i (%s) as favorite messaging number\n",
favorite_messaging_numbers[i],
DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum ++;
}
return ERR_NONE;
}
void NOKIA_GetDefaultCallerGroupName(GSM_Bitmap *Bitmap)
{
Bitmap->DefaultName = FALSE;
if (Bitmap->Text[0]==0x00 && Bitmap->Text[1]==0x00) {
Bitmap->DefaultName = TRUE;
switch(Bitmap->Location) {
case 1: EncodeUnicode(Bitmap->Text,_("Family"),strlen(_("Family")));
break;
case 2: EncodeUnicode(Bitmap->Text,_("VIP"),strlen(_("VIP")));
break;
case 3: EncodeUnicode(Bitmap->Text,_("Friends"),strlen(_("Friends")));
break;
case 4: EncodeUnicode(Bitmap->Text,_("Colleagues"),strlen(_("Colleagues")));
break;
case 5: EncodeUnicode(Bitmap->Text,_("Other"),strlen(_("Other")));
break;
}
}
}
void NOKIA_DecodeDateTime(GSM_StateMachine *s, unsigned char* buffer, GSM_DateTime *datetime, gboolean seconds, gboolean DayMonthReverse)
{
datetime->Year = buffer[0] * 256 + buffer[1];
/* Sometimes reversed */
if (datetime->Year > 3000) {
datetime->Year = buffer[1] * 256 + buffer[0];
}
if (DayMonthReverse) {
datetime->Month = buffer[3];
datetime->Day = buffer[2];
} else {
datetime->Month = buffer[2];
datetime->Day = buffer[3];
}
datetime->Hour = buffer[4];
datetime->Minute = buffer[5];
if (seconds) {
datetime->Second = buffer[6];
} else {
datetime->Second = 0;
}
datetime->Timezone = 0;
smprintf(s, "Decoding date and time\n");
smprintf(s, " Time: %02d:%02d:%02d\n",
datetime->Hour, datetime->Minute, datetime->Second);
smprintf(s, " Date: %4d/%02d/%02d\n",
datetime->Year, datetime->Month, datetime->Day);
}
void NOKIA_EncodeDateTime(GSM_StateMachine *s UNUSED, unsigned char* buffer, GSM_DateTime *datetime)
{
buffer[0] = datetime->Year / 256;
buffer[1] = datetime->Year % 256;
buffer[2] = datetime->Month;
buffer[3] = datetime->Day;
buffer[4] = datetime->Hour;
buffer[5] = datetime->Minute;
}
#if defined(GSM_ENABLE_NOKIA_DCT3) || defined(GSM_ENABLE_NOKIA_DCT4)
/* --------------------- Some general Nokia functions ---------------------- */
void NOKIA_DecodeSMSState(GSM_StateMachine *s, unsigned char state, GSM_SMSMessage *sms)
{
switch (state) {
case 0x01 : sms->State = SMS_Read; break;
case 0x03 : sms->State = SMS_UnRead; break;
case 0x05 : sms->State = SMS_Sent; break;
case 0x07 : sms->State = SMS_UnSent; break;
default :
sms->State = SMS_Read;
smprintf(s, "Unknown SMS state: %02x\n",state);
break;
}
}
GSM_Error NOKIA_ReplyGetPhoneString(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
strcpy(s->Phone.Data.PhoneString, msg->Buffer+s->Phone.Data.StartPhoneString);
return ERR_NONE;
}
/* Some strings are very easy. Some header, after it required string and 0x00.
* We can get them using this function. We give frame to send (*string),
* type of message (type), pointer for buffer for response (*value), request
* type (request) and what is start byte in response for our string
*/
GSM_Error NOKIA_GetPhoneString(GSM_StateMachine *s, const unsigned char *msgframe, int msglen, unsigned char msgtype, char *retvalue, GSM_Phone_RequestID request, int startresponse)
{
retvalue[0] = 0;
s->Phone.Data.StartPhoneString = startresponse;
s->Phone.Data.PhoneString = retvalue;
return GSM_WaitFor (s, msgframe, msglen,msgtype, 4, request);
}
GSM_Error NOKIA_GetManufacturer(GSM_StateMachine *s)
{
strcpy(s->Phone.Data.Manufacturer,"Nokia");
return ERR_NONE;
}
/* Many functions contains such strings:
* (1. length/256) - exist or not
* 2. length%256
* 3. string (unicode, no termination)
* This function read string to output and increases counter
*/
void NOKIA_GetUnicodeString(GSM_StateMachine *s UNUSED, int *current, unsigned char *input, unsigned char *output, gboolean FullLength)
{
int length;
if (FullLength) {
length = (input[*current]*256+input[*current+1])*2;
memcpy(output,input+(*current+2),length);
*current = *current + 2 + length;
} else {
length = (input[*current])*2;
memcpy(output,input+(*current+1),length);
*current = *current + 1 + length;
}
output[length ] = 0;
output[length+1] = 0;
}
int NOKIA_SetUnicodeString(GSM_StateMachine *s UNUSED, unsigned char *dest, unsigned char *string, gboolean FullLength)
{
int length;
length = UnicodeLength(string);
if (FullLength) {
dest[0] = length / 256;
dest[1] = length % 256;
CopyUnicodeString(dest + 2, string);
return 2+length*2;
} else {
dest[0] = length % 256;
CopyUnicodeString(dest + 1, string);
return 1+length*2;
}
}
/* Returns correct ID for concrete memory type */
GSM_MemoryType NOKIA_GetMemoryType(GSM_StateMachine *s UNUSED, GSM_MemoryType memory_type, unsigned char *ID)
{
int i=0;
while (ID[i+1]!=0x00) {
if (ID[i]==memory_type) return ID[i+1];
i=i+2;
}
return 0xff;
}
void NOKIA_SortSMSFolderStatus(GSM_StateMachine *s, GSM_NOKIASMSFolder *Folder)
{
int i,j;
if (Folder->Number!=0) {
/* Bouble sorting */
i=0;
while (i!=Folder->Number-1) {
if (Folder->Location[i]>Folder->Location[i+1]) {
j=Folder->Location[i];
Folder->Location[i]=Folder->Location[i+1];
Folder->Location[i+1]=j;
i=0;
} else {
i++;
}
}
#ifdef DEBUG
smprintf(s, "Locations: ");
for (i=0;i<Folder->Number;i++) {
smprintf(s, "%i ",Folder->Location[i]);
}
smprintf(s, "\n");
#endif
}
}
void NOKIA_GetDefaultProfileName(GSM_Profile *Profile)
{
if (Profile->DefaultName) {
switch(Profile->Location) {
case 1: EncodeUnicode(Profile->Name,_("General"),strlen(_("General")));
break;
case 2: EncodeUnicode(Profile->Name,_("Silent"),strlen(_("Silent")));
break;
case 3: EncodeUnicode(Profile->Name,_("Meeting"),strlen(_("Meeting")));
break;
case 4: EncodeUnicode(Profile->Name,_("Outdoor"),strlen(_("Outdoor")));
break;
case 5: EncodeUnicode(Profile->Name,_("Pager"),strlen(_("Pager")));
break;
case 6: EncodeUnicode(Profile->Name,_("Car"),strlen(_("Car")));
break;
case 7: EncodeUnicode(Profile->Name,_("Headset"),strlen(_("Headset")));
break;
}
}
}
/* - Shared for DCT3 (n6110.c, n7110.c, n9110.c) and DCT4 (n6510.c) phones - */
GSM_Error DCT3DCT4_ReplyCallDivert(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
GSM_MultiCallDivert *cd = s->Phone.Data.Divert;
int i,pos = 11,j;
size_t number_pos;
GSM_Error error;
switch (msg->Buffer[3]) {
case 0x02:
smprintf(s,"Message: Call divert status received\n");
smprintf(s," Divert type: ");
switch (msg->Buffer[6]) {
case 0x43: smprintf(s,"when busy"); break;
case 0x3d: smprintf(s,"when not answered"); break;
case 0x3e: smprintf(s,"when phone off or no coverage"); break;
case 0x15: smprintf(s,"all types of diverts"); break;
default: smprintf(s,"unknown %i",msg->Buffer[6]); break;
}
if (cd == NULL) {
return ERR_NONE;
}
/* 6150 */
if (msg->Length == 0x0b) {
cd->EntriesNum = 0;
return ERR_NONE;
}
cd->EntriesNum = msg->Buffer[10];
for (i=0;i<cd->EntriesNum;i++) {
smprintf(s,"\n Calls type : ");
switch (msg->Buffer[pos]) {
case 0x0b:
smprintf(s,"voice");
cd->Entries[i].CallType = GSM_DIVERT_VoiceCalls;
break;
case 0x0d:
smprintf(s,"fax");
cd->Entries[i].CallType = GSM_DIVERT_FaxCalls;
break;
case 0x19:
smprintf(s,"data");
cd->Entries[i].CallType = GSM_DIVERT_DataCalls;
break;
default:
smprintf(s,"unknown %i",msg->Buffer[pos]);
/* 6310i */
cd->EntriesNum = 0;
return ERR_NONE;
}
smprintf(s,"\n");
j = pos + 2;
while (msg->Buffer[j] != 0x00) j++;
msg->Buffer[pos+1] = j - pos - 2;
number_pos = pos + 1;
error = GSM_UnpackSemiOctetNumber(&(s->di), cd->Entries[i].Number, msg->Buffer, &number_pos, msg->Length, FALSE);
if (error != ERR_NONE) {
return error;
}
smprintf(s," Number : %s\n",DecodeUnicodeString(cd->Entries[i].Number));
cd->Entries[i].Timeout = msg->Buffer[pos+34];
smprintf(s," Timeout : %i seconds\n",msg->Buffer[pos+34]);
pos+=35;
}
return ERR_NONE;
case 0x03:
smprintf(s,"Message: Call divert status receiving error ?\n");
return ERR_UNKNOWN;
}
return ERR_UNKNOWNRESPONSE;
}
static GSM_Error DCT3DCT4_CallDivert(GSM_StateMachine *s, GSM_CallDivert *request, GSM_MultiCallDivert *response, gboolean get)
{
int length = 0x09;
unsigned char req[55] = {N6110_FRAME_HEADER, 0x01,
0x05, /* operation = Query */
0x00,
0x00, /* divert type */
0x00, /* call type */
0x00};
if (!get) {
if (UnicodeLength(request->Number) == 0) {
req[4] = 0x04;
} else {
req[4] = 0x03;
req[8] = 0x01;
req[29] = GSM_PackSemiOctetNumber(request->Number, req + 9, FALSE);
req[52] = request->Timeout;
length = 55;
}
}
switch (request->DivertType) {
case GSM_DIVERT_AllTypes : req[6] = 0x15; break;
case GSM_DIVERT_Busy : req[6] = 0x43; break;
case GSM_DIVERT_NoAnswer : req[6] = 0x3d; break;
case GSM_DIVERT_OutOfReach: req[6] = 0x3e; break;
default : return ERR_NOTIMPLEMENTED;
}
switch (request->CallType) {
case GSM_DIVERT_AllCalls : break;
case GSM_DIVERT_VoiceCalls: req[7] = 0x0b; break;
case GSM_DIVERT_FaxCalls : req[7] = 0x0d; break;
case GSM_DIVERT_DataCalls : req[7] = 0x19; break;
default : return ERR_NOTIMPLEMENTED;
}
s->Phone.Data.Divert = response;
smprintf(s, "Call divert\n");
return GSM_WaitFor (s, req, length, 0x06, 10, ID_Divert);
}
GSM_Error DCT3DCT4_GetCallDivert(GSM_StateMachine *s, GSM_CallDivert *request, GSM_MultiCallDivert *response)
{
return DCT3DCT4_CallDivert(s, request, response, TRUE);
}
GSM_Error DCT3DCT4_SetCallDivert(GSM_StateMachine *s, GSM_CallDivert *divert)
{
return DCT3DCT4_CallDivert(s, divert, NULL, FALSE);
}
GSM_Error DCT3DCT4_CancelAllDiverts(GSM_StateMachine *s)
{
GSM_MultiCallDivert divert;
unsigned char req[55] = {N6110_FRAME_HEADER, 0x01,
0x04, /* operation = Disable */
0x00,
0x02, /* divert type */
0x00, /* call type */
0x00};
s->Phone.Data.Divert = &divert;
smprintf(s, "Call divert\n");
return GSM_WaitFor (s, req, 0x09, 0x06, 10, ID_Divert);
}
GSM_Error DCT3DCT4_ReplyGetActiveConnectSet(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
GSM_Phone_Data *Data = &s->Phone.Data;
Data->WAPSettings->Active = FALSE;
if (Data->WAPSettings->Location - 1 == msg->Buffer[4]) {
Data->WAPSettings->Active = TRUE;
}
return ERR_NONE;
}
GSM_Error DCT3DCT4_GetActiveConnectSet(GSM_StateMachine *s)
{
unsigned char GetSetreq[] = {N6110_FRAME_HEADER, 0x0F};
smprintf(s, "Checking, if connection settings are active\n");
return GSM_WaitFor (s, GetSetreq, 4, 0x3f, 4, ID_GetConnectSet);
}
GSM_Error DCT3DCT4_ReplySetActiveConnectSet(GSM_Protocol_Message *msg UNUSED, GSM_StateMachine *s)
{
smprintf(s, "Connection settings activated\n");
return ERR_NONE;
}
GSM_Error DCT3DCT4_SetActiveConnectSet(GSM_StateMachine *s, GSM_MultiWAPSettings *settings)
{
unsigned char reqActivate[] = {N6110_FRAME_HEADER, 0x12,
0x00}; /* Location */
if (settings->Active) {
reqActivate[4] = settings->Location-1;
smprintf(s, "Activating connection settings number %i\n",settings->Location);
return GSM_WaitFor (s, reqActivate, 5, 0x3f, 4, ID_SetConnectSet);
}
return ERR_NONE;
}
GSM_Error DCT3DCT4_SendDTMF(GSM_StateMachine *s, char *DTMFSequence)
{
unsigned char req[100] = {N6110_FRAME_HEADER, 0x50,
0x00}; /* Length */
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_NODTMF)) return ERR_NOTSUPPORTED;
if (strlen(DTMFSequence) > 100 - 5) return ERR_NOTSUPPORTED;
req[4] = strlen(DTMFSequence);
memcpy(req+5,DTMFSequence,strlen(DTMFSequence));
smprintf(s, "Sending DTMF\n");
return GSM_WaitFor (s, req, 5+strlen(DTMFSequence), 0x01, 4, ID_SendDTMF);
}
GSM_Error DCT3DCT4_ReplyGetWAPBookmark(GSM_Protocol_Message *msg, GSM_StateMachine *s, gboolean FullLength)
{
int tmp;
GSM_Phone_Data *Data = &s->Phone.Data;
smprintf(s, "WAP bookmark received\n");
switch (msg->Buffer[3]) {
case 0x07:
tmp = 4;
Data->WAPBookmark->Location = msg->Buffer[tmp] * 256 + msg->Buffer[tmp+1];
smprintf(s, "Location: %i\n",Data->WAPBookmark->Location);
tmp = tmp + 2;
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer, Data->WAPBookmark->Title, FullLength);
smprintf(s, "Title : \"%s\"\n",DecodeUnicodeString(Data->WAPBookmark->Title));
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer, Data->WAPBookmark->Address, FullLength);
smprintf(s, "Address : \"%s\"\n",DecodeUnicodeString(Data->WAPBookmark->Address));
return ERR_NONE;
case 0x08:
switch (msg->Buffer[4]) {
case 0x01:
smprintf(s, "Security error. Inside WAP bookmarks menu\n");
return ERR_INSIDEPHONEMENU;
case 0x02:
smprintf(s, "Invalid or empty\n");
return ERR_INVALIDLOCATION;
default:
smprintf(s, "ERROR: unknown %i\n",msg->Buffer[4]);
return ERR_UNKNOWNRESPONSE;
}
}
return ERR_UNKNOWNRESPONSE;
}
GSM_Error DCT3DCT4_ReplySetWAPBookmark(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
switch (msg->Buffer[3]) {
case 0x0A:
smprintf(s, "WAP bookmark set OK\n");
return ERR_NONE;
case 0x0B:
smprintf(s, "WAP bookmark setting error\n");
switch (msg->Buffer[4]) {
case 0x01:
smprintf(s, "Security error. Inside WAP bookmarks menu\n");
return ERR_INSIDEPHONEMENU;
case 0x02:
smprintf(s, "Can't write to empty location ?\n");
return ERR_EMPTY;
case 0x04:
smprintf(s, "Full memory\n");
return ERR_FULL;
default:
smprintf(s, "ERROR: unknown %i\n",msg->Buffer[4]);
return ERR_UNKNOWNRESPONSE;
}
}
return ERR_UNKNOWNRESPONSE;
}
GSM_Error DCT3DCT4_ReplyEnableConnectFunc(GSM_Protocol_Message *msg UNUSED, GSM_StateMachine *s)
{
smprintf(s, "Connection functions enabled\n");
return ERR_NONE;
}
GSM_Error DCT3DCT4_EnableWAPFunctions(GSM_StateMachine *s)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x00};
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo,F_NOWAP)) return ERR_NOTSUPPORTED;
smprintf(s, "Enabling WAP\n");
return GSM_WaitFor (s, req, 4, 0x3f, 4, ID_EnableConnectFunc);
}
GSM_Error DCT3DCT4_ReplyDisableConnectFunc(GSM_Protocol_Message *msg UNUSED, GSM_StateMachine *s)
{
smprintf(s, "Connection functions disabled\n");
return ERR_NONE;
}
GSM_Error DCT3DCT4_DisableConnectionFunctions(GSM_StateMachine *s)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x03};
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo,F_NOWAP)) return ERR_NOTSUPPORTED;
smprintf(s, "Disabling connection settings\n");
return GSM_WaitFor (s, req, 4, 0x3f, 4, ID_DisableConnectFunc);
}
GSM_Error DCT3DCT4_ReplyDelWAPBookmark(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
switch (msg->Buffer[3]) {
case 0x0D:
smprintf(s, "WAP bookmark deleted OK\n");
return ERR_NONE;
case 0x0E:
smprintf(s, "WAP bookmark deleting error\n");
switch (msg->Buffer[4]) {
case 0x01:
smprintf(s, "Security error. Inside WAP bookmarks menu\n");
return ERR_SECURITYERROR;
case 0x02:
smprintf(s, "Invalid location\n");
return ERR_INVALIDLOCATION;
default:
smprintf(s, "ERROR: unknown %i\n",msg->Buffer[4]);
return ERR_UNKNOWNRESPONSE;
}
}
return ERR_UNKNOWNRESPONSE;
}
GSM_Error DCT3DCT4_DeleteWAPBookmarkPart(GSM_StateMachine *s, GSM_WAPBookmark *bookmark)
{
GSM_Error error;
unsigned char req[] = {N6110_FRAME_HEADER, 0x0C,
0x00, 0x00}; /* Location */
req[5] = bookmark->Location;
smprintf(s, "Deleting WAP bookmark\n");
error = GSM_WaitFor (s, req, 6, 0x3f, 4, ID_DeleteWAPBookmark);
if (error != ERR_NONE) {
if (error == ERR_INVALIDLOCATION || error == ERR_INSIDEPHONEMENU) {
DCT3DCT4_DisableConnectionFunctions(s);
}
return error;
}
return DCT3DCT4_DisableConnectionFunctions(s);
}
GSM_Error DCT3DCT4_GetWAPBookmarkPart(GSM_StateMachine *s, GSM_WAPBookmark *bookmark)
{
GSM_Error error;
unsigned char req[] = {N6110_FRAME_HEADER, 0x06,
0x00, 0x00}; /* Location */
req[5]=bookmark->Location-1;
s->Phone.Data.WAPBookmark=bookmark;
smprintf(s, "Getting WAP bookmark\n");
error = GSM_WaitFor (s, req, 6, 0x3f, 4, ID_GetWAPBookmark);
if (error != ERR_NONE) {
if (error == ERR_INVALIDLOCATION || error == ERR_INSIDEPHONEMENU) {
DCT3DCT4_DisableConnectionFunctions(s);
}
return error;
}
return DCT3DCT4_DisableConnectionFunctions(s);
}
GSM_Error DCT3DCT4_CancelCall(GSM_StateMachine *s, int ID)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x08, 0x00, 0x85};
req[4] = (unsigned char)ID;
s->Phone.Data.CallID = ID;
smprintf(s, "Canceling single call\n");
return GSM_WaitFor (s, req, 6, 0x01, 4, ID_CancelCall);
}
GSM_Error DCT3DCT4_AnswerCall(GSM_StateMachine *s, int ID)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x06, 0x00, 0x00};
req[4] = (unsigned char)ID;
s->Phone.Data.CallID = ID;
smprintf(s, "Answering single call\n");
return GSM_WaitFor (s, req, 6, 0x01, 4, ID_AnswerCall);
}
GSM_Error DCT3DCT4_ReplyGetModelFirmware(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
GSM_CutLines lines;
GSM_Phone_Data *Data = &s->Phone.Data;
InitLines(&lines);
SplitLines(msg->Buffer, msg->Length, &lines, "\x20\x0A", 2, "", 0, FALSE);
strcpy(Data->Model,GetLineString(msg->Buffer, &lines, 4));
smprintf(s, "Received model %s\n",Data->Model);
Data->ModelInfo = GetModelData(s, NULL, Data->Model, NULL);
strcpy(Data->VerDate,GetLineString(msg->Buffer, &lines, 3));
smprintf(s, "Received firmware date %s\n",Data->VerDate);
strcpy(Data->Version,GetLineString(msg->Buffer, &lines, 2));
smprintf(s, "Received firmware version %s\n",Data->Version);
GSM_CreateFirmwareNumber(s);
FreeLines(&lines);
return ERR_NONE;
}
GSM_Error DCT3DCT4_GetModel (GSM_StateMachine *s)
{
unsigned char req[5] = {N6110_FRAME_HEADER, 0x03, 0x00};
GSM_Error error;
if (strlen(s->Phone.Data.Model)>0) return ERR_NONE;
smprintf(s, "Getting model\n");
error=GSM_WaitFor (s, req, 5, 0xd1, 3, ID_GetModel);
if (error == ERR_NONE) {
smprintf_level(s, D_TEXT, "[Connected model - \"%s\"]\n",
s->Phone.Data.Model);
smprintf_level(s, D_TEXT, "[Firmware version - \"%s\"]\n",
s->Phone.Data.Version);
smprintf_level(s, D_TEXT, "[Firmware date - \"%s\"]\n",
s->Phone.Data.VerDate);
}
return error;
}
GSM_Error DCT3DCT4_GetFirmware (GSM_StateMachine *s)
{
unsigned char req[5] = {N6110_FRAME_HEADER, 0x03, 0x00};
GSM_Error error;
if (strlen(s->Phone.Data.Version)>0) return ERR_NONE;
smprintf(s, "Getting firmware version\n");
error=GSM_WaitFor (s, req, 5, 0xd1, 3, ID_GetFirmware);
if (error == ERR_NONE) {
smprintf_level(s, D_TEXT, "[Connected model - \"%s\"]\n",
s->Phone.Data.Model);
smprintf_level(s, D_TEXT, "[Firmware version - \"%s\"]\n",
s->Phone.Data.Version);
smprintf_level(s, D_TEXT, "[Firmware date - \"%s\"]\n",
s->Phone.Data.VerDate);
}
return error;
}
/* ---------- Shared for n7110.c and n6510.c ------------------------------- */
GSM_Error N71_65_ReplyGetMemoryError(unsigned char error, GSM_StateMachine *s)
{
switch (error) {
case 0x21:
smprintf(s, "Wait for synchronisation???\n");
return ERR_WORKINPROGRESS;
case 0x24:
smprintf(s, "No own number???\n");
return ERR_NOTSUPPORTED;
case 0x27:
smprintf(s, "No PIN\n");
return ERR_SECURITYERROR;
case 0x30:
if (s->Phone.Data.Memory->MemoryType == MEM_ME ||
s->Phone.Data.Memory->MemoryType == MEM_SM) {
smprintf(s, "Empty entry\n");
return ERR_EMPTY;
}
smprintf(s, "Invalid memory type\n");
return ERR_NOTSUPPORTED;
case 0x31:
smprintf(s, "Invalid memory type?\n");
s->Phone.Data.Memory->EntriesNum = 0;
return ERR_EMPTY;
case 0x33:
smprintf(s, "Empty location\n");
s->Phone.Data.Memory->EntriesNum = 0;
return ERR_EMPTY;
case 0x34:
smprintf(s, "Too high location ?\n");
return ERR_INVALIDLOCATION;
case 0x3B: /* Tim Dreessen, 6230 */
smprintf(s, "Empty location\n");
s->Phone.Data.Memory->EntriesNum = 0;
/*
* This is really empty, but this entry is calculated to
* entries count, so we must return something.
*/
return ERR_NONE;
case 0x3d: /* Seen on RH-105 for own number */
smprintf(s, "Empty location\n");
s->Phone.Data.Memory->EntriesNum = 0;
return ERR_NONE;
default:
smprintf(s, "ERROR: unknown status code 0x%x\n", error);
return ERR_UNKNOWNRESPONSE;
}
}
GSM_Error N71_65_ReplyWritePhonebook(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
switch (msg->Buffer[6]) {
case 0x0f:
smprintf(s, "Phonebook entry writing failed\n");
switch (msg->Buffer[10]) {
case 0xf:
smprintf(s, "Invalid block sent\n");
return ERR_BUG;
case 0x21:
smprintf(s, "Still busy processing the last command\n");
return ERR_BUSY;
case 0x23:
smprintf(s, "Block size does not match a definition\n");
return ERR_BUG;
case 0x25:
smprintf(s, "when you try to save into entry with caller group assignment in phone with caller groups standard 2 (like in 6230i)\n");
return ERR_PERMISSION;
case 0x29:
smprintf(s, "no caller group with given number (6230i)\n");
return ERR_MEMORY;
case 0x32:
smprintf(s, "Ignoring ERROR: unknown 50 (probably group contains 50 entries)\n");
return ERR_NONE;
case 0x36:
smprintf(s, "Too long name\n");
return ERR_NOTSUPPORTED;
case 0x3c:
smprintf(s, "Can not add entry with 0 subentries\n");
return ERR_NOTSUPPORTED;
case 0x3d:
smprintf(s, "Wrong entry type\n");
return ERR_NOTSUPPORTED;
case 0x3e:
smprintf(s, "Too many entries\n");
return ERR_NOTSUPPORTED;
case 0x43:
smprintf(s, "Incorrect characters\n");
return ERR_NOTSUPPORTED;
default:
smprintf(s, "ERROR: unknown %i\n",msg->Buffer[10]);
return ERR_UNKNOWNRESPONSE;
}
default:
smprintf(s, "Phonebook entry written\n");
return ERR_NONE;
}
}
gboolean NOKIA_FindPhoneFeatureValue(GSM_StateMachine *s,
GSM_Profile_PhoneTableValue ProfileTable[],
GSM_Profile_Feat_ID FeatureID,
GSM_Profile_Feat_Value FeatureValue,
unsigned char *PhoneID,
unsigned char *PhoneValue)
{
int i=0;
smprintf(s, "Trying to find feature %i with value %i\n",FeatureID,FeatureValue);
while (ProfileTable[i].ID != 0x00) {
if (ProfileTable[i].ID == FeatureID &&
ProfileTable[i].Value == FeatureValue) {
*PhoneID = ProfileTable[i].PhoneID;
*PhoneValue = ProfileTable[i].PhoneValue;
return TRUE;
}
i++;
}
return FALSE;
}
#define PROFILE_CALLERGROUPS_GROUP1 0x01
#define PROFILE_CALLERGROUPS_GROUP2 0x02
#define PROFILE_CALLERGROUPS_GROUP3 0x04
#define PROFILE_CALLERGROUPS_GROUP4 0x08
#define PROFILE_CALLERGROUPS_GROUP5 0x10
void NOKIA_FindFeatureValue(GSM_StateMachine *s,
GSM_Profile_PhoneTableValue ProfileTable[],
unsigned char ID,
unsigned char Value,
GSM_Phone_Data *Data,
gboolean CallerGroups)
{
int i;
if (CallerGroups) {
smprintf(s, "Caller groups: %i\n", Value);
Data->Profile->FeatureID [Data->Profile->FeaturesNumber] = Profile_CallerGroups;
Data->Profile->FeaturesNumber++;
for (i=0;i<5;i++) Data->Profile->CallerGroups[i] = FALSE;
if ((Value & PROFILE_CALLERGROUPS_GROUP1)==PROFILE_CALLERGROUPS_GROUP1) Data->Profile->CallerGroups[0] = TRUE;
if ((Value & PROFILE_CALLERGROUPS_GROUP2)==PROFILE_CALLERGROUPS_GROUP2) Data->Profile->CallerGroups[1] = TRUE;
if ((Value & PROFILE_CALLERGROUPS_GROUP3)==PROFILE_CALLERGROUPS_GROUP3) Data->Profile->CallerGroups[2] = TRUE;
if ((Value & PROFILE_CALLERGROUPS_GROUP4)==PROFILE_CALLERGROUPS_GROUP4) Data->Profile->CallerGroups[3] = TRUE;
if ((Value & PROFILE_CALLERGROUPS_GROUP5)==PROFILE_CALLERGROUPS_GROUP5) Data->Profile->CallerGroups[4] = TRUE;
return;
}
i = 0;
while (ProfileTable[i].ID != 0x00) {
if (ProfileTable[i].PhoneID == ID &&
ProfileTable[i].PhoneValue == Value) {
#ifdef DEBUG
switch (ProfileTable[i].ID) {
case Profile_KeypadTone : smprintf(s, "Keypad tones\n"); break;
case Profile_CallAlert : smprintf(s, "Call alert\n"); break;
case Profile_RingtoneVolume : smprintf(s, "Ringtone volume\n"); break;
case Profile_MessageTone : smprintf(s, "SMS message tones\n"); break;
case Profile_Vibration : smprintf(s, "Vibration\n"); break;
case Profile_WarningTone : smprintf(s, "Warning (ang games) tones\n"); break;
case Profile_AutoAnswer : smprintf(s, "Automatic answer\n"); break;
case Profile_Lights : smprintf(s, "Lights\n"); break;
case Profile_ScreenSaver : smprintf(s, "Screen Saver\n"); break;
case Profile_ScreenSaverTime : smprintf(s, "Screen Saver timeout\n"); break;
default : break;
}
#endif
Data->Profile->FeatureID [Data->Profile->FeaturesNumber] = ProfileTable[i].ID;
Data->Profile->FeatureValue [Data->Profile->FeaturesNumber] = ProfileTable[i].Value;
Data->Profile->FeaturesNumber++;
break;
}
i++;
}
}
GSM_Profile_PhoneTableValue Profile71_65[] = {
{Profile_KeypadTone, PROFILE_KEYPAD_OFF, 0x00,0x00},
{Profile_KeypadTone, PROFILE_KEYPAD_LEVEL1, 0x00,0x01},
{Profile_KeypadTone, PROFILE_KEYPAD_LEVEL2, 0x00,0x02},
{Profile_KeypadTone, PROFILE_KEYPAD_LEVEL3, 0x00,0x03},
/* Lights ? */
{Profile_CallAlert, PROFILE_CALLALERT_RINGING, 0x02,0x00},
{Profile_CallAlert, PROFILE_CALLALERT_ASCENDING, 0x02,0x01},
{Profile_CallAlert, PROFILE_CALLALERT_RINGONCE, 0x02,0x02},
{Profile_CallAlert, PROFILE_CALLALERT_BEEPONCE, 0x02,0x03},
{Profile_CallAlert, PROFILE_CALLALERT_OFF, 0x02,0x05},
/* {Profile_CallAlert, PROFILE_CALLALERT_CALLERGROUPS,0x02,0x07}, */
/* Ringtone ID */
{Profile_RingtoneVolume, PROFILE_VOLUME_LEVEL1, 0x04,0x00},
{Profile_RingtoneVolume, PROFILE_VOLUME_LEVEL2, 0x04,0x01},
{Profile_RingtoneVolume, PROFILE_VOLUME_LEVEL3, 0x04,0x02},
{Profile_RingtoneVolume, PROFILE_VOLUME_LEVEL4, 0x04,0x03},
{Profile_RingtoneVolume, PROFILE_VOLUME_LEVEL5, 0x04,0x04},
{Profile_MessageTone, PROFILE_MESSAGE_NOTONE, 0x05,0x00},
{Profile_MessageTone, PROFILE_MESSAGE_STANDARD, 0x05,0x01},
{Profile_MessageTone, PROFILE_MESSAGE_SPECIAL, 0x05,0x02},
{Profile_MessageTone, PROFILE_MESSAGE_BEEPONCE, 0x05,0x03},
{Profile_MessageTone, PROFILE_MESSAGE_ASCENDING, 0x05,0x04},
{Profile_Vibration, PROFILE_VIBRATION_OFF, 0x06,0x00},
{Profile_Vibration, PROFILE_VIBRATION_ON, 0x06,0x01},
{Profile_WarningTone, PROFILE_WARNING_OFF, 0x07,0x00},
{Profile_WarningTone, PROFILE_WARNING_ON, 0x07,0x01},
/* Caller groups */
{Profile_AutoAnswer, PROFILE_AUTOANSWER_OFF, 0x09,0x00},
{Profile_AutoAnswer, PROFILE_AUTOANSWER_ON, 0x09,0x01},
{0x00, 0x00, 0x00,0x00}
};
GSM_Error NOKIA_SetIncomingSMS(GSM_StateMachine *s, gboolean enable)
{
s->Phone.Data.EnableIncomingSMS = enable;
#ifdef DEBUG
if (enable) {
smprintf(s, "Enabling incoming SMS\n");
} else {
smprintf(s, "Disabling incoming SMS\n");
}
#endif
return ERR_NONE;
}
GSM_Error N71_65_ReplyUSSDInfo(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
unsigned char buffer[2000];
GSM_USSDMessage ussd;
if (s->Phone.Data.RequestID == ID_Divert) return ERR_NONE;
memcpy(buffer,msg->Buffer+8,msg->Buffer[7]);
buffer[msg->Buffer[7]] = 0x00;
smprintf(s, "USSD reply: \"%s\"\n",buffer);
if (s->Phone.Data.EnableIncomingUSSD && s->User.IncomingUSSD!=NULL) {
EncodeUnicode(ussd.Text,buffer,strlen(buffer));
/**
* @todo: Should determine status.
*/
ussd.Status = USSD_Unknown;
s->User.IncomingUSSD(s, &ussd, s->User.IncomingUSSDUserData);
}
return ERR_NONE;
}
GSM_Error NOKIA_SetIncomingUSSD(GSM_StateMachine *s, gboolean enable)
{
s->Phone.Data.EnableIncomingUSSD = enable;
#ifdef DEBUG
if (enable) {
smprintf(s, "Enabling incoming USSD\n");
} else {
smprintf(s, "Disabling incoming USSD\n");
}
#endif
return ERR_NONE;
}
GSM_Error NOKIA_SetIncomingCall(GSM_StateMachine *s, gboolean enable)
{
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo,F_NOCALLINFO)) return ERR_NOTSUPPORTED;
s->Phone.Data.EnableIncomingCall = enable;
#ifdef DEBUG
if (enable) {
smprintf(s, "Enabling incoming Call\n");
} else {
smprintf(s, "Disabling incoming Call\n");
}
#endif
return ERR_NONE;
}
GSM_Error N71_65_ReplyCallInfo(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
GSM_Call call;
int tmp;
unsigned char buffer[200];
call.Status = 0;
call.StatusCode = 0;
call.CallIDAvailable = TRUE;
call.PhoneNumber[0] = 0;
call.PhoneNumber[1] = 0;
smprintf(s, "Call info, ");
switch (msg->Buffer[3]) {
case 0x02:
smprintf(s, "Call established, waiting for answer\n");
call.Status = GSM_CALL_CallEstablished;
break;
case 0x03:
case 0x53:
case 0x05:
if (msg->Buffer[3] == 0x03) {
smprintf(s, "Call started\n");
call.Status = GSM_CALL_CallStart;
} else if (msg->Buffer[3] == 0x05) {
smprintf(s, "Incoming call\n");
call.Status = GSM_CALL_IncomingCall;
} else {
smprintf(s, "Outgoing call\n");
call.Status = GSM_CALL_OutgoingCall;
}
/* Sample reply:
01 |72r|02 |03 |01 |03 |07 |04 |01 |01 |01 |1C |11 |300|00 | 0B .r...........0..
00 |333|00 |322|00 |344|00 |399|00 |399|00 |355|00 |366|00 |377 .3.2.4.9.9.5.6.7
00 |322|00 |311|00 |311|0E |1C |300|02 |0A |00 |00 |09 |00 |4AJ .2.1.1..0......J
00 |6Fo|00 |72r|00 |69i|00 |73s|00 |20 |00 |41A|00 |63c|00 |63c .o.r.i.s. .A.c.c
00 |00 |00 |00 |00 |00 |00 |00 |00 |00 |00 |00 ............
*/
smprintf(s, "Call mode : %i\n",msg->Buffer[5]);/* such interpretation is in gnokii */
/* This is probably wrong, but I need more sample data to properly parse output */
if (msg->Buffer[6] == 7) {
tmp = 14;
} else {
tmp = 6;
}
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer,call.PhoneNumber,FALSE);
smprintf(s, "Number : \"%s\"\n",DecodeUnicodeString(call.PhoneNumber));
/* FIXME: read name from frame */
break;
case 0x04:
smprintf(s, "Remote end hang up\n");
smprintf(s, "Cause Type : %i\n",msg->Buffer[5]);/* such interpretation is in gnokii */
smprintf(s, "CC : %i\n",msg->Buffer[6]);
smprintf(s, "MM(?) : %i\n",msg->Buffer[7]);
smprintf(s, "RR(?) : %i\n",msg->Buffer[8]);
call.Status = GSM_CALL_CallRemoteEnd;
call.StatusCode = msg->Buffer[6];
break;
case 0x07:
smprintf(s, "Call answer initiated\n");
break;
case 0x09:
smprintf(s, "Call released\n");
call.Status = GSM_CALL_CallLocalEnd;
break;
case 0x0a:
smprintf(s, "Call is being released\n");
break;
case 0x0b:
smprintf(s, "Meaning not known\n");
call.CallIDAvailable = FALSE;
break;
case 0x0c:
smprintf(s, "Audio status\n");
if (msg->Buffer[4] == 0x01) smprintf(s, "Audio enabled\n");
else smprintf(s, "Audio disabled\n");
call.CallIDAvailable = FALSE;
break;
case 0x0f: /* 6111 */
if (msg->Buffer[8]==0x01) {
smprintf(s, "Calling from phone keypad ?\n");
if (msg->Buffer[14]==0x03) {
tmp = 19;
} else {
tmp = 21;
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer,buffer,FALSE);
smprintf(s, "Name : \"%s\"\n",DecodeUnicodeString(buffer));
tmp+=7;
}
if (msg->Buffer[tmp-3]==0x11) {
call.PhoneNumber[0]=0;
call.PhoneNumber[1]='+';
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer,call.PhoneNumber+2,FALSE);
} else {
NOKIA_GetUnicodeString(s, &tmp, msg->Buffer,call.PhoneNumber,FALSE);
}
call.Status = GSM_CALL_OutgoingCall;
}
if (msg->Buffer[8]==0x00) {
smprintf(s, "Call released\n");
call.Status = GSM_CALL_CallLocalEnd;
}
break;
case 0x10:
smprintf(s, "Meaning not known\n");
call.CallIDAvailable = FALSE;
break;
case 0x23:
smprintf(s, "Call held\n");
call.Status = GSM_CALL_CallHeld;
break;
case 0x25:
smprintf(s, "Call resumed\n");
call.Status = GSM_CALL_CallResumed;
break;
case 0x27:
smprintf(s, "Call switched\n");
call.Status = GSM_CALL_CallSwitched;
break;
case 0xA6:
case 0xD2:
case 0xD3:
smprintf(s, "Meaning not known\n");
call.CallIDAvailable = FALSE;
break;
}
if (call.CallIDAvailable) smprintf(s, "Call ID : %d\n",msg->Buffer[4]);
if (s->Phone.Data.EnableIncomingCall && s->User.IncomingCall!=NULL && call.Status != 0) {
if (call.CallIDAvailable) call.CallID = msg->Buffer[4];
s->User.IncomingCall(s, &call, s->User.IncomingCallUserData);
}
if (s->Phone.Data.RequestID == ID_DialVoice) {
if (msg->Buffer[3] == 0x10) return ERR_NOTSUPPORTED;
}
if (s->Phone.Data.RequestID == ID_CancelCall) {
if (msg->Buffer[3] == 0x09) {
if (s->Phone.Data.CallID == msg->Buffer[4]) return ERR_NONE;
/* when we canceled call and see frame about other
* call releasing, we don't give ERR_NONE for "our"
* call release command
*/
return ERR_NEEDANOTHERANSWER;
}
}
if (s->Phone.Data.RequestID == ID_AnswerCall) {
if (msg->Buffer[3] == 0x07) {
if (s->Phone.Data.CallID == msg->Buffer[4]) return ERR_NONE;
return ERR_NEEDANOTHERANSWER;
}
}
return ERR_NONE;
}
/* method 2 */
GSM_Error N71_65_ReplyAddCalendar2(GSM_Protocol_Message *msg UNUSED, GSM_StateMachine *s)
{
smprintf(s, "Calendar note added\n");
return ERR_NONE;
}
/* method 2 */
GSM_Error N71_65_AddCalendar2(GSM_StateMachine *s, GSM_CalendarEntry *Note)
{
GSM_CalendarNoteType NoteType;
time_t t_time1,t_time2;
GSM_DateTime Date,date_time;
GSM_Error error;
long diff;
int Text, Time, Alarm, Phone, EndTime, Location, length=25;
unsigned char req[5000] = {
N6110_FRAME_HEADER,
0x40,
0x00, /* frame length - 7 */
0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00, /* start time saved as difference */
0x00,0x00,0xff,0xff, /* alarm saved as difference */
0x00, /* frame length - 7 */
0x00, /* note type */
0x00,0x00, /* recurrance */
0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00}; /* rest depends on note type */
NoteType = N71_65_FindCalendarType(Note->Type, s->Phone.Data.ModelInfo);
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL62) ||
GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL65)) {
switch(NoteType) {
case GSM_CAL_MEETING : req[18] = 0x01; length = 25; break;
case GSM_CAL_CALL : req[18] = 0x02; length = 27; break;
case GSM_CAL_BIRTHDAY : req[18] = 0x04; length = 28; break;
case GSM_CAL_MEMO : req[18] = 0x08; length = 25; break;
default : return ERR_UNKNOWN;
}
} else {
switch(NoteType) {
case GSM_CAL_REMINDER : req[18] = 0x01; length = 25; break;
case GSM_CAL_CALL : req[18] = 0x02; length = 27; break;
case GSM_CAL_BIRTHDAY : req[18] = 0x04; length = 28; break;
case GSM_CAL_MEMO : req[18] = 0x08; length = 25; break;
default : return ERR_UNKNOWN;
}
}
GSM_CalendarFindDefaultTextTimeAlarmPhone(Note, &Text, &Time, &Alarm, &Phone, &EndTime, &Location);
if (Time == -1) {
smprintf(s, "Can not save entry without time!\n");
return ERR_UNKNOWN;
}
if (NoteType != GSM_CAL_BIRTHDAY) {
Date.Year = 2030; Date.Month = 01; Date.Day = 01;
Date.Hour = 00; Date.Minute = 00; Date.Second = 00;
} else {
Date.Year = 2029; Date.Month = 12; Date.Day = 31;
Date.Hour = 22; Date.Minute = 59; Date.Second = 58;
}
t_time1 = Fill_Time_T(Date);
memcpy(&Date,&Note->Entries[Time].Date,sizeof(GSM_DateTime));
if (NoteType != GSM_CAL_BIRTHDAY) {
Date.Year -= 20;
} else {
/* 6230 and probably other new models handle it differently
we don't make difference from 1980 year
*/
if (GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL35) ||
GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL65) ||
GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL62)) {
Date.Year = 1980;
}
Date.Hour = 22; Date.Minute = 58; Date.Second = 58;
}
t_time2 = Fill_Time_T(Date);
diff = t_time1-t_time2;
smprintf(s, " Difference : %li seconds\n", -diff);
req[9] = (unsigned char)(-diff >> 24);
req[10] = (unsigned char)(-diff >> 16);
req[11] = (unsigned char)(-diff >> 8);
req[12] = (unsigned char)(-diff);
if (NoteType == GSM_CAL_BIRTHDAY) {
req[25] = Note->Entries[Time].Date.Year / 256;
req[26] = Note->Entries[Time].Date.Year % 256;
/* Recurrance = 1 year */
req[19] = 0xff;
req[20] = 0xff;
}
if (NoteType == GSM_CAL_CALL && Phone != -1) {
req[25] = UnicodeLength(Note->Entries[Phone].Text);
CopyUnicodeString(req+length,Note->Entries[Phone].Text);
length += UnicodeLength(Note->Entries[Phone].Text)*2;
}
if (Alarm != -1) {
if (NoteType == GSM_CAL_BIRTHDAY) {
if (Note->Entries[Alarm].EntryType == CAL_SILENT_ALARM_DATETIME) req[27] = 0x01;
error=s->Phone.Functions->GetDateTime(s,&date_time);
switch (error) {
case ERR_EMPTY:
case ERR_NOTIMPLEMENTED:
GSM_GetCurrentDateTime(&date_time);
break;
case ERR_NONE:
break;
default:
return error;
}
Date.Year = date_time.Year;
Date.Hour = 23;
Date.Minute = 59;
} else {
Date.Year += 20;
}
t_time2 = Fill_Time_T(Date);
t_time1 = Fill_Time_T(Note->Entries[Alarm].Date);
diff = t_time1-t_time2;
/* Sometimes we have difference in minutes */
if (NoteType == GSM_CAL_MEETING) diff = diff / 60;
if (!GSM_IsPhoneFeatureAvailable(s->Phone.Data.ModelInfo, F_CAL35)) {
if (NoteType == GSM_CAL_MEMO || NoteType == GSM_CAL_CALL) {
diff = diff / 60;
}
}
smprintf(s, " Difference : %li seconds or minutes\n", -diff);
req[13] = (unsigned char)(-diff >> 24);
req[14] = (unsigned char)(-diff >> 16);
req[15] = (unsigned char)(-diff >> 8);
req[16] = (unsigned char)(-diff);
}
GSM_SetCalendarRecurranceRepeat(&(s->di), req+19, NULL, Note);
if (Text != -1) {
switch (NoteType) {
case GSM_CAL_CALL:
req[26] = UnicodeLength(Note->Entries[Text].Text);
break;
default:
req[length++] = UnicodeLength(Note->Entries[Text].Text);
if (NoteType == GSM_CAL_MEMO || NoteType == GSM_CAL_MEETING) req[length++] = 0x00;
}
CopyUnicodeString(req+length,Note->Entries[Text].Text);
length += UnicodeLength(Note->Entries[Text].Text)*2;
}
req[length++] = 0x00;
req[length++] = 0x00;
req[4] = req[17] = length-7;
smprintf(s, "Writing calendar note method 2\n");
return GSM_WaitFor (s, req, length, 0x13, 4, ID_SetCalendarNote);
}
/* method 1*/
GSM_Error N71_65_ReplyGetCalendarNotePos1(GSM_Protocol_Message *msg, GSM_StateMachine *s,int *FirstCalendarPos)
{
smprintf(s, "First calendar location: %i\n",msg->Buffer[4]*256+msg->Buffer[5]);
*FirstCalendarPos = msg->Buffer[4]*256+msg->Buffer[5];
return ERR_NONE;
}
/* method 1*/
static GSM_Error N71_65_GetCalendarNotePos1(GSM_StateMachine *s)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x31};
smprintf(s, "Getting first free calendar note location\n");
return GSM_WaitFor (s, req, 4, 0x13, 4, ID_GetCalendarNotePos);
}
/* method 1 */
GSM_Error N71_65_ReplyAddCalendar1(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
#ifdef DEBUG
smprintf(s, "Written calendar note type ");
switch ((msg->Buffer[3]/2)-1) {
case 0: smprintf(s, "Meeting"); break;
case 1: smprintf(s, "Call"); break;
case 2: smprintf(s, "Birthday");break;
case 3: smprintf(s, "Reminder");break;
}
smprintf(s, " on location %d\n",msg->Buffer[4]*256+msg->Buffer[5]);
#endif
return ERR_NONE;
}
/* method 1 */
GSM_Error N71_65_AddCalendar1(GSM_StateMachine *s, GSM_CalendarEntry *Note, int *FirstCalendarPos)
{
long seconds;
GSM_Error error;
GSM_DateTime DT;
int Text, Time, Alarm, Phone, EndTime, Location, count=12;
unsigned char req[5000] = {
N6110_FRAME_HEADER,
0x01, /* note type */
0x00, 0x00, /* location ? */
0x00, /* entry type */
0x00,
0x00, 0x00, /* Year */
0x00, /* Month */
0x00, /* Day */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
error=N71_65_GetCalendarNotePos1(s);
if (error!=ERR_NONE) return error;
if (FirstCalendarPos != NULL) {
Note->Location = *FirstCalendarPos;
req[4] = *FirstCalendarPos/256;
req[5] = *FirstCalendarPos%256;
}
switch(Note->Type) {
case GSM_CAL_CALL : req[3]=0x03; req[6]=0x02; break;
case GSM_CAL_BIRTHDAY: req[3]=0x05; req[6]=0x04; break;
case GSM_CAL_MEMO : req[3]=0x07; req[6]=0x08; break;
case GSM_CAL_MEETING :
default : req[3]=0x01; req[6]=0x01; break;
}
GSM_CalendarFindDefaultTextTimeAlarmPhone(Note, &Text, &Time, &Alarm, &Phone, &EndTime, &Location);
if (Time == -1) {
smprintf(s, "Can not save entry without time!\n");
return ERR_UNKNOWN;
}
memcpy(&DT,&Note->Entries[Time].Date,sizeof(GSM_DateTime));
req[8] = DT.Year / 256;
req[9] = DT.Year % 256;
req[10] = DT.Month;
req[11] = DT.Day;
switch(Note->Type) {
case GSM_CAL_BIRTHDAY:
/* byte 12 and 13 */
req[count++] = 0x00;
req[count++] = 0x00;
/* Alarm - bytes 14 to 17 */
req[count++] = 0x00;
req[count++] = 0x00;
req[count++] = 0xff;
req[count++] = 0xff;
if (Alarm != -1) {
/* Comment from original source by Gabriele Zappi:
* I try with Time.Year = Alarm.Year. If negative, I increase 1 year,
* but only once ! This thing, because I may have Alarm period across
* a year. (eg. Birthday on 2001-01-10 and Alarm on 2000-12-27)
*/
DT.Year = Note->Entries[Alarm].Date.Year;
seconds = Fill_Time_T(DT)-Fill_Time_T(Note->Entries[Alarm].Date);
if (seconds<0L) {
DT.Year++;
seconds = Fill_Time_T(DT)-Fill_Time_T(Note->Entries[Alarm].Date);
}
if (seconds>=0L) {
count -= 4;
/* bytes 14 to 17 */
req[count++] = (unsigned char)(seconds>>24);
req[count++] = (unsigned char)((seconds>>16) & 0xff);
req[count++] = (unsigned char)((seconds>>8) & 0xff);
req[count++] = (unsigned char)(seconds & 0xff);
}
/* byte 18 */
if (Note->Entries[Alarm].EntryType == CAL_SILENT_ALARM_DATETIME) req[count++] = 0x01; else req[count++] = 0x00;
}
/* byte 19 and next */
if (Text != -1) {
req[count++] = UnicodeLength(Note->Entries[Text].Text);
CopyUnicodeString(req+count,Note->Entries[Text].Text);
count=count+2*UnicodeLength(Note->Entries[Text].Text);
} else {
req[count++] = 0x00;
}
break;
case GSM_CAL_MEMO:
/* byte 12 and 13 */
GSM_SetCalendarRecurranceRepeat(&(s->di), req+count, NULL, Note);
count+=2;
/* byte 14 and next */
if (Text != -1) {
req[count++] = UnicodeLength(Note->Entries[Text].Text);
req[count++] = 0x00;
CopyUnicodeString(req+count,Note->Entries[Text].Text);
count=count+2*UnicodeLength(Note->Entries[Text].Text);
} else {
req[count++] = 0x00;
req[count++] = 0x00;
}
break;
case GSM_CAL_MEETING:
case GSM_CAL_CALL:
default:
/* byte 12 and 13 */
req[count++] = DT.Hour;
req[count++] = DT.Minute;
/* Alarm - byte 14 and 15 */
req[count++] = 0xff;
req[count++] = 0xff;
if (Alarm != -1) {
seconds=Fill_Time_T(DT)-Fill_Time_T(Note->Entries[Alarm].Date);
if (seconds>=0L) {
count -= 2;
req[count++] = (unsigned char)((seconds/60L)>>8);
req[count++] = (unsigned char)((seconds/60L)&0xff);
}
}
/* byte 16 and 17 */
GSM_SetCalendarRecurranceRepeat(&(s->di), req+count, NULL, Note);
count+=2;
/* byte 18 */
if (Text != -1) {
req[count++] = UnicodeLength(Note->Entries[Text].Text);
} else {
req[count++] = 0x00;
}
/* byte 19 */
if (Note->Type == GSM_CAL_CALL && Phone != -1) {
req[count++] = UnicodeLength(Note->Entries[Phone].Text);
} else {
req[count++] = 0x00;
}
if (Text != -1) {
CopyUnicodeString(req+count,Note->Entries[Text].Text);
count=count+2*UnicodeLength(Note->Entries[Text].Text);
}
if (Note->Type == GSM_CAL_CALL && Phone != -1) {
CopyUnicodeString(req+count,Note->Entries[Phone].Text);
count=count+2*UnicodeLength(Note->Entries[Phone].Text);
}
break;
}
req[count] = 0x00;
smprintf(s, "Writing calendar note method 1\n");
return GSM_WaitFor (s, req, count, 0x13, 4, ID_SetCalendarNote);
}
GSM_Error N71_65_ReplyDelCalendar(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
if (msg->Buffer[3] == 0xf0) return ERR_NOTSUPPORTED;
smprintf(s, "Deleted calendar note on location %d\n",msg->Buffer[4]*256+msg->Buffer[5]);
return ERR_NONE;
}
GSM_Error N71_65_DelCalendar(GSM_StateMachine *s, GSM_CalendarEntry *Note)
{
unsigned char req[] = {N6110_FRAME_HEADER, 0x0b,
0x00, 0x00}; /* location */
req[4] = Note->Location / 256;
req[5] = Note->Location % 256;
smprintf(s, "Deleting calendar note\n");
return GSM_WaitFor (s, req, 6, 0x13, 4, ID_DeleteCalendarNote);
}
/* method 1 */
GSM_Error N71_65_ReplyGetCalendarInfo1(GSM_Protocol_Message *msg, GSM_StateMachine *s, GSM_NOKIACalToDoLocations *LastCalendar)
{
size_t i,j=0;
smprintf(s, "Info with calendar notes locations received method 1\n");
while (LastCalendar->Location[j] != 0x00) j++;
if (j >= GSM_MAXCALENDARTODONOTES) {
smprintf(s, "Increase GSM_MAXCALENDARNOTES\n");
return ERR_MOREMEMORY;
}
if (j == 0) {
LastCalendar->Number=msg->Buffer[4]*256+msg->Buffer[5];
smprintf(s, "Number of Entries: %i\n",LastCalendar->Number);
}
smprintf(s, "Locations: ");
i = 0;
while (9+(i*2) <= msg->Length) {
LastCalendar->Location[j++]=msg->Buffer[8+(i*2)]*256+msg->Buffer[9+(i*2)];
smprintf(s, "%i ",LastCalendar->Location[j-1]);
i++;
}
smprintf(s, "\nNumber of Entries in frame: %ld\n", (long)i);
smprintf(s, "\n");
LastCalendar->Location[j] = 0;
if (i == 1 && msg->Buffer[8+(0*2)]*256+msg->Buffer[9+(0*2)] == 0) return ERR_EMPTY;
if (i == 0) return ERR_EMPTY;
return ERR_NONE;
}
/* method 1 */
GSM_Error N71_65_GetCalendarInfo1(GSM_StateMachine *s, GSM_NOKIACalToDoLocations *LastCalendar)
{
GSM_Error error;
int i;
unsigned char req[] = {N6110_FRAME_HEADER, 0x3a,
0xFF, 0xFE}; /* First location number */
LastCalendar->Location[0] = 0x00;
LastCalendar->Number = 0;
smprintf(s, "Getting locations for calendar method 1\n");
error = GSM_WaitFor (s, req, 6, 0x13, 4, ID_GetCalendarNotesInfo);
if (error != ERR_NONE && error != ERR_EMPTY) return error;
while (1) {
i=0;
while (LastCalendar->Location[i] != 0x00) i++;
if (i == LastCalendar->Number) break;
if (i != LastCalendar->Number && error == ERR_EMPTY) {
smprintf(s, "Phone doesn't support some notes with this method. Workaround\n");
LastCalendar->Number = i;
break;
}
smprintf(s, "i = %i %i\n",i,LastCalendar->Number);
req[4] = LastCalendar->Location[i-1] / 256;
req[5] = LastCalendar->Location[i-1] % 256;
smprintf(s, "Getting locations for calendar\n");
error = GSM_WaitFor (s, req, 6, 0x13, 4, ID_GetCalendarNotesInfo);
if (error != ERR_NONE && error != ERR_EMPTY) return error;
}
return ERR_NONE;
}
/* method 1 */
GSM_Error N71_65_ReplyGetNextCalendar1(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
int timedelta,i;
GSM_CalendarEntry *entry = s->Phone.Data.Cal;
smprintf(s, "Calendar note received method 1\n");
/* Later these values can change */
if (msg->Buffer[6]!=0x04) { /* Here not birthday */
entry->Entries[0].Date.Year = msg->Buffer[8]*256+msg->Buffer[9];
}
entry->Entries[0].Date.Month = msg->Buffer[10];
entry->Entries[0].Date.Day = msg->Buffer[11];
entry->Entries[0].Date.Hour = msg->Buffer[12];
entry->Entries[0].Date.Minute = msg->Buffer[13];
entry->Entries[0].Date.Second = 0;
entry->Entries[0].EntryType = CAL_START_DATETIME;
entry->EntriesNum++;
switch (msg->Buffer[6]) {
case 0x01:
smprintf(s, "Meeting\n");
entry->Type = GSM_CAL_MEETING;
timedelta=msg->Buffer[14]*256+msg->Buffer[15];
if (timedelta != 0xffff) {
smprintf(s, " Difference : %i seconds\n", timedelta);
memcpy(&entry->Entries[1].Date,&entry->Entries[0].Date,sizeof(GSM_DateTime));
GetTimeDifference(timedelta, &entry->Entries[1].Date, FALSE, 60);
entry->Entries[1].EntryType = CAL_TONE_ALARM_DATETIME;
entry->EntriesNum++;
}
GSM_GetCalendarRecurranceRepeat(&(s->di), msg->Buffer + 16, NULL, entry);
memcpy(entry->Entries[entry->EntriesNum].Text, msg->Buffer+20, msg->Buffer[18]*2);
entry->Entries[entry->EntriesNum].Text[msg->Buffer[18]*2] = 0;
entry->Entries[entry->EntriesNum].Text[msg->Buffer[18]*2+1] = 0;
entry->Entries[entry->EntriesNum].EntryType = CAL_TEXT;
smprintf(s, "Text : \"%s\"\n", DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum++;
return ERR_NONE;
case 0x02:
smprintf(s, "Call\n");
entry->Type = GSM_CAL_CALL;
timedelta=msg->Buffer[14]*256+msg->Buffer[15];
if (timedelta != 0xffff) {
smprintf(s, " Difference : %i seconds\n", timedelta);
memcpy(&entry->Entries[1].Date,&entry->Entries[0].Date,sizeof(GSM_DateTime));
GetTimeDifference(timedelta, &entry->Entries[1].Date, FALSE, 60);
entry->Entries[1].EntryType = CAL_TONE_ALARM_DATETIME;
entry->EntriesNum++;
}
GSM_GetCalendarRecurranceRepeat(&(s->di), msg->Buffer + 16, NULL, entry);
i = msg->Buffer[18] * 2;
if (i!=0) {
memcpy(entry->Entries[entry->EntriesNum].Text, msg->Buffer+20, i);
entry->Entries[entry->EntriesNum].Text[i] = 0;
entry->Entries[entry->EntriesNum].Text[i+1] = 0;
entry->Entries[entry->EntriesNum].EntryType = CAL_TEXT;
smprintf(s, "Text : \"%s\"\n", DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum++;
}
memcpy(entry->Entries[entry->EntriesNum].Text, msg->Buffer+20+i, msg->Buffer[19]*2);
entry->Entries[entry->EntriesNum].Text[msg->Buffer[19]*2] = 0;
entry->Entries[entry->EntriesNum].Text[msg->Buffer[19]*2+1] = 0;
entry->Entries[entry->EntriesNum].EntryType = CAL_PHONE;
smprintf(s, "Phone : \"%s\"\n", DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum++;
return ERR_NONE;
case 0x04:
smprintf(s, "Birthday\n");
entry->Type = GSM_CAL_BIRTHDAY;
entry->Entries[0].Date.Hour = 23;
entry->Entries[0].Date.Minute = 59;
entry->Entries[0].Date.Second = 58;
timedelta = ((unsigned int)msg->Buffer[14]) << 24;
timedelta += ((unsigned int)msg->Buffer[15]) << 16;
timedelta += ((unsigned int)msg->Buffer[16]) << 8;
timedelta += msg->Buffer[17];
if (timedelta != 0xffff) {
smprintf(s, " Difference : %i seconds\n", timedelta);
memcpy(&entry->Entries[1].Date,&entry->Entries[0].Date,sizeof(GSM_DateTime));
GetTimeDifference(timedelta, &entry->Entries[1].Date, FALSE, 1);
entry->Entries[1].EntryType = CAL_TONE_ALARM_DATETIME;
if (msg->Buffer[20]!=0x00) {
entry->Entries[1].EntryType = CAL_SILENT_ALARM_DATETIME;
smprintf(s, "Alarm type : Silent\n");
}
entry->EntriesNum++;
}
entry->Entries[0].Date.Year = msg->Buffer[18]*256 + msg->Buffer[19];
if (entry->Entries[0].Date.Year == 65535) entry->Entries[0].Date.Year = 0;
smprintf(s, "Age : %i\n",entry->Entries[0].Date.Year);
memcpy(entry->Entries[entry->EntriesNum].Text, msg->Buffer+22, msg->Buffer[21]*2);
entry->Entries[entry->EntriesNum].Text[msg->Buffer[21]*2] = 0;
entry->Entries[entry->EntriesNum].Text[msg->Buffer[21]*2+1] = 0;
entry->Entries[entry->EntriesNum].EntryType = CAL_TEXT;
smprintf(s, "Text : \"%s\"\n", DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum++;
entry->Entries[entry->EntriesNum].EntryType = CAL_REPEAT_FREQUENCY;
entry->Entries[entry->EntriesNum].Number = 1;
entry->EntriesNum++;
entry->Entries[entry->EntriesNum].EntryType = CAL_REPEAT_DAY;
entry->Entries[entry->EntriesNum].Number = entry->Entries[0].Date.Day;
entry->EntriesNum++;
entry->Entries[entry->EntriesNum].EntryType = CAL_REPEAT_MONTH;
entry->Entries[entry->EntriesNum].Number = entry->Entries[0].Date.Month;
entry->EntriesNum++;
return ERR_NONE;
case 0x08:
smprintf(s, "Memo\n");
entry->Type = GSM_CAL_MEMO;
entry->Entries[0].Date.Hour = 0;
entry->Entries[0].Date.Minute = 0;
GSM_GetCalendarRecurranceRepeat(&(s->di), msg->Buffer + 12, NULL, entry);
memcpy(entry->Entries[entry->EntriesNum].Text, msg->Buffer+16, msg->Buffer[14]*2);
entry->Entries[entry->EntriesNum].Text[msg->Buffer[14]*2] = 0;
entry->Entries[entry->EntriesNum].Text[msg->Buffer[14]*2+1] = 0;
entry->Entries[entry->EntriesNum].EntryType = CAL_TEXT;
smprintf(s, "Text : \"%s\"\n", DecodeUnicodeString(entry->Entries[entry->EntriesNum].Text));
entry->EntriesNum++;
return ERR_NONE;
default:
smprintf(s, "ERROR: unknown %i\n",msg->Buffer[6]);
return ERR_UNKNOWNRESPONSE;
}
}
/* method 1 */
GSM_Error N71_65_GetNextCalendar1(GSM_StateMachine *s, GSM_CalendarEntry *Note, gboolean start, GSM_NOKIACalToDoLocations *LastCalendar, int *LastCalendarYear, int *LastCalendarPos)
{
GSM_Error error;
GSM_DateTime date_time;
unsigned char req[] = {N6110_FRAME_HEADER, 0x19,
0x00, 0x00}; /* Location */
if (start) {
error=N71_65_GetCalendarInfo1(s, LastCalendar);
if (error!=ERR_NONE) return error;
if (LastCalendar->Number == 0) return ERR_EMPTY;
/* We have to get current year. It's NOT written in frame for
* Birthday
*/
error=s->Phone.Functions->GetDateTime(s,&date_time);
switch (error) {
case ERR_EMPTY:
case ERR_NOTIMPLEMENTED:
GSM_GetCurrentDateTime(&date_time);
break;
case ERR_NONE:
break;
default:
return error;
}
*LastCalendarYear = date_time.Year;
*LastCalendarPos = 0;
} else {
(*LastCalendarPos)++;
}
if (*LastCalendarPos >= LastCalendar->Number) return ERR_EMPTY;
req[4] = LastCalendar->Location[*LastCalendarPos] / 256;
req[5] = LastCalendar->Location[*LastCalendarPos] % 256;
Note->EntriesNum = 0;
Note->Entries[0].Date.Year = *LastCalendarYear;
Note->Location = LastCalendar->Location[*LastCalendarPos];
s->Phone.Data.Cal=Note;
smprintf(s, "Getting calendar note method 1\n");
return GSM_WaitFor (s, req, 6, 0x13, 4, ID_GetCalendarNote);
}
GSM_Error N71_65_EnableFunctions(GSM_StateMachine *s,const char *buff,int len)
{
unsigned char buffer[50] = {N6110_FRAME_HEADER, 0x10,
0x07}; /* Length */
buffer[4] = len;
memcpy(buffer+5,buff,len);
/* Enables various things like incoming SMS, call info, etc. */
return s->Protocol.Functions->WriteMessage(s, buffer, 5+len, 0x10);
}
GSM_Error N71_65_ReplySendDTMF(GSM_Protocol_Message *msg, GSM_StateMachine *s)
{
switch (msg->Buffer[3]) {
case 0xf0:
return ERR_NOTSUPPORTED;
case 0x51:
smprintf(s, "DTMF sent OK\n");
return ERR_NONE;
case 0x59:
case 0x5E:
smprintf(s, "meaning unknown - during sending DTMF\n");
return ERR_NONE;
}
return ERR_UNKNOWNRESPONSE;
}
GSM_CalendarNoteType N71_65_FindCalendarType(GSM_CalendarNoteType Type, GSM_PhoneModel *model)
{
switch (Type) {
case GSM_CAL_CALL:
return GSM_CAL_CALL;
case GSM_CAL_BIRTHDAY:
return GSM_CAL_BIRTHDAY;
case GSM_CAL_MEETING:
if (GSM_IsPhoneFeatureAvailable(model, F_CAL35)) {
return GSM_CAL_REMINDER;
} else return GSM_CAL_MEETING;
case GSM_CAL_MEMO:
if (GSM_IsPhoneFeatureAvailable(model, F_CAL35)) {
return GSM_CAL_REMINDER;
} else return GSM_CAL_MEMO;
case GSM_CAL_REMINDER:
if (GSM_IsPhoneFeatureAvailable(model, F_CAL62) ||
GSM_IsPhoneFeatureAvailable(model, F_CAL65)) {
return GSM_CAL_CALL;
} else return GSM_CAL_REMINDER;
default:
return GSM_CAL_CALL;
}
}
#endif
/* How should editor hadle tabs in this file? Add editor commands here.
* vim: noexpandtab sw=8 ts=8 sts=8:
*/
| 412 | 0.939516 | 1 | 0.939516 | game-dev | MEDIA | 0.279094 | game-dev | 0.972077 | 1 | 0.972077 |
ScottLilly/SuperAdventure | 8,865 | Engine/World.cs | using System.Collections.Generic;
using System.Linq;
namespace Engine
{
public static class World
{
private static readonly List<Item> _items = new List<Item>();
private static readonly List<Monster> _monsters = new List<Monster>();
private static readonly List<Quest> _quests = new List<Quest>();
private static readonly List<Location> _locations = new List<Location>();
public const int UNSELLABLE_ITEM_PRICE = -1;
public const int ITEM_ID_RUSTY_SWORD = 1;
public const int ITEM_ID_RAT_TAIL = 2;
public const int ITEM_ID_PIECE_OF_FUR = 3;
public const int ITEM_ID_SNAKE_FANG = 4;
public const int ITEM_ID_SNAKESKIN = 5;
public const int ITEM_ID_CLUB = 6;
public const int ITEM_ID_HEALING_POTION = 7;
public const int ITEM_ID_SPIDER_FANG = 8;
public const int ITEM_ID_SPIDER_SILK = 9;
public const int ITEM_ID_ADVENTURER_PASS = 10;
public const int MONSTER_ID_RAT = 1;
public const int MONSTER_ID_SNAKE = 2;
public const int MONSTER_ID_GIANT_SPIDER = 3;
public const int QUEST_ID_CLEAR_ALCHEMIST_GARDEN = 1;
public const int QUEST_ID_CLEAR_FARMERS_FIELD = 2;
public const int LOCATION_ID_HOME = 1;
public const int LOCATION_ID_TOWN_SQUARE = 2;
public const int LOCATION_ID_GUARD_POST = 3;
public const int LOCATION_ID_ALCHEMIST_HUT = 4;
public const int LOCATION_ID_ALCHEMISTS_GARDEN = 5;
public const int LOCATION_ID_FARMHOUSE = 6;
public const int LOCATION_ID_FARM_FIELD = 7;
public const int LOCATION_ID_BRIDGE = 8;
public const int LOCATION_ID_SPIDER_FIELD = 9;
static World()
{
PopulateItems();
PopulateMonsters();
PopulateQuests();
PopulateLocations();
}
private static void PopulateItems()
{
_items.Add(new Weapon(ITEM_ID_RUSTY_SWORD, "Rusty sword", "Rusty swords", 0, 5, 5));
_items.Add(new Item(ITEM_ID_RAT_TAIL, "Rat tail", "Rat tails", 1));
_items.Add(new Item(ITEM_ID_PIECE_OF_FUR, "Piece of fur", "Pieces of fur", 1));
_items.Add(new Item(ITEM_ID_SNAKE_FANG, "Snake fang", "Snake fangs", 1));
_items.Add(new Item(ITEM_ID_SNAKESKIN, "Snakeskin", "Snakeskins", 2));
_items.Add(new Weapon(ITEM_ID_CLUB, "Club", "Clubs", 3, 10, 8));
_items.Add(new HealingPotion(ITEM_ID_HEALING_POTION, "Healing potion", "Healing potions", 5, 3));
_items.Add(new Item(ITEM_ID_SPIDER_FANG, "Spider fang", "Spider fangs", 1));
_items.Add(new Item(ITEM_ID_SPIDER_SILK, "Spider silk", "Spider silks", 1));
_items.Add(new Item(ITEM_ID_ADVENTURER_PASS, "Adventurer pass", "Adventurer passes", UNSELLABLE_ITEM_PRICE));
}
private static void PopulateMonsters()
{
Monster rat = new Monster(MONSTER_ID_RAT, "Rat", 5, 3, 10, 3, 3);
rat.LootTable.Add(new LootItem(ItemByID(ITEM_ID_RAT_TAIL), 75, false));
rat.LootTable.Add(new LootItem(ItemByID(ITEM_ID_PIECE_OF_FUR), 75, true));
Monster snake = new Monster(MONSTER_ID_SNAKE, "Snake", 5, 3, 10, 3, 3);
snake.LootTable.Add(new LootItem(ItemByID(ITEM_ID_SNAKE_FANG), 75, false));
snake.LootTable.Add(new LootItem(ItemByID(ITEM_ID_SNAKESKIN), 75, true));
Monster giantSpider = new Monster(MONSTER_ID_GIANT_SPIDER, "Giant spider", 20, 5, 40, 10, 10);
giantSpider.LootTable.Add(new LootItem(ItemByID(ITEM_ID_SPIDER_FANG), 75, true));
giantSpider.LootTable.Add(new LootItem(ItemByID(ITEM_ID_SPIDER_SILK), 25, false));
_monsters.Add(rat);
_monsters.Add(snake);
_monsters.Add(giantSpider);
}
private static void PopulateQuests()
{
Quest clearAlchemistGarden =
new Quest(
QUEST_ID_CLEAR_ALCHEMIST_GARDEN,
"Clear the alchemist's garden",
"Kill rats in the alchemist's garden and bring back 3 rat tails. You will receive a healing potion and 10 gold pieces.", 20, 10);
clearAlchemistGarden.QuestCompletionItems.Add(new QuestCompletionItem(ItemByID(ITEM_ID_RAT_TAIL), 3));
clearAlchemistGarden.RewardItem = ItemByID(ITEM_ID_HEALING_POTION);
Quest clearFarmersField =
new Quest(
QUEST_ID_CLEAR_FARMERS_FIELD,
"Clear the farmer's field",
"Kill snakes in the farmer's field and bring back 3 snake fangs. You will receive an adventurer's pass and 20 gold pieces.", 20, 20);
clearFarmersField.QuestCompletionItems.Add(new QuestCompletionItem(ItemByID(ITEM_ID_SNAKE_FANG), 3));
clearFarmersField.RewardItem = ItemByID(ITEM_ID_ADVENTURER_PASS);
_quests.Add(clearAlchemistGarden);
_quests.Add(clearFarmersField);
}
private static void PopulateLocations()
{
// Create each location
Location home = new Location(LOCATION_ID_HOME, "Home", "Your house. You really need to clean up the place.");
Location townSquare = new Location(LOCATION_ID_TOWN_SQUARE, "Town square", "You see a fountain.");
Vendor bobTheRatCatcher = new Vendor("Bob the Rat-Catcher");
bobTheRatCatcher.AddItemToInventory(ItemByID(ITEM_ID_PIECE_OF_FUR), 5);
bobTheRatCatcher.AddItemToInventory(ItemByID(ITEM_ID_RAT_TAIL), 3);
townSquare.VendorWorkingHere = bobTheRatCatcher;
Location alchemistHut = new Location(LOCATION_ID_ALCHEMIST_HUT, "Alchemist's hut", "There are many strange plants on the shelves.");
alchemistHut.QuestAvailableHere = QuestByID(QUEST_ID_CLEAR_ALCHEMIST_GARDEN);
Location alchemistsGarden = new Location(LOCATION_ID_ALCHEMISTS_GARDEN, "Alchemist's garden", "Many plants are growing here.");
alchemistsGarden.AddMonster(MONSTER_ID_RAT, 100);
Location farmhouse = new Location(LOCATION_ID_FARMHOUSE, "Farmhouse", "There is a small farmhouse, with a farmer in front.");
farmhouse.QuestAvailableHere = QuestByID(QUEST_ID_CLEAR_FARMERS_FIELD);
Location farmersField = new Location(LOCATION_ID_FARM_FIELD, "Farmer's field", "You see rows of vegetables growing here.");
farmersField.AddMonster(MONSTER_ID_SNAKE, 100);
Location guardPost = new Location(LOCATION_ID_GUARD_POST, "Guard post", "There is a large, tough-looking guard here.", ItemByID(ITEM_ID_ADVENTURER_PASS));
Location bridge = new Location(LOCATION_ID_BRIDGE, "Bridge", "A stone bridge crosses a wide river.");
Location spiderField = new Location(LOCATION_ID_SPIDER_FIELD, "Forest", "You see spider webs covering covering the trees in this forest.");
spiderField.AddMonster(MONSTER_ID_GIANT_SPIDER, 100);
// Link the locations together
home.LocationToNorth = townSquare;
townSquare.LocationToNorth = alchemistHut;
townSquare.LocationToSouth = home;
townSquare.LocationToEast = guardPost;
townSquare.LocationToWest = farmhouse;
farmhouse.LocationToEast = townSquare;
farmhouse.LocationToWest = farmersField;
farmersField.LocationToEast = farmhouse;
alchemistHut.LocationToSouth = townSquare;
alchemistHut.LocationToNorth = alchemistsGarden;
alchemistsGarden.LocationToSouth = alchemistHut;
guardPost.LocationToEast = bridge;
guardPost.LocationToWest = townSquare;
bridge.LocationToWest = guardPost;
bridge.LocationToEast = spiderField;
spiderField.LocationToWest = bridge;
// Add the locations to the static list
_locations.Add(home);
_locations.Add(townSquare);
_locations.Add(guardPost);
_locations.Add(alchemistHut);
_locations.Add(alchemistsGarden);
_locations.Add(farmhouse);
_locations.Add(farmersField);
_locations.Add(bridge);
_locations.Add(spiderField);
}
public static Item ItemByID(int id)
{
return _items.SingleOrDefault(x => x.ID == id);
}
public static Monster MonsterByID(int id)
{
return _monsters.SingleOrDefault(x => x.ID == id);
}
public static Quest QuestByID(int id)
{
return _quests.SingleOrDefault(x => x.ID == id);
}
public static Location LocationByID(int id)
{
return _locations.SingleOrDefault(x => x.ID == id);
}
}
}
| 412 | 0.852988 | 1 | 0.852988 | game-dev | MEDIA | 0.814785 | game-dev | 0.80321 | 1 | 0.80321 |
blurite/rsprox | 1,157 | protocol/src/main/kotlin/net/rsprox/protocol/game/outgoing/model/info/playerinfo/util/LowResolutionPosition.kt | package net.rsprox.protocol.game.outgoing.model.info.playerinfo.util
import net.rsprox.protocol.common.CoordGrid
@JvmInline
public value class LowResolutionPosition(
public val packed: Int,
) {
public val x: Int
get() = packed ushr 8 and 0xFF
public val z: Int
get() = packed and 0xFF
public val level: Int
get() = packed ushr 16 and 0x3
}
/**
* A fake constructor for the low resolution position value class, as the JVM signature
* matches that of the primary constructor.
* @param coordGrid the absolute coordinate to turn into a low resolution position.
* @return the low resolution representation of the given [coordGrid]
*/
public fun LowResolutionPosition(coordGrid: CoordGrid): LowResolutionPosition {
return LowResolutionPosition(
(coordGrid.z ushr 13)
.or((coordGrid.x ushr 13) shl 8)
.or((coordGrid.level shl 16)),
)
}
public fun LowResolutionPosition(
lowResX: Int,
lowResZ: Int,
level: Int,
): LowResolutionPosition {
return LowResolutionPosition(
(lowResZ)
.or((lowResX) shl 8)
.or((level shl 16)),
)
}
| 412 | 0.891267 | 1 | 0.891267 | game-dev | MEDIA | 0.516429 | game-dev | 0.766564 | 1 | 0.766564 |
CyberdyneCC/Thermos | 2,123 | patches/net/minecraft/item/ItemLilyPad.java.patch | --- ../src-base/minecraft/net/minecraft/item/ItemLilyPad.java
+++ ../src-work/minecraft/net/minecraft/item/ItemLilyPad.java
@@ -48,7 +48,17 @@
{
// special case for handling block placement with water lilies
net.minecraftforge.common.util.BlockSnapshot blocksnapshot = net.minecraftforge.common.util.BlockSnapshot.getBlockSnapshot(p_77659_2_, i, j + 1, k);
+ // Cauldron start - special case for handling block placement with water lilies
+ org.bukkit.block.BlockState blockstate = org.bukkit.craftbukkit.block.CraftBlockState.getBlockState(p_77659_2_, i, j + 1, k);
p_77659_2_.setBlock(i, j + 1, k, Blocks.waterlily);
+ org.bukkit.event.block.BlockPlaceEvent placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPlaceEvent(p_77659_2_,
+ p_77659_3_, blockstate, i, j, k);
+ if (placeEvent != null && (placeEvent.isCancelled() || !placeEvent.canBuild()))
+ {
+ blockstate.update(true, false);
+ return p_77659_1_;
+ }
+ // Cauldron end
if (net.minecraftforge.event.ForgeEventFactory.onPlayerBlockPlace(p_77659_3_, blocksnapshot, net.minecraftforge.common.util.ForgeDirection.UP).isCanceled())
{
blocksnapshot.restore(true, false);
@@ -66,6 +76,15 @@
}
}
+ // Cauldron start
+ public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8,
+ float par9, float par10)
+ {
+ cpw.mods.fml.relauncher.FMLRelaunchLog.info("onItemUse par1ItemStack = " + par1ItemStack);
+ return super.onItemUse(par1ItemStack, par2EntityPlayer, par3World, par4, par5, par6, par7, par8, par9, par10);
+ }
+ // Cauldron end
+
@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack p_82790_1_, int p_82790_2_)
{
| 412 | 0.78402 | 1 | 0.78402 | game-dev | MEDIA | 0.9962 | game-dev | 0.60589 | 1 | 0.60589 |
magefree/mage | 2,203 | Mage.Sets/src/mage/cards/m/MartyrOfFrost.java |
package mage.cards.m;
import java.util.UUID;
import mage.MageInt;
import mage.ObjectColor;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.RevealTargetFromHandCost;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.dynamicvalue.common.RevealTargetFromHandCostCount;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.CounterUnlessPaysEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.filter.predicate.mageobject.ColorPredicate;
import mage.target.TargetSpell;
import mage.target.common.TargetCardInHand;
/**
*
* @author emerald000
*/
public final class MartyrOfFrost extends CardImpl {
private static final FilterCard filter = new FilterCard("X blue cards from your hand");
static {
filter.add(new ColorPredicate(ObjectColor.BLUE));
}
public MartyrOfFrost(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// {2}, Reveal X blue cards from your hand, Sacrifice Martyr of Frost: Counter target spell unless its controller pays {X}.
Effect effect = new CounterUnlessPaysEffect(RevealTargetFromHandCostCount.instance);
effect.setText("Counter target spell unless its controller pays {X}.");
Ability ability = new SimpleActivatedAbility(effect, new GenericManaCost(2));
ability.addCost(new RevealTargetFromHandCost(new TargetCardInHand(0, Integer.MAX_VALUE, filter)));
ability.addCost(new SacrificeSourceCost());
ability.addTarget(new TargetSpell());
this.addAbility(ability);
}
private MartyrOfFrost(final MartyrOfFrost card) {
super(card);
}
@Override
public MartyrOfFrost copy() {
return new MartyrOfFrost(this);
}
}
| 412 | 0.898616 | 1 | 0.898616 | game-dev | MEDIA | 0.968217 | game-dev | 0.970353 | 1 | 0.970353 |
cedrickchee/pytorch-android | 7,571 | app/src/main/cpp/c10/impl/InlineStreamGuard.h | #pragma once
#include <c10/impl/InlineDeviceGuard.h>
namespace c10 {
namespace impl {
/**
* A StreamGuard is an RAII class that changes the current device
* to the device corresponding to some stream, and changes the
* default stream on that device to be this stream.
*
* InlineStreamGuard is a helper class for implementing StreamGuards.
* See InlineDeviceGuard for guidance on how to use this class.
*/
template <typename T>
class InlineStreamGuard : private InlineDeviceGuard<T> {
public:
/// No default constructor, see Note [Omitted default constructor from RAII]
explicit InlineStreamGuard() = delete;
/// Set the current device to the device associated with the passed stream,
/// and set the current stream on that device to the passed stream.
explicit InlineStreamGuard(Stream stream)
: InlineDeviceGuard<T>(stream.device())
, original_stream_of_original_device_(this->impl_.getStream(original_device()))
, original_stream_of_current_device_(this->impl_.exchangeStream(stream))
, current_stream_(stream)
{}
/// This constructor exists purely for testing
template <typename U=T, typename=typename std::enable_if<std::is_same<U, VirtualGuardImpl>::value>::type>
explicit InlineStreamGuard(Stream stream, const DeviceGuardImplInterface* impl)
: InlineDeviceGuard<T>(stream.device(), impl ? impl : getDeviceGuardImpl(stream.device_type()))
, original_stream_of_original_device_(this->impl_.getStream(original_device()))
, original_stream_of_current_device_(this->impl_.exchangeStream(stream))
, current_stream_(stream)
{}
/// Copy is disallowed
InlineStreamGuard(const InlineStreamGuard<T>&) = delete;
InlineStreamGuard<T>& operator=(const InlineStreamGuard<T>&) = delete;
/// Move is disallowed, as StreamGuard does not have an uninitialized state,
/// which is required for moves on types with nontrivial destructors.
InlineStreamGuard(InlineStreamGuard<T>&& other) = delete;
InlineStreamGuard& operator=(InlineStreamGuard<T>&& other) = delete;
~InlineStreamGuard() {
this->impl_.exchangeStream(original_stream_of_current_device_);
}
/// Resets the currently set stream to the original stream and
/// the currently set device to the original device. Then,
/// set the current device to the device associated with the passed stream,
/// and set the current stream on that device to the passed stream.
///
/// NOTE: this implementation may skip some stream/device setting if
/// it can prove that it is unnecessary.
///
/// WARNING: reset_stream does NOT preserve previously set streams on
/// different devices. If you need to set streams on multiple devices
/// on CUDA, use CUDAMultiStreamGuard instead.
void reset_stream(Stream stream) {
// TODO: make a version that takes an impl argument. Unfortunately,
// that will require SFINAE because impl is only valid for the
// VirtualGuardImpl specialization.
if (stream.device() == this->current_device()) {
this->impl_.exchangeStream(stream);
current_stream_ = stream;
} else {
// Destruct and reconstruct the StreamGuard in-place
this->impl_.exchangeStream(original_stream_of_current_device_);
this->reset_device(stream.device());
original_stream_of_current_device_ = this->impl_.exchangeStream(stream);
current_stream_ = stream;
}
}
// It's not clear if set_device should also reset the current stream
// if the device is unchanged; therefore, we don't provide it.
// The situation is somewhat clearer with reset_device, but it's still
// a pretty weird thing to do, so haven't added this either.
/// Returns the stream of the original device prior to this guard. Subtly,
/// the stream returned here is the original stream of the *original*
/// device; i.e., it's the stream that your computation *would* have
/// been put on, if it hadn't been for this meddling stream guard.
/// This is usually what you want.
Stream original_stream() const {
return original_stream_of_original_device_;
}
/// Returns the most recent stream that was set using this device guard,
/// either from construction, or via set_stream.
Stream current_stream() const {
return current_stream_;
}
/// Returns the most recent device that was set using this device guard,
/// either from construction, or via set_device/reset_device/set_index.
Device current_device() const {
return InlineDeviceGuard<T>::current_device();
}
/// Returns the device that was set at the most recent reset_stream(),
/// or otherwise the device at construction time.
Device original_device() const {
return InlineDeviceGuard<T>::original_device();
}
private:
Stream original_stream_of_original_device_; // what the user probably cares about
Stream original_stream_of_current_device_; // what we need to restore
Stream current_stream_;
};
/**
* An OptionalStreamGuard is an RAII class that sets a device to some value on
* initialization, and resets the device to its original value on destruction.
* See InlineOptionalDeviceGuard for more guidance on how to use this class.
*/
template <typename T>
class InlineOptionalStreamGuard {
public:
/// Creates an uninitialized stream guard.
explicit InlineOptionalStreamGuard()
: guard_() // See Note [Explicit initialization of optional fields]
{}
/// Set the current device to the device associated with the passed stream,
/// and set the current stream on that device to the passed stream,
/// if the passed stream is not nullopt.
explicit InlineOptionalStreamGuard(optional<Stream> stream_opt)
: guard_() {
if (stream_opt.has_value()) {
guard_.emplace(stream_opt.value());
}
}
/// All constructors of StreamGuard are valid for OptionalStreamGuard
template <typename... Args>
explicit InlineOptionalStreamGuard(Args&&... args)
: guard_(in_place, std::forward<Args>(args)...) {}
// See Note [Move construction for RAII guards is tricky]
InlineOptionalStreamGuard(InlineOptionalStreamGuard<T>&& other) = delete;
// See Note [Move assignment for RAII guards is tricky]
InlineOptionalStreamGuard& operator=(InlineOptionalStreamGuard&& other) = delete;
/// Resets the currently set stream to the original stream and
/// the currently set device to the original device. Then,
/// set the current device to the device associated with the passed stream,
/// and set the current stream on that device to the passed stream.
/// Initializes the OptionalStreamGuard if it was not previously initialized.
void reset_stream(Stream stream) {
if (guard_.has_value()) {
guard_->reset_stream(stream);
} else {
guard_.emplace(stream);
}
}
/// Returns the stream that was set at the time the guard was most recently
/// initialized, or nullopt if the guard is uninitialized.
optional<Stream> original_stream() const {
return guard_.has_value() ? make_optional(guard_->original_stream()) : nullopt;
}
/// Returns the most recent stream that was set using this stream guard,
/// either from construction, or via reset_stream, if the guard is initialized,
/// or nullopt if the guard is uninitialized.
optional<Stream> current_stream() const {
return guard_.has_value() ? make_optional(guard_->current_stream()) : nullopt;
}
/// Restore the original device and stream, resetting this guard to uninitialized state.
void reset() {
guard_.reset();
}
private:
optional<InlineStreamGuard<T>> guard_;
};
}} // namespace c10::impl
| 412 | 0.921841 | 1 | 0.921841 | game-dev | MEDIA | 0.234651 | game-dev | 0.84684 | 1 | 0.84684 |
klikli-dev/occultism | 2,092 | src/main/java/com/klikli_dev/occultism/common/entity/job/RainWeatherJob.java | /*
* MIT License
*
* Copyright 2020 klikli-dev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.klikli_dev.occultism.common.entity.job;
import com.klikli_dev.occultism.Occultism;
import com.klikli_dev.occultism.common.entity.spirit.SpiritEntity;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import java.util.function.Supplier;
public class RainWeatherJob extends ChangeWeatherJob {
public static final int RAIN_DURATION = 6000;
public RainWeatherJob(SpiritEntity entity, Supplier<Integer> ticksToClear) {
super(entity, ticksToClear);
}
public void changeWeather() {
if (Occultism.SERVER_CONFIG.rituals.enableRainWeatherRitual.get()) {
var level = (ServerLevel) this.entity.level();
level.setWeatherParameters(0, getDuration(level.getRandom(), RAIN_DURATION, ServerLevel.RAIN_DURATION), true, false);
} else {
this.entity.getOwner().sendSystemMessage(Component.translatable("ritual.occultism.disabled"));
}
}
}
| 412 | 0.537024 | 1 | 0.537024 | game-dev | MEDIA | 0.34494 | game-dev | 0.57191 | 1 | 0.57191 |
rooch-network/rooch | 1,664 | crates/rooch/src/commands/bitseed/mod.rs | // Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0
use crate::cli_types::CommandAction;
use async_trait::async_trait;
use rooch_types::error::RoochResult;
pub mod commands;
pub mod generator;
pub mod inscribe;
pub mod inscription;
pub mod operation;
pub mod sft;
pub const PROTOCOL: &str = "bitseed";
pub const METADATA_OP: &str = "op";
pub const METADATA_TICK: &str = "tick";
pub const METADATA_AMOUNT: &str = "amount";
pub const METADATA_ATTRIBUTES: &str = "attributes";
pub const GENERATOR_TICK: &str = "generator";
/// Tool for interacting with bitseed protocol
#[derive(clap::Parser)]
pub struct Bitseed {
#[clap(subcommand)]
cmd: BitseedCommand,
}
#[async_trait]
impl CommandAction<String> for Bitseed {
async fn execute(self) -> RoochResult<String> {
match self.cmd {
BitseedCommand::Generator(generator) => generator.execute_serialized().await,
BitseedCommand::Deploy(deploy) => deploy.execute_serialized().await,
BitseedCommand::Mint(mint) => mint.execute_serialized().await,
BitseedCommand::Split(split) => split.execute_serialized().await,
BitseedCommand::Merge(merge) => merge.execute_serialized().await,
BitseedCommand::View(view) => view.execute_serialized().await,
}
}
}
#[derive(Debug, clap::Subcommand)]
#[clap(name = "bitseed")]
pub enum BitseedCommand {
Generator(commands::generator::GeneratorCommand),
Deploy(commands::deploy::DeployCommand),
Mint(commands::mint::MintCommand),
Split(commands::split::SplitCommand),
Merge(commands::merge::MergeCommand),
View(commands::view::ViewCommand),
}
| 412 | 0.777773 | 1 | 0.777773 | game-dev | MEDIA | 0.296307 | game-dev | 0.836287 | 1 | 0.836287 |
Vulcalien/minicraft-gba | 5,801 | src/entity.c | /* Copyright 2022 Vulcalien
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "entity.h"
#include "level.h"
#include "tile.h"
#include "mob.h"
IWRAM_RODATA_SECTION
const struct Entity * const entity_list[ENTITY_TYPES] = {
&zombie_entity,
&slime_entity,
&air_wizard_entity,
&player_entity,
&workbench_entity,
&furnace_entity,
&oven_entity,
&anvil_entity,
&chest_entity,
&lantern_entity,
&item_entity,
&spark_entity,
&text_particle_entity,
&smash_particle_entity
};
IWRAM_SECTION
bool entity_move(struct Level *level, struct entity_Data *data,
i32 xm, i32 ym) {
if(xm == 0 && ym == 0)
return true;
bool stopped = true;
if(xm != 0 && entity_move2(level, data, xm, 0))
stopped = false;
if(ym != 0 && entity_move2(level, data, 0, ym))
stopped = false;
if(!stopped) {
i32 xt = data->x >> 4;
i32 yt = data->y >> 4;
const struct Tile *tile = LEVEL_GET_TILE_S(level, xt, yt);
if(tile->stepped_on)
tile->stepped_on(level, xt, yt, data);
}
return !stopped;
}
IWRAM_SECTION
bool entity_move2(struct Level *level, struct entity_Data *data,
i32 xm, i32 ym) {
const struct Entity *entity = ENTITY_S(data);
u32 tiles_to_check;
i32 tiles[2][2];
i32 xto0 = (data->x - entity->xr) >> 4;
i32 yto0 = (data->y - entity->yr) >> 4;
i32 xto1 = (data->x + entity->xr) >> 4;
i32 yto1 = (data->y + entity->yr) >> 4;
i32 xt0 = (data->x + xm - entity->xr) >> 4;
i32 yt0 = (data->y + ym - entity->yr) >> 4;
i32 xt1 = (data->x + xm + entity->xr) >> 4;
i32 yt1 = (data->y + ym + entity->yr) >> 4;
if(xm < 0) {
tiles[0][0] = xt0; tiles[0][1] = yt0;
tiles[1][0] = xt0; tiles[1][1] = yt1;
tiles_to_check = (xt0 != xto0) * (1 + (yt0 != yt1));
} else if(xm > 0) {
tiles[0][0] = xt1; tiles[0][1] = yt0;
tiles[1][0] = xt1; tiles[1][1] = yt1;
tiles_to_check = (xt1 != xto1) * (1 + (yt0 != yt1));
} else if(ym < 0) {
tiles[0][0] = xt0; tiles[0][1] = yt0;
tiles[1][0] = xt1; tiles[1][1] = yt0;
tiles_to_check = (yt0 != yto0) * (1 + (xt0 != xt1));
} else {
tiles[0][0] = xt0; tiles[0][1] = yt1;
tiles[1][0] = xt1; tiles[1][1] = yt1;
tiles_to_check = (yt1 != yto1) * (1 + (xt0 != xt1));
}
for(u32 i = 0; i < tiles_to_check; i++) {
const i32 *t = tiles[i];
const struct Tile *tile = LEVEL_GET_TILE_S(level, t[0], t[1]);
if(tile->touch_damage && (data->type == ZOMBIE_ENTITY ||
data->type == SLIME_ENTITY ||
data->type == PLAYER_ENTITY)) {
struct mob_Data *mob_data = (struct mob_Data *) &data->data;
mob_hurt(level, data, tile->touch_damage, mob_data->dir ^ 2);
}
if(tile->is_solid && tile->may_pass != data->type)
return false;
}
// solid entity collision
xt0--;
yt0--;
xt1++;
yt1++;
if(xt0 < 0) xt0 = 0;
if(yt0 < 0) yt0 = 0;
if(xt1 >= LEVEL_W) xt1 = LEVEL_W - 1;
if(yt1 >= LEVEL_H) yt1 = LEVEL_H - 1;
i32 xo0 = data->x - entity->xr;
i32 yo0 = data->y - entity->yr;
i32 xo1 = data->x + entity->xr;
i32 yo1 = data->y + entity->yr;
i32 x0 = data->x + xm - entity->xr;
i32 y0 = data->y + ym - entity->yr;
i32 x1 = data->x + xm + entity->xr;
i32 y1 = data->y + ym + entity->yr;
bool blocked_by_entity = false;
for(u32 yt = yt0; yt <= yt1; yt++) {
for(u32 xt = xt0; xt <= xt1; xt++) {
const u32 tile = xt + yt * LEVEL_W;
for(u32 i = 0; i < SOLID_ENTITIES_IN_TILE; i++) {
const u8 entity_id = level_solid_entities[tile][i];
if(entity_id >= ENTITY_LIMIT)
continue;
struct entity_Data *e_data = &level->entities[entity_id];
if(e_data == data)
continue;
if(entity_intersects(e_data, x0, y0, x1, y1)) {
if(!blocked_by_entity)
if(!entity_intersects(e_data, xo0, yo0, xo1, yo1))
blocked_by_entity = true;
// item entity doesn't have a touch_player function
if(data->type == ITEM_ENTITY) {
if(blocked_by_entity)
return false;
else
continue;
}
// touch player
if(data->type == PLAYER_ENTITY) {
const struct Entity *entity = ENTITY_S(e_data);
entity->touch_player(level, e_data, data);
} else if(e_data->type == PLAYER_ENTITY) {
const struct Entity *entity = ENTITY_S(data);
entity->touch_player(level, data, e_data);
}
}
}
}
}
if(blocked_by_entity)
return false;
data->x += xm;
data->y += ym;
return true;
}
| 412 | 0.944351 | 1 | 0.944351 | game-dev | MEDIA | 0.902597 | game-dev | 0.972822 | 1 | 0.972822 |
rotators/fo2238 | 7,318 | Server/extensions/3rdParty/angelscript/source/as_objecttype.h | /*
AngelCode Scripting Library
Copyright (c) 2003-2013 Andreas Jonsson
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.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_objecttype.h
//
// A class for storing object type information
//
#ifndef AS_OBJECTTYPE_H
#define AS_OBJECTTYPE_H
#include "as_atomic.h"
#include "as_string.h"
#include "as_property.h"
#include "as_array.h"
#include "as_scriptfunction.h"
BEGIN_AS_NAMESPACE
// TODO: memory: Need to minimize used memory here, because not all types use all properties of the class
// TODO: The type id should have flags for diferenciating between value types and reference types. It should also have a flag for differenciating interface types.
// Additional flag to the class object type
const asDWORD asOBJ_IMPLICIT_HANDLE = 0x00400000;
const asDWORD asOBJ_TYPEDEF = 0x40000000;
const asDWORD asOBJ_ENUM = 0x10000000;
const asDWORD asOBJ_TEMPLATE_SUBTYPE = 0x20000000;
// asOBJ_GC is used to indicate that the type can potentially
// form circular references, thus is garbage collected.
// The fact that an object is garbage collected doesn't imply that an other object
// that can reference it also must be garbage collected, only if the garbage collected
// object can reference the other object as well.
// For registered types however, we set the flag asOBJ_GC if the GC
// behaviours are registered. For script types that contain any such type we
// automatically make garbage collected as well, because we cannot know what type
// of references that object can contain, and must assume the worst.
struct asSTypeBehaviour
{
asSTypeBehaviour()
{
factory = 0;
listFactory = 0;
copyfactory = 0;
construct = 0;
copyconstruct = 0;
destruct = 0;
copy = 0;
addref = 0;
release = 0;
gcGetRefCount = 0;
gcSetFlag = 0;
gcGetFlag = 0;
gcEnumReferences = 0;
gcReleaseAllReferences = 0;
templateCallback = 0;
}
int factory;
int listFactory; // Used for initialization lists only
int copyfactory;
int construct;
int copyconstruct;
int destruct;
int copy;
int addref;
int release;
int templateCallback;
// GC behaviours
int gcGetRefCount;
int gcSetFlag;
int gcGetFlag;
int gcEnumReferences;
int gcReleaseAllReferences;
asCArray<int> factories;
asCArray<int> constructors;
asCArray<int> operators;
};
struct asSEnumValue
{
asCString name;
int value;
};
class asCScriptEngine;
struct asSNameSpace;
void RegisterObjectTypeGCBehaviours(asCScriptEngine *engine);
class asCObjectType : public asIObjectType
{
public:
//=====================================
// From asIObjectType
//=====================================
asIScriptEngine *GetEngine() const;
const char *GetConfigGroup() const;
asDWORD GetAccessMask() const;
// Memory management
int AddRef() const;
int Release() const;
// Type info
const char *GetName() const;
const char *GetNamespace() const;
asIObjectType *GetBaseType() const;
bool DerivesFrom(const asIObjectType *objType) const;
asDWORD GetFlags() const;
asUINT GetSize() const;
int GetTypeId() const;
int GetSubTypeId(asUINT subtypeIndex = 0) const;
asIObjectType *GetSubType(asUINT subtypeIndex = 0) const;
asUINT GetSubTypeCount() const;
// Interfaces
asUINT GetInterfaceCount() const;
asIObjectType *GetInterface(asUINT index) const;
bool Implements(const asIObjectType *objType) const;
// Factories
asUINT GetFactoryCount() const;
#ifdef AS_DEPRECATED
// Deprecated since 2.24.0 - 2012-05-25
int GetFactoryIdByIndex(asUINT index) const;
int GetFactoryIdByDecl(const char *decl) const;
#endif
asIScriptFunction *GetFactoryByIndex(asUINT index) const;
asIScriptFunction *GetFactoryByDecl(const char *decl) const;
// Methods
asUINT GetMethodCount() const;
#ifdef AS_DEPRECATED
// Deprecated since 2.24.0 - 2012-05-25
int GetMethodIdByIndex(asUINT index, bool getVirtual) const;
int GetMethodIdByName(const char *name, bool getVirtual) const;
int GetMethodIdByDecl(const char *decl, bool getVirtual) const;
#endif
asIScriptFunction *GetMethodByIndex(asUINT index, bool getVirtual) const;
asIScriptFunction *GetMethodByName(const char *name, bool getVirtual) const;
asIScriptFunction *GetMethodByDecl(const char *decl, bool getVirtual) const;
// Properties
asUINT GetPropertyCount() const;
int GetProperty(asUINT index, const char **name, int *typeId, bool *isPrivate, int *offset, bool *isReference, asDWORD *accessMask) const;
const char *GetPropertyDeclaration(asUINT index) const;
// Behaviours
asUINT GetBehaviourCount() const;
asIScriptFunction *GetBehaviourByIndex(asUINT index, asEBehaviours *outBehaviour) const;
// User data
void *SetUserData(void *data, asPWORD type);
void *GetUserData(asPWORD type) const;
//===========================================
// Internal
//===========================================
public:
asCObjectType(asCScriptEngine *engine);
~asCObjectType();
void Orphan(asCModule *module);
int GetRefCount();
void SetGCFlag();
bool GetGCFlag();
void EnumReferences(asIScriptEngine *);
void ReleaseAllHandles(asIScriptEngine *);
void ReleaseAllFunctions();
bool IsInterface() const;
bool IsShared() const;
asCObjectProperty *AddPropertyToClass(const asCString &name, const asCDataType &dt, bool isPrivate);
void ReleaseAllProperties();
asCString name;
asSNameSpace *nameSpace;
int size;
asCArray<asCObjectProperty*> properties;
asCArray<int> methods;
asCArray<asCObjectType*> interfaces;
asCArray<asSEnumValue*> enumValues;
asCObjectType * derivedFrom;
asCArray<asCScriptFunction*> virtualFunctionTable;
asDWORD flags;
asDWORD accessMask;
asSTypeBehaviour beh;
// Used for template types
asCArray<asCDataType> templateSubTypes;
bool acceptValueSubType;
bool acceptRefSubType;
asCScriptEngine *engine;
asCModule *module;
asCArray<asPWORD> userData;
protected:
friend class asCScriptEngine;
asCObjectType();
mutable asCAtomic refCount;
mutable bool gcFlag;
};
END_AS_NAMESPACE
#endif
| 412 | 0.89753 | 1 | 0.89753 | game-dev | MEDIA | 0.372797 | game-dev | 0.77273 | 1 | 0.77273 |
EphemeralSpace/ephemeral-space | 2,859 | Content.Server/Xenoarchaeology/Artifact/RandomArtifactSpriteSystem.cs | using Content.Shared.Item;
using Content.Shared.Xenoarchaeology.Artifact;
using Content.Shared.Xenoarchaeology.XenoArtifacts;
using Robust.Server.GameObjects;
using Robust.Shared.Random;
using Robust.Shared.Timing;
namespace Content.Server.Xenoarchaeology.Artifact;
public sealed class RandomArtifactSpriteSystem : EntitySystem
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IGameTiming _time = default!;
[Dependency] private readonly AppearanceSystem _appearance = default!;
[Dependency] private readonly SharedItemSystem _item = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<RandomArtifactSpriteComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<RandomArtifactSpriteComponent, ArtifactUnlockingStartedEvent>(UnlockingStageStarted);
SubscribeLocalEvent<RandomArtifactSpriteComponent, ArtifactUnlockingFinishedEvent>(UnlockingStageFinished);
SubscribeLocalEvent<RandomArtifactSpriteComponent, XenoArtifactActivatedEvent>(ArtifactActivated);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<RandomArtifactSpriteComponent, AppearanceComponent>();
while (query.MoveNext(out var uid, out var component, out var appearance))
{
if (component.ActivationStart == null)
continue;
var timeDif = _time.CurTime - component.ActivationStart.Value;
if (timeDif.Seconds >= component.ActivationTime)
{
_appearance.SetData(uid, SharedArtifactsVisuals.IsActivated, false, appearance);
component.ActivationStart = null;
}
}
}
private void OnMapInit(EntityUid uid, RandomArtifactSpriteComponent component, MapInitEvent args)
{
var randomSprite = _random.Next(component.MinSprite, component.MaxSprite + 1);
_appearance.SetData(uid, SharedArtifactsVisuals.SpriteIndex, randomSprite);
_item.SetHeldPrefix(uid, "ano" + randomSprite.ToString("D2")); //set item artifact inhands
}
private void UnlockingStageStarted(Entity<RandomArtifactSpriteComponent> ent, ref ArtifactUnlockingStartedEvent args)
{
_appearance.SetData(ent, SharedArtifactsVisuals.IsUnlocking, true);
}
private void UnlockingStageFinished(Entity<RandomArtifactSpriteComponent> ent, ref ArtifactUnlockingFinishedEvent args)
{
_appearance.SetData(ent, SharedArtifactsVisuals.IsUnlocking, false);
}
private void ArtifactActivated(Entity<RandomArtifactSpriteComponent> ent, ref XenoArtifactActivatedEvent args)
{
_appearance.SetData(ent, SharedArtifactsVisuals.IsActivated, true);
ent.Comp.ActivationStart = _time.CurTime;
}
}
| 412 | 0.938229 | 1 | 0.938229 | game-dev | MEDIA | 0.902966 | game-dev | 0.876791 | 1 | 0.876791 |
mmusiienko/the_greatest_shaman_forge_1.20.2 | 1,588 | src/main/java/com/the_greatest_shaman/entity/renderer/RedskinRenderer.java | package com.the_greatest_shaman.entity.renderer;
import com.mojang.blaze3d.vertex.PoseStack;
import com.the_greatest_shaman.entity.mob.AbstractRedskin;
import com.the_greatest_shaman.entity.model.ModMobModelLayers;
import com.the_greatest_shaman.entity.model.RedskinModel;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.entity.MobRenderer;
import net.minecraft.client.renderer.entity.layers.CustomHeadLayer;
import net.minecraft.client.renderer.entity.layers.ItemInHandLayer;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
public class RedskinRenderer extends MobRenderer<AbstractRedskin, RedskinModel<AbstractRedskin>> {
public RedskinRenderer(EntityRendererProvider.Context pContext) {
super(pContext, new RedskinModel<>(pContext.bakeLayer(ModMobModelLayers.REDSKIN_LAYER)), 0.45f);
this.addLayer(new ItemInHandLayer<>(this, pContext.getItemInHandRenderer()));
this.addLayer(new CustomHeadLayer<>(this, pContext.getModelSet() ,pContext.getItemInHandRenderer()));
}
@Override
public @NotNull ResourceLocation getTextureLocation(@NotNull AbstractRedskin pEntity) {
return pEntity.getTextureLocation();
}
@Override
public void render(AbstractRedskin pEntity, float pEntityYaw, float pPartialTicks, PoseStack pPoseStack, MultiBufferSource pBuffer, int pPackedLight) {
super.render(pEntity, pEntityYaw, pPartialTicks, pPoseStack, pBuffer, pPackedLight);
}
} | 412 | 0.724573 | 1 | 0.724573 | game-dev | MEDIA | 0.849138 | game-dev,graphics-rendering | 0.921109 | 1 | 0.921109 |
polyml/polyml | 2,292 | libpolyml/machoexport.h | /*
Title: Export memory as a Mach object file
Author: David C. J. Matthews.
Copyright (c) 2006, 2016-18, 2020 David C. J. Matthews
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR H PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MachExport_H_INCLUDED
#define MachExport_H_INCLUDED
#include "config.h"
#include "scanaddrs.h" // For base class
#include "exporter.h"
#include <mach-o/reloc.h>
class MachoExport: public Exporter, public ScanAddress
{
public:
MachoExport(): relocationCount(0), symbolNum(0) {}
public:
virtual void exportStore(void);
private:
// ScanAddress overrides
virtual void ScanConstant(PolyObject *base, byte *addrOfConst, ScanRelocationKind code, intptr_t displacement);
// At the moment we should only get calls to ScanConstant.
virtual PolyObject *ScanObjectAddress(PolyObject *base) { return base; }
virtual void addExternalReference(void *addr, const char *name, bool isFuncPtr);
virtual void RelocateOnly(PolyObject* base, byte* addressOfConstant, ScanRelocationKind code)
{
ScanConstant(base, addressOfConstant, code, 0);
}
private:
void setRelocationAddress(void *p, int32_t *reloc);
PolyWord createRelocation(PolyWord p, void *relocAddr);
PolyWord writeRelocation(POLYUNSIGNED offset, void *relocAddr, unsigned symbolNumber, bool isExtern);
void alignFile(int align);
void createStructsRelocation(unsigned area, size_t offset);
void adjustOffset(unsigned area, size_t &offset);
unsigned relocationCount;
ExportStringTable stringTable;
// Table and count for external references.
ExportStringTable externTable;
unsigned symbolNum;
};
#endif
| 412 | 0.874945 | 1 | 0.874945 | game-dev | MEDIA | 0.46226 | game-dev | 0.551835 | 1 | 0.551835 |
duaneking/BansheeEngine | 1,200 | BansheeEngine/Include/BsGUILayoutOptions.h | //__________________________ Banshee Project - A modern game development toolkit _________________________________//
//_____________________________________ www.banshee-project.com __________________________________________________//
//________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
#pragma once
#include "BsPrerequisites.h"
namespace BansheeEngine
{
/**
* @brief Options that control how an element is positioned and sized in a GUI layout.
*/
struct BS_EXPORT GUILayoutOptions
{
/**
* @brief Creates new default layout options.
*/
static GUILayoutOptions create();
/**
* @brief Creates layout options with user defined options.
*/
static GUILayoutOptions create(const GUIOptions& options);
GUILayoutOptions();
/**
* @brief Updates layout options from the provided style. If user has not manually
* set a specific layout property, that property will be inherited from style.
*/
void updateWithStyle(const GUIElementStyle* style);
UINT32 width, height;
UINT32 minWidth, maxWidth, minHeight, maxHeight;
bool fixedWidth, fixedHeight;
bool overridenWidth, overridenHeight;
};
} | 412 | 0.905286 | 1 | 0.905286 | game-dev | MEDIA | 0.51223 | game-dev,desktop-app | 0.550571 | 1 | 0.550571 |
godot-nim/gdext-nim | 10,346 | docs/gdext/othertools.idx | nimTitle othertools gdext/othertools.html module gdext/othertools 0
nim callable gdext/othertools.html#callable proc callable(): Callable 9
nim signal gdext/othertools.html#signal proc signal(): Signal 10
nim rid gdext/othertools.html#rid proc rid(): RID 12
nim rid gdext/othertools.html#rid,RID proc rid(from: RID): RID 13
nim callable gdext/othertools.html#callable,Callable proc callable(from: Callable): Callable 7
nim callable gdext/othertools.html#callable,Object,StringName proc callable(object: Object; method: StringName): Callable 10
nim signal gdext/othertools.html#signal,Signal proc signal(from: Signal): Signal 7
nim signal gdext/othertools.html#signal,Object,StringName proc signal(object: Object; signal: StringName): Signal 10
nim `not` gdext/othertools.html#not,Callable proc `not`(left: Callable): bool 8
nim `==` gdext/othertools.html#==,Callable,Callable proc `==`(left: Callable; right: Callable): bool 9
nim create gdext/othertools.html#create,typedesc[Callable],Variant,StringName proc create(_: typedesc[Callable]; variant: Variant; method: StringName): Callable 36
nim callv gdext/othertools.html#callv,Callable,Array proc callv(self: Callable; arguments: Array): Variant 39
nim isNull gdext/othertools.html#isNull,Callable proc isNull(self: Callable): bool 42
nim isCustom gdext/othertools.html#isCustom,Callable proc isCustom(self: Callable): bool 44
nim isStandard gdext/othertools.html#isStandard,Callable proc isStandard(self: Callable): bool 46
nim isValid gdext/othertools.html#isValid,Callable proc isValid(self: Callable): bool 48
nim getObject gdext/othertools.html#getObject,Callable proc getObject(self: Callable): Object 50
nim getObjectId gdext/othertools.html#getObjectId,Callable proc getObjectId(self: Callable): Int 52
nim getMethod gdext/othertools.html#getMethod,Callable proc getMethod(self: Callable): StringName 54
nim getArgumentCount gdext/othertools.html#getArgumentCount,Callable proc getArgumentCount(self: Callable): Int 56
nim getBoundArgumentsCount gdext/othertools.html#getBoundArgumentsCount,Callable proc getBoundArgumentsCount(self: Callable): Int 58
nim getBoundArguments gdext/othertools.html#getBoundArguments,Callable proc getBoundArguments(self: Callable): Array 60
nim getUnboundArgumentsCount gdext/othertools.html#getUnboundArgumentsCount,Callable proc getUnboundArgumentsCount(self: Callable): Int 62
nim hash gdext/othertools.html#hash,Callable proc hash(self: Callable): Hash 64
nim bindv gdext/othertools.html#bindv,Callable,Array proc bindv(self: var Callable; arguments: Array): Callable 66
nim unbind gdext/othertools.html#unbind,Callable,Int proc unbind(self: Callable; argcount: Int): Callable 69
nim call gdext/othertools.html#call,Callable,varargs[Variant,variant] proc call(self: Callable; args: varargs[Variant, variant]): Variant 72
nim callDeferred gdext/othertools.html#callDeferred,Callable,varargs[Variant,variant] proc callDeferred(self: Callable; args: varargs[Variant, variant]): void 78
nim rpc gdext/othertools.html#rpc,Callable,varargs[Variant,variant] proc rpc(self: Callable; args: varargs[Variant, variant]): void 84
nim rpcId gdext/othertools.html#rpcId,Callable,Int,varargs[Variant,variant] proc rpcId(self: Callable; peerId: Int; args: varargs[Variant, variant]): void 90
nim `bind` gdext/othertools.html#bind,Callable,varargs[Variant,variant] proc `bind`(self: Callable; args: varargs[Variant, variant]): Callable 98
nim `not` gdext/othertools.html#not,Signal proc `not`(left: Signal): bool 8
nim `==` gdext/othertools.html#==,Signal,Signal proc `==`(left: Signal; right: Signal): bool 9
nim isNull gdext/othertools.html#isNull,Signal proc isNull(self: Signal): bool 25
nim getObject gdext/othertools.html#getObject,Signal proc getObject(self: Signal): Object 27
nim getObjectId gdext/othertools.html#getObjectId,Signal proc getObjectId(self: Signal): Int 29
nim getName gdext/othertools.html#getName,Signal proc getName(self: Signal): StringName 31
nim connect gdext/othertools.html#connect,Signal,Callable,Int proc connect(self: var Signal; callable: Callable; flags: Int = 0): Int 33
nim disconnect gdext/othertools.html#disconnect,Signal,Callable proc disconnect(self: var Signal; callable: Callable): void 36
nim isConnected gdext/othertools.html#isConnected,Signal,Callable proc isConnected(self: Signal; callable: Callable): bool 39
nim getConnections gdext/othertools.html#getConnections,Signal proc getConnections(self: Signal): Array 42
nim hasConnections gdext/othertools.html#hasConnections,Signal proc hasConnections(self: Signal): bool 44
nim emit gdext/othertools.html#emit,Signal,varargs[Variant,variant] proc emit(self: Signal; args: varargs[Variant, variant]): void 46
nim `not` gdext/othertools.html#not,RID proc `not`(left: RID): bool 12
nim `==` gdext/othertools.html#==,RID,RID proc `==`(left: RID; right: RID): bool 13
nim `<` gdext/othertools.html#<,RID,RID proc `<`(left: RID; right: RID): bool 14
nim `<=` gdext/othertools.html#<=,RID,RID proc `<=`(left: RID; right: RID): bool 15
nim isValid gdext/othertools.html#isValid,RID proc isValid(self: RID): bool 25
nim getId gdext/othertools.html#getId,RID proc getId(self: RID): Int 27
nim `and` gdext/othertools.html#and,Int,Variant proc `and`(left: Int; right: Variant): bool 65
nim `or` gdext/othertools.html#or,Int,Variant proc `or`(left: Int; right: Variant): bool 66
nim `xor` gdext/othertools.html#xor,Int,Variant proc `xor`(left: Int; right: Variant): bool 67
nim `and` gdext/othertools.html#and,Int,bool proc `and`(left: Int; right: bool): bool 68
nim `or` gdext/othertools.html#or,Int,bool proc `or`(left: Int; right: bool): bool 69
nim `xor` gdext/othertools.html#xor,Int,bool proc `xor`(left: Int; right: bool): bool 70
nim `**` gdext/othertools.html#**,Int,Int proc `**`(left: Int; right: Int): Int 71
nim `**` gdext/othertools.html#**,Int,Float proc `**`(left: Int; right: Float): Float 72
nim `and` gdext/othertools.html#and,Int,Float proc `and`(left: Int; right: Float): bool 73
nim `or` gdext/othertools.html#or,Int,Float proc `or`(left: Int; right: Float): bool 74
nim `xor` gdext/othertools.html#xor,Int,Float proc `xor`(left: Int; right: Float): bool 75
nim `*` gdext/othertools.html#*,Int,Quaternion proc `*`(left: Int; right: Quaternion): Quaternion 76
nim `*` gdext/othertools.html#*,Int,Color proc `*`(left: Int; right: Color): Color 77
nim `and` gdext/othertools.html#and,Int,Object proc `and`(left: Int; right: Object): bool 78
nim `or` gdext/othertools.html#or,Int,Object proc `or`(left: Int; right: Object): bool 79
nim `xor` gdext/othertools.html#xor,Int,Object proc `xor`(left: Int; right: Object): bool 80
nim `and` gdext/othertools.html#and,Float,Variant proc `and`(left: Float; right: Variant): bool 58
nim `or` gdext/othertools.html#or,Float,Variant proc `or`(left: Float; right: Variant): bool 59
nim `xor` gdext/othertools.html#xor,Float,Variant proc `xor`(left: Float; right: Variant): bool 60
nim `not` gdext/othertools.html#not,Float proc `not`(left: Float): bool 61
nim `and` gdext/othertools.html#and,Float,bool proc `and`(left: Float; right: bool): bool 62
nim `or` gdext/othertools.html#or,Float,bool proc `or`(left: Float; right: bool): bool 63
nim `xor` gdext/othertools.html#xor,Float,bool proc `xor`(left: Float; right: bool): bool 64
nim `**` gdext/othertools.html#**,Float,Int proc `**`(left: Float; right: Int): Float 65
nim `and` gdext/othertools.html#and,Float,Int proc `and`(left: Float; right: Int): bool 66
nim `or` gdext/othertools.html#or,Float,Int proc `or`(left: Float; right: Int): bool 67
nim `xor` gdext/othertools.html#xor,Float,Int proc `xor`(left: Float; right: Int): bool 68
nim `**` gdext/othertools.html#**,Float,Float proc `**`(left: Float; right: Float): Float 69
nim `and` gdext/othertools.html#and,Float,Float proc `and`(left: Float; right: Float): bool 70
nim `or` gdext/othertools.html#or,Float,Float proc `or`(left: Float; right: Float): bool 71
nim `xor` gdext/othertools.html#xor,Float,Float proc `xor`(left: Float; right: Float): bool 72
nim `*` gdext/othertools.html#*,Float,Quaternion proc `*`(left: Float; right: Quaternion): Quaternion 73
nim `*` gdext/othertools.html#*,Float,Color proc `*`(left: Float; right: Color): Color 74
nim `and` gdext/othertools.html#and,Float,Object proc `and`(left: Float; right: Object): bool 75
nim `or` gdext/othertools.html#or,Float,Object proc `or`(left: Float; right: Object): bool 76
nim `xor` gdext/othertools.html#xor,Float,Object proc `xor`(left: Float; right: Object): bool 77
nim `and` gdext/othertools.html#and,bool,Int proc `and`(left: bool; right: Int): bool 25
nim `or` gdext/othertools.html#or,bool,Int proc `or`(left: bool; right: Int): bool 26
nim `xor` gdext/othertools.html#xor,bool,Int proc `xor`(left: bool; right: Int): bool 27
nim `and` gdext/othertools.html#and,bool,Float proc `and`(left: bool; right: Float): bool 28
nim `or` gdext/othertools.html#or,bool,Float proc `or`(left: bool; right: Float): bool 29
nim `xor` gdext/othertools.html#xor,bool,Float proc `xor`(left: bool; right: Float): bool 30
nim `and` gdext/othertools.html#and,bool,Object proc `and`(left: bool; right: Object): bool 31
nim `or` gdext/othertools.html#or,bool,Object proc `or`(left: bool; right: Object): bool 32
nim `xor` gdext/othertools.html#xor,bool,Object proc `xor`(left: bool; right: Object): bool 33
nim `()` gdext/othertools.html#(),Signal,varargs[Variant,variant] proc `()`(signal: Signal; args: varargs[Variant, variant]) 27
nimgrp getobject gdext/othertools.html#getObject-procs-all proc 50
nimgrp isnull gdext/othertools.html#isNull-procs-all proc 42
nimgrp xor gdext/othertools.html#xor-procs-all proc 67
nimgrp getobjectid gdext/othertools.html#getObjectId-procs-all proc 52
nimgrp == gdext/othertools.html#==-procs-all proc 9
nimgrp and gdext/othertools.html#and-procs-all proc 65
nimgrp isvalid gdext/othertools.html#isValid-procs-all proc 48
nimgrp callable gdext/othertools.html#callable-procs-all proc 9
nimgrp ** gdext/othertools.html#**-procs-all proc 71
nimgrp * gdext/othertools.html#*-procs-all proc 76
nimgrp rid gdext/othertools.html#rid-procs-all proc 12
nimgrp not gdext/othertools.html#not-procs-all proc 8
nimgrp or gdext/othertools.html#or-procs-all proc 66
nimgrp signal gdext/othertools.html#signal-procs-all proc 10
| 412 | 0.800676 | 1 | 0.800676 | game-dev | MEDIA | 0.255879 | game-dev | 0.535758 | 1 | 0.535758 |
oot-pc-port/oot-pc-port | 3,602 | asm/non_matchings/overlays/actors/ovl_Obj_Mure3/func_80B9A9D0.s | glabel func_80B9A9D0
/* 00000 80B9A9D0 27BDFFB0 */ addiu $sp, $sp, 0xFFB0 ## $sp = FFFFFFB0
/* 00004 80B9A9D4 AFB50030 */ sw $s5, 0x0030($sp)
/* 00008 80B9A9D8 AFB4002C */ sw $s4, 0x002C($sp)
/* 0000C 80B9A9DC AFB20024 */ sw $s2, 0x0024($sp)
/* 00010 80B9A9E0 00809025 */ or $s2, $a0, $zero ## $s2 = 00000000
/* 00014 80B9A9E4 00A0A025 */ or $s4, $a1, $zero ## $s4 = 00000000
/* 00018 80B9A9E8 27B50040 */ addiu $s5, $sp, 0x0040 ## $s5 = FFFFFFF0
/* 0001C 80B9A9EC AFBF0034 */ sw $ra, 0x0034($sp)
/* 00020 80B9A9F0 AFB30028 */ sw $s3, 0x0028($sp)
/* 00024 80B9A9F4 AFB10020 */ sw $s1, 0x0020($sp)
/* 00028 80B9A9F8 AFB0001C */ sw $s0, 0x001C($sp)
/* 0002C 80B9A9FC F7B40010 */ sdc1 $f20, 0x0010($sp)
/* 00030 80B9AA00 02A02025 */ or $a0, $s5, $zero ## $a0 = FFFFFFF0
/* 00034 80B9AA04 0C01DF90 */ jal Math_Vec3f_Copy
## Vec3f_Copy
/* 00038 80B9AA08 26450024 */ addiu $a1, $s2, 0x0024 ## $a1 = 00000024
/* 0003C 80B9AA0C 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000
/* 00040 80B9AA10 4481A000 */ mtc1 $at, $f20 ## $f20 = 20.00
/* 00044 80B9AA14 00008025 */ or $s0, $zero, $zero ## $s0 = 00000000
/* 00048 80B9AA18 24130005 */ addiu $s3, $zero, 0x0005 ## $s3 = 00000005
.L80B9AA1C:
/* 0004C 80B9AA1C 964E016C */ lhu $t6, 0x016C($s2) ## 0000016C
/* 00050 80B9AA20 02802025 */ or $a0, $s4, $zero ## $a0 = 00000000
/* 00054 80B9AA24 02A02825 */ or $a1, $s5, $zero ## $a1 = FFFFFFF0
/* 00058 80B9AA28 020E7807 */ srav $t7, $t6, $s0
/* 0005C 80B9AA2C 31F80001 */ andi $t8, $t7, 0x0001 ## $t8 = 00000000
/* 00060 80B9AA30 17000008 */ bne $t8, $zero, .L80B9AA54
/* 00064 80B9AA34 24064001 */ addiu $a2, $zero, 0x4001 ## $a2 = 00004001
/* 00068 80B9AA38 0010C880 */ sll $t9, $s0, 2
/* 0006C 80B9AA3C 0C007DDF */ jal Item_DropCollectible2
/* 00070 80B9AA40 02598821 */ addu $s1, $s2, $t9
/* 00074 80B9AA44 10400003 */ beq $v0, $zero, .L80B9AA54
/* 00078 80B9AA48 AE220150 */ sw $v0, 0x0150($s1) ## 00000150
/* 0007C 80B9AA4C 82480003 */ lb $t0, 0x0003($s2) ## 00000003
/* 00080 80B9AA50 A0480003 */ sb $t0, 0x0003($v0) ## 00000003
.L80B9AA54:
/* 00084 80B9AA54 C7A40044 */ lwc1 $f4, 0x0044($sp)
/* 00088 80B9AA58 26100001 */ addiu $s0, $s0, 0x0001 ## $s0 = 00000001
/* 0008C 80B9AA5C 46142180 */ add.s $f6, $f4, $f20
/* 00090 80B9AA60 1613FFEE */ bne $s0, $s3, .L80B9AA1C
/* 00094 80B9AA64 E7A60044 */ swc1 $f6, 0x0044($sp)
/* 00098 80B9AA68 8FBF0034 */ lw $ra, 0x0034($sp)
/* 0009C 80B9AA6C D7B40010 */ ldc1 $f20, 0x0010($sp)
/* 000A0 80B9AA70 8FB0001C */ lw $s0, 0x001C($sp)
/* 000A4 80B9AA74 8FB10020 */ lw $s1, 0x0020($sp)
/* 000A8 80B9AA78 8FB20024 */ lw $s2, 0x0024($sp)
/* 000AC 80B9AA7C 8FB30028 */ lw $s3, 0x0028($sp)
/* 000B0 80B9AA80 8FB4002C */ lw $s4, 0x002C($sp)
/* 000B4 80B9AA84 8FB50030 */ lw $s5, 0x0030($sp)
/* 000B8 80B9AA88 03E00008 */ jr $ra
/* 000BC 80B9AA8C 27BD0050 */ addiu $sp, $sp, 0x0050 ## $sp = 00000000
| 412 | 0.84238 | 1 | 0.84238 | game-dev | MEDIA | 0.97071 | game-dev | 0.699273 | 1 | 0.699273 |
magefree/mage | 2,170 | Mage.Tests/src/test/java/org/mage/test/cards/abilities/other/RielleTheEverwiseTest.java |
package org.mage.test.cards.abilities.other;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
*
* @author smartinsempere
*/
public class RielleTheEverwiseTest extends CardTestPlayerBase {
@Test
public void testRielleTheEverwiseAbilityDiscarding() {
addCard(Zone.HAND, playerA, "Faithless Looting");
addCard(Zone.HAND, playerA, "Brainwash");
addCard(Zone.HAND, playerA, "Brainwash");
addCard(Zone.HAND, playerA, "Brainwash");
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1);
addCard(Zone.BATTLEFIELD, playerA, "Rielle, the Everwise");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Faithless Looting");
setChoice(playerA, "Brainwash"); // discard
setChoice(playerA, "Brainwash"); // discard
setStrictChooseMode(true);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
execute();
assertHandCount(playerA, 5);
}
@Test
public void testRielleTheEverwiseAbilityCycling() {
addCard(Zone.HAND, playerA, "Unearth");
addCard(Zone.HAND, playerA, "Brainwash");
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 5);
addCard(Zone.BATTLEFIELD, playerA, "Rielle, the Everwise");
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cycling {2}");
setStrictChooseMode(true);
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertHandCount(playerA, 3);
}
@Test
public void testRielleTheEverwiseAbilityTransmute() {
addCard(Zone.HAND, playerA, "Tolaria West");
addCard(Zone.HAND, playerA, "Brainwash");
addCard(Zone.LIBRARY, playerA, "Memnite", 2);
addCard(Zone.BATTLEFIELD, playerA, "Island", 5);
addCard(Zone.BATTLEFIELD, playerA, "Rielle, the Everwise");
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Transmute {1}{U}{U}");
addTarget(playerA, "Memnite");
setStrictChooseMode(true);
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertHandCount(playerA, 3);
}
}
| 412 | 0.928665 | 1 | 0.928665 | game-dev | MEDIA | 0.818201 | game-dev,testing-qa | 0.763008 | 1 | 0.763008 |
qt/qtwebkit | 5,186 | Source/WebCore/platform/animation/Animation.cpp | /*
* Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "Animation.h"
#include <wtf/NeverDestroyed.h>
namespace WebCore {
Animation::Animation()
: m_name(initialName())
, m_property(CSSPropertyInvalid)
, m_mode(AnimateAll)
, m_iterationCount(initialIterationCount())
, m_delay(initialDelay())
, m_duration(initialDuration())
, m_timingFunction(initialTimingFunction())
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
, m_trigger(initialTrigger())
#endif
, m_direction(initialDirection())
, m_fillMode(initialFillMode())
, m_playState(initialPlayState())
, m_delaySet(false)
, m_directionSet(false)
, m_durationSet(false)
, m_fillModeSet(false)
, m_iterationCountSet(false)
, m_nameSet(false)
, m_playStateSet(false)
, m_propertySet(false)
, m_timingFunctionSet(false)
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
, m_triggerSet(false)
#endif
, m_isNone(false)
{
}
Animation::Animation(const Animation& o)
: RefCounted<Animation>()
, m_name(o.m_name)
, m_property(o.m_property)
, m_mode(o.m_mode)
, m_iterationCount(o.m_iterationCount)
, m_delay(o.m_delay)
, m_duration(o.m_duration)
, m_timingFunction(o.m_timingFunction)
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
, m_trigger(o.m_trigger)
#endif
, m_direction(o.m_direction)
, m_fillMode(o.m_fillMode)
, m_playState(o.m_playState)
, m_delaySet(o.m_delaySet)
, m_directionSet(o.m_directionSet)
, m_durationSet(o.m_durationSet)
, m_fillModeSet(o.m_fillModeSet)
, m_iterationCountSet(o.m_iterationCountSet)
, m_nameSet(o.m_nameSet)
, m_playStateSet(o.m_playStateSet)
, m_propertySet(o.m_propertySet)
, m_timingFunctionSet(o.m_timingFunctionSet)
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
, m_triggerSet(o.m_triggerSet)
#endif
, m_isNone(o.m_isNone)
{
}
Animation& Animation::operator=(const Animation& o)
{
m_name = o.m_name;
m_property = o.m_property;
m_mode = o.m_mode;
m_iterationCount = o.m_iterationCount;
m_delay = o.m_delay;
m_duration = o.m_duration;
m_timingFunction = o.m_timingFunction;
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
m_trigger = o.m_trigger;
#endif
m_direction = o.m_direction;
m_fillMode = o.m_fillMode;
m_playState = o.m_playState;
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
m_trigger = o.m_trigger;
#endif
m_delaySet = o.m_delaySet;
m_directionSet = o.m_directionSet;
m_durationSet = o.m_durationSet;
m_fillModeSet = o.m_fillModeSet;
m_iterationCountSet = o.m_iterationCountSet;
m_nameSet = o.m_nameSet;
m_playStateSet = o.m_playStateSet;
m_propertySet = o.m_propertySet;
m_timingFunctionSet = o.m_timingFunctionSet;
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
m_triggerSet = o.m_triggerSet;
#endif
m_isNone = o.m_isNone;
return *this;
}
Animation::~Animation()
{
}
bool Animation::animationsMatch(const Animation& other, bool matchPlayStates) const
{
bool result = m_name == other.m_name
&& m_property == other.m_property
&& m_mode == other.m_mode
&& m_iterationCount == other.m_iterationCount
&& m_delay == other.m_delay
&& m_duration == other.m_duration
&& *(m_timingFunction.get()) == *(other.m_timingFunction.get())
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
&& *(m_trigger.get()) == *(other.m_trigger.get())
#endif
&& m_direction == other.m_direction
&& m_fillMode == other.m_fillMode
&& m_delaySet == other.m_delaySet
&& m_directionSet == other.m_directionSet
&& m_durationSet == other.m_durationSet
&& m_fillModeSet == other.m_fillModeSet
&& m_iterationCountSet == other.m_iterationCountSet
&& m_nameSet == other.m_nameSet
&& m_propertySet == other.m_propertySet
&& m_timingFunctionSet == other.m_timingFunctionSet
#if ENABLE(CSS_ANIMATIONS_LEVEL_2)
&& m_triggerSet == other.m_triggerSet
#endif
&& m_isNone == other.m_isNone;
if (!result)
return false;
return !matchPlayStates || (m_playState == other.m_playState && m_playStateSet == other.m_playStateSet);
}
const String& Animation::initialName()
{
static NeverDestroyed<String> initialValue(ASCIILiteral("none"));
return initialValue;
}
} // namespace WebCore
| 412 | 0.843783 | 1 | 0.843783 | game-dev | MEDIA | 0.884176 | game-dev | 0.944407 | 1 | 0.944407 |
Histidine91/Nexerelin | 13,726 | jars/sources/ExerelinCore/exerelin/campaign/StatsTracker.java | package exerelin.campaign;
import com.fs.starfarer.api.Global;
import com.fs.starfarer.api.campaign.*;
import com.fs.starfarer.api.campaign.CargoAPI.CargoItemQuantity;
import com.fs.starfarer.api.campaign.econ.Industry;
import com.fs.starfarer.api.campaign.econ.MarketAPI;
import com.fs.starfarer.api.campaign.listeners.ColonyPlayerHostileActListener;
import com.fs.starfarer.api.campaign.listeners.SurveyPlanetListener;
import com.fs.starfarer.api.characters.OfficerDataAPI;
import com.fs.starfarer.api.fleet.FleetMemberAPI;
import com.fs.starfarer.api.impl.campaign.RuleBasedInteractionDialogPluginImpl;
import com.fs.starfarer.api.impl.campaign.ids.Factions;
import com.fs.starfarer.api.impl.campaign.rulecmd.salvage.MarketCMD.TempData;
import com.fs.starfarer.api.loading.FighterWingSpecAPI;
import com.fs.starfarer.api.util.Misc;
import exerelin.campaign.submarkets.PrismMarket;
import exerelin.utilities.NexUtilsMarket;
import exerelin.utilities.StringHelper;
import org.apache.log4j.Logger;
import org.lazywizard.lazylib.MathUtils;
import java.util.*;
/**
* Tracks lifetime stats: kills, losses, planets captured, etc.
*/
public class StatsTracker extends BaseCampaignEventListener implements ColonyPlayerHostileActListener, SurveyPlanetListener {
protected static final String TRACKER_MAP_KEY = "exerelin_statsTracker";
public static Logger log = Global.getLogger(StatsTracker.class);
public static final Set<String> NO_ORPHANS_FACTIONS = new HashSet<>(Arrays.asList(new String[] {
Factions.DERELICT, "nex_derelict", Factions.REMNANTS, "spire", "darkspire"
}));
protected static StatsTracker tracker;
protected int shipsKilled = 0;
protected int shipsLost = 0;
protected float fpKilled = 0;
protected float fpLost = 0;
protected int marketsCaptured = 0;
protected int marketsRaided = 0;
protected int marketsTacBombarded = 0;
protected int marketsSatBombarded = 0;
protected int prisonersRepatriated = 0;
protected int prisonersRansomed = 0;
protected int agentActions = 0;
@Deprecated protected int slavesSold = 0;
protected int orphansMade = 0; // hee hee
protected int planetsSurveyed;
protected Set<DeadOfficerEntry> deadOfficers = new HashSet<>();
public StatsTracker() {
super(true);
}
public int getShipsKilled() {
return shipsKilled;
}
public int getShipsLost() {
return shipsLost;
}
public float getFpKilled() {
return fpKilled;
}
public float getFpLost() {
return fpLost;
}
public int getMarketsCaptured() {
return marketsCaptured;
}
public int getMarketsRaided() {
return marketsRaided;
}
public int getMarketsTacBombarded() {
return marketsTacBombarded;
}
public int getMarketsSatBombarded() {
return marketsSatBombarded;
}
public int getNumAgentActions() {
return agentActions;
}
public int getPrisonersRepatriated() {
return prisonersRepatriated;
}
public int getPrisonersRansomed() {
return prisonersRansomed;
}
public int getSlavesSold() {
return slavesSold;
}
public int getOrphansMade() {
return orphansMade;
}
public int getPlanetsSurveyed() {
return planetsSurveyed;
}
/**
* @return The set of dead officers (not a copy, changes to the returned set will be reflected in the rest of the mod).
*/
public Set<DeadOfficerEntry> getDeadOfficers() {
return deadOfficers;
}
public List<DeadOfficerEntry> getDeadOfficersSorted() {
List<DeadOfficerEntry> list = new ArrayList(deadOfficers);
Collections.sort(list);
return list;
}
public int getNumOfficersLost() {
return deadOfficers.size();
}
public void modifyOrphansMade(int num) {
orphansMade += num;
}
public void notifyAgentActions(int num)
{
agentActions += num;
}
public void notifyPrisonersRepatriated(int num) {
prisonersRepatriated += num;
}
public void notifyPrisonersRansomed(int num) {
prisonersRansomed += num;
}
public void notifySlavesSold(int num) {
slavesSold += num;
}
public void notifyMarketCaptured(MarketAPI market) {
marketsCaptured++;
}
public void modifyOrphansMadeByCrewCount(int crew, String faction)
{
float numAvgKids = MathUtils.getRandomNumberInRange(0f, 1.5f) + MathUtils.getRandomNumberInRange(0f, 1.5f);
if (faction.equals("templars")) // High-ranking Templars (including those who'd get to serve on a ship) have large (adopted) families
numAvgKids = MathUtils.getRandomNumberInRange(0f, 5f) + MathUtils.getRandomNumberInRange(0f, 5f);
orphansMade += crew * numAvgKids;
}
public DeadOfficerEntry addDeadOfficer(OfficerDataAPI officer, FleetMemberAPI member)
{
if (deadOfficers == null) deadOfficers = new HashSet<>(); // reverse compat
DeadOfficerEntry entry = new DeadOfficerEntry(officer, member);
deadOfficers.add(entry);
return entry;
}
public void removeDeadOfficer(OfficerDataAPI officer)
{
if (deadOfficers == null) deadOfficers = new HashSet<>(); // reverse compat
DeadOfficerEntry toRemove = null;
for (DeadOfficerEntry dead : deadOfficers)
{
if (dead.officer == officer)
{
toRemove = dead;
break;
}
}
if (toRemove != null)
deadOfficers.remove(toRemove);
}
@Override
public void reportBattleFinished(CampaignFleetAPI winner, BattleAPI battle)
{
if (RevengeanceManager.getManager() != null)
{
//RevengeanceManager.getManager().reportBattle(winner, battle);
}
if (!battle.isPlayerInvolved()) return;
List<CampaignFleetAPI> killedFleets = battle.getNonPlayerSide();
//List<CampaignFleetAPI> lossesFleets = battle.getPlayerSide();
CampaignFleetAPI myFleet = Global.getSector().getPlayerFleet();
Global.getLogger(StatsTracker.class).info("Tracker tracking battle");
float involvedFraction = battle.getPlayerInvolvementFraction();
float recentFpKilled = 0;
int recentShipsKilled = 0;
for (CampaignFleetAPI killedFleet : killedFleets)
{
for (FleetMemberAPI member : Misc.getSnapshotMembersLost(killedFleet)) {
recentFpKilled += member.getFleetPointCost();
recentShipsKilled++;
// orphans
String factionId = member.getCaptain().getFaction().getId();
if (!haveOrphans(factionId)) continue;
modifyOrphansMadeByCrewCount((int)(member.getMinCrew()*involvedFraction), factionId);
}
}
fpKilled += recentFpKilled * involvedFraction;
shipsKilled += recentShipsKilled * involvedFraction;
List<FleetMemberAPI> myCurrent = myFleet.getFleetData().getMembersListCopy();
List<FleetMemberAPI> mySnapshot = myFleet.getFleetData().getSnapshot();
for (FleetMemberAPI member : mySnapshot) {
if (!myCurrent.contains(member)) {
fpLost += member.getFleetPointCost();
shipsLost++;
}
}
// report captured ships to Prism market
for (FleetMemberAPI member : myCurrent) {
if (!mySnapshot.contains(member)) {
PrismMarket.notifyShipAcquired(member);
}
}
}
// use this to record IBB ships for already-bought list
// should catch debris field salvage
@Override
public void reportShownInteractionDialog(InteractionDialogAPI dialog) {
if (dialog == null) return; // temp: https://fractalsoftworks.com/forum/index.php?topic=31941.msg469453#msg469453
InteractionDialogPlugin plugin = dialog.getPlugin();
if (plugin instanceof RuleBasedInteractionDialogPluginImpl)
{
PrismMarket.recordShipsOwned(Global.getSector().getPlayerFleet().getMembersWithFightersCopy());
CargoAPI cargo = Global.getSector().getPlayerFleet().getCargo();
for (CargoItemQuantity<String> fighterStack : cargo.getFighters())
{
FighterWingSpecAPI bla = Global.getSettings().getFighterWingSpec(fighterStack.getItem());
PrismMarket.notifyShipAcquired(bla.getId());
}
}
}
public static StatsTracker getStatsTracker()
{
return getOrCreateTracker();
}
public static boolean isTrackerLoaded()
{
return (tracker != null);
}
public static StatsTracker getOrCreateTracker()
{
Map<String, Object> data = Global.getSector().getPersistentData();
tracker = (StatsTracker)data.get(TRACKER_MAP_KEY);
if (tracker != null)
return tracker;
tracker = new StatsTracker();
data.put(TRACKER_MAP_KEY, tracker);
Global.getSector().getListenerManager().addListener(tracker);
return tracker;
}
// all guesstimates until TempData becomes actually accessible
public int addOrphansFromMilitaryAction(int power, float raidMult) {
int orphans = (int)(MathUtils.getRandomNumberInRange(5, 20) * Math.pow(2, power));
if (raidMult > 0) {
float contestedFactor = 0.5f - Math.abs(0.5f - raidMult);
orphans = orphans * 2 * Math.round(contestedFactor);
}
orphansMade += orphans;
return orphans;
}
@Override
public void reportRaidForValuablesFinishedBeforeCargoShown(
InteractionDialogAPI dialog, MarketAPI market, TempData actionData, CargoAPI cargo) {
if (haveOrphans(market.getFactionId())) {
int orphans = addOrphansFromMilitaryAction(market.getSize() - 2, actionData.raidMult);
log.info("Making " + orphans + " orphans from raid for valuables");
}
marketsRaided++;
}
@Override
public void reportRaidToDisruptFinished(InteractionDialogAPI dialog, MarketAPI market,
TempData actionData, Industry industry) {
if (haveOrphans(market.getFactionId())) {
int orphans = addOrphansFromMilitaryAction(market.getSize() - 2, actionData.raidMult);
log.info("Making " + orphans + " orphans from raid to disrupt");
}
marketsRaided++;
}
@Override
public void reportTacticalBombardmentFinished(InteractionDialogAPI dialog,
MarketAPI market, TempData actionData) {
if (haveOrphans(market.getFactionId())) {
int orphans = addOrphansFromMilitaryAction(market.getSize() - 1, -1);
log.info("Making " + orphans + " orphans from tactical bombardment");
}
marketsTacBombarded++;
}
@Override
public void reportSaturationBombardmentFinished(InteractionDialogAPI dialog,
MarketAPI market, TempData actionData) {
if (haveOrphans(market.getFactionId())) {
int oldSize = market.getSize() + 1;
float deaths = NexUtilsMarket.getPopulation(oldSize) - NexUtilsMarket.getPopulation(market.getSize());
deaths *= MathUtils.getRandomNumberInRange(0.5f, 1.5f);
int orphans = (int)Math.round(Math.sqrt(deaths));
log.info("Making " + orphans + " orphans from saturation bombardment");
orphansMade += orphans;
}
marketsSatBombarded++;
}
@Override
public void reportPlayerSurveyedPlanet(PlanetAPI planet) {
planetsSurveyed++;
}
public static boolean haveOrphans(String factionId) {
return !NO_ORPHANS_FACTIONS.contains(factionId);
}
public static class DeadOfficerEntry implements Comparable<DeadOfficerEntry>
{
public static final int NUM_CAUSES_OF_DEATH = 12;
public OfficerDataAPI officer;
public int deadCycle;
public int deadMonth;
public int deadDay;
public String shipName;
public String shipClass;
public String shipDesignation;
public String causeOfDeath;
public DeadOfficerEntry(OfficerDataAPI officer, FleetMemberAPI member)
{
this.officer = officer;
this.shipName = member.getShipName();
this.shipClass = member.getHullSpec().getHullNameWithDashClass();
this.shipDesignation = member.getHullSpec().getDesignation();
CampaignClockAPI clock = Global.getSector().getClock();
this.deadCycle = clock.getCycle();
this.deadMonth = clock.getMonth();
this.deadDay = clock.getDay();
this.causeOfDeath = StringHelper.getString("exerelin_officers",
"causeOfDeath" + MathUtils.getRandomNumberInRange(1, NUM_CAUSES_OF_DEATH));
}
public String getDeathDate()
{
return deadCycle + "." + deadMonth + "." + deadDay;
}
@Override
public int compareTo(DeadOfficerEntry other) {
int result = Integer.compare(deadCycle, other.deadCycle);
if (result != 0) return result;
result = Integer.compare(deadMonth, other.deadMonth);
if (result != 0) return result;
result = Integer.compare(deadDay, other.deadDay);
return result;
}
}
}
| 412 | 0.956428 | 1 | 0.956428 | game-dev | MEDIA | 0.930539 | game-dev | 0.982021 | 1 | 0.982021 |
elanthia-online/dr-scripts | 5,607 | profiles/Samples/Paladin/Tekronn-setup.yaml | ---
# Register my sallet (Thanks Chuno!)
training_manager_hunting_priority: false
hunting_info:
- :zone: warklin
:duration: 30
stop_on:
- Brawling
- Crossbow
- Twohanded Edged
- Large Edged
- Large Blunt
- Twohanded Blunt
- Heavy Thrown
- Polearms
- Offhand Weapon
- Small Edged
- Small Blunt
- Light Thrown
- Staves
prehunt_buffing_room: 1189
waggle_sets:
prehunt_buffs:
Sentinel's Resolve:
cambrinth:
- 10
Manifest Force:
cambrinth:
- 10
hunting_buddies:
- Torgro
- Sheltim
- Mooselurk
- Fuss
- Feltzer
gear:
- :adjective: plate
:name: gauntlets
:is_leather: false
:hinders_lockpicking: true
:is_worn: true
:swappable: false
:tie_to:
- :adjective: scale
:name: vambraces
:is_leather: false
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective: target
:name: shield
:is_leather: false
:hinders_lockpicking: true
:is_worn: true
:swappable: false
:tie_to:
- :adjective: insulated
:name: vest
:is_leather: true
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective: ring
:name: greaves
:is_leather: false
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective:
:name: sallet
:is_leather: false
:hinders_lockpicking: true
:is_worn: true
:swappable: false
:tie_to:
- :adjective:
:name: tasset
:is_leather: false
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective: parry
:name: stick
:is_leather: false
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective: brass
:name: knuckles
:is_leather: false
:hinders_lockpicking: true
:is_worn: true
:swappable: false
:tie_to:
- :adjective: elbow
:name: spikes
:is_leather: false
:hinders_lockpicking: false
:is_worn: true
:swappable: false
:tie_to:
- :adjective: light
:name: crossbow
:is_leather: true
:hinders_lockpicking:
:is_worn: false
:swappable: false
:tie_to:
- :adjective: bastard
:name: sword
:is_leather: false
:hinders_lockpicking:
:is_worn: false
:swappable: true
:tie_to:
- :adjective:
:name: spear
:is_leather: false
:hinders_lockpicking:
:is_worn: false
:swappable: false
:tie_to:
- :adjective: horseman
:name: flail
:is_leather: false
:hinders_lockpicking:
:is_worn: false
:swappable: false
:tie_to:
- :adjective: throwing
:name: spike
:is_leather: false
:hinders_lockpicking: false
:is_worn: false
:swappable: true
:tie_to:
- :adjective:
:name: akabo
:is_leather: false
:hinders_lockpicking: false
:is_worn: false
:swappable: false
:tie_to:
- :adjective:
:name: nightstick
:is_leather: false
:hinders_lockpicking: false
:is_worn: false
:swappable: false
:tie_to:
gear_sets:
standard:
- scale vambraces
- plate gauntlets
- ring greaves
- insulated vest
- sallet
- tasset
- target shield
- parry stick
- brass knuckles
- elbow spikes
hand_armor: gauntlets
offensive_spells:
- name: Footman's Strike
cast_only_to_train: true
mana: 5
- name: Stun Foe
mana: 5
buff_spells:
# Rutilor's Edge:
# prep_time: 0
Manifest Force:
cambrinth:
- 10
- 10
Sentinel's Resolve:
cambrinth:
- 10
- 10
Aspirant's Aegis:
cambrinth:
- 10
- 10
Divine Armor:
cambrinth:
- 10
- 10
# Lay Ward:
# Righteous Wrath:
# Truffenyi's Rally:
# Heroic Strength:
Courage:
cambrinth:
- 10
# Divine Guidance:
# Clarity:
Marshal Order:
cambrinth:
- 10
dance_skill: Large Edged
dance_actions_stealth:
training_abilities:
Hunt: 80
Perc: 120
App Quick: 60
weapon_training:
Brawling: ''
Crossbow: light crossbow
Twohanded Edged: bastard sword
Large Edged: bastard sword
Large Blunt: horseman flail
Twohanded Blunt: akabo
Heavy Thrown: spear
Polearms: spear
Offhand Weapon: throwing spike
Small Edged: throwing spike
Small Blunt: throwing spike
Light Thrown: throwing spike
Staves: nightstick
skinning:
skin: true
arrange_all: false
arrange_count: 1
tie_bundle: true
loot_subtractions:
- arrow
- arrows
- rock
- rocks
# use_weak_attacks: true
training_spells:
Warding:
abbrev: AA
symbiosis: true
Augmentation:
abbrev: DIG
symbiosis: true
Utility:
abbrev: VOS
symbiosis: true
cyclic_training_spells:
Warding:
abbrev: HOW
cyclic: true
Augmentation:
abbrev: TR
cyclic: true
Utility:
abbrev: TR
cyclic: true
cyclic_cycle_skills:
- Warding
- Augmentation
- Utility
listen: true
crossing_training:
- Perception
- Forging
- Outfitting
# - Engineering
- Sorcery
# - First Aid
# - Appraisal
- Warding
- Augmentation
- Utility
- Attunement
- Athletics
- Mechanical Lore
# - Scholarship
# - Outdoorsmanship
tithe: true
cambrinth: anklet
cambrinth_cap: 50
train_workorders:
- Blacksmithing
- Tailoring
- Shaping
crafting_container: backpack
forging_tools:
- ball-peen hammer
- tongs
- bellows
- shovel
- stamp
- pliers
- stirring rod
sell_loot_pouch: false
gem_pouch_adjective: suede
spare_gem_pouch_container: haver
dedicated_camb_use: spell
favor_god: Chadatru
favor_goal: 30
crossing_training_sorcery:
abbrev: ART
mana: 15
cambrinth:
- 10
- 10
quit_on_status_warning: true
braid_item: grass
saferoom_health_threshold: 25
status_monitor_no_window: true
bankbot_deposit_threshold: 0
# From UserVars
crossing_training_sorcery_room:
engineering_room:
outfitting_room:
safe_room:
safe_room_id:
safe_room_empath:
slack_username:
bankbot_name:
bankbot_room_id:
| 412 | 0.9391 | 1 | 0.9391 | game-dev | MEDIA | 0.937251 | game-dev | 0.510794 | 1 | 0.510794 |
Inori/FuckGalEngine | 14,838 | Krkr/M2Psb/PSBReader_Sources/NumberFileStream/FileStream.cpp | /*
Moe-Sky(ȿպ) File Stream Sources
201724 @ Moe-Sky
2013-01-20
*/
#include "stdafx.h"
#include "NumberFileStream.h"
#include "FileStream.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <shlwapi.h>
#include "zlib.h"
#pragma comment(lib,"zlib.lib")
#pragma comment(lib,"shlwapi.lib")
#include <malloc.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
CFileStream::CFileStream()
{
}
CFileStream::~CFileStream()
{
}
bool CFileStream::Open(char* pszFilePath)
{
DWORD fileSize;
DWORD readSize;
fileHandle = CreateFile(pszFilePath,GENERIC_READ,NULL,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(fileHandle != INVALID_HANDLE_VALUE)
{
fileSize = GetFileSize(fileHandle,&fileSize);
if(fileSize > sizeof(file_header_s))
{
if(ReadFile(fileHandle,(LPVOID)&fileHeader,sizeof(fileHeader),&readSize,NULL))
{
if( strcmp(fileHeader.Sign,SIGN_STRING)==0 &&
fileHeader.strCount &&
fileHeader.strData &&
fileHeader.treeData &&
fileHeader.treeList)
{
memoryData = new BYTE[fileSize];
SetFilePointer(fileHandle,0,NULL,FILE_BEGIN);
if(ReadFile(fileHandle,(LPVOID)memoryData,fileSize,&readSize,NULL))
{
fileType = FileOpen;
return true;
}
}
}
}
}
return false;
}
DWORD CFileStream::GetHashValue(char* str)
{
DWORD hashValue=0;
int len = strlen(str);
for(int i=0;i<len;i++)
{
hashValue += ~(((str[i] << 8) | ~str[i]) << 8);
hashValue += (((str[i] << 8) | str[i]) << 8);
hashValue *= hashValue;
}
return hashValue;
}
bool CFileStream::Create(char* pszFilePath)
{
fileHandle = CreateFile(pszFilePath,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if(fileHandle != INVALID_HANDLE_VALUE)
{
fileType = FileCreate;
memset(&fileHeader,0,sizeof(fileHeader));
memoryTreeRoot.bDirectory = TRUE;
memoryTreeRoot.dataOffset = NULL;
memoryTreeRoot.dataSize = NULL;
memoryTreeRoot.dwHashValue = GetHashValue("/");
memoryTreeRoot.nStringIdx = 0;
stringtable_s * string = new stringtable_s;
string->size = strlen("/")+1;
string->data = new char[strlen("/")+1];
strcpy(string->data,"/");
memoryString.push_back(string);
return true;
}
return false;
}
bool CFileStream::m_strcmp(int idx,char* string)
{
return (strcmp((const char*)memoryString[idx]->data,string)==0);
}
char* CFileStream::GetFolderName(char* TreePath)
{
static char szFolderName[MAX_PATH];
int len = strlen(TreePath);
strcpy(szFolderName,TreePath);
bool find=false;
for(int i=0;i<len;i++)
{
if(szFolderName[i] == '/')
{
szFolderName[i] = 0;
find = true;
break;
}
}
if(!find)
return FALSE;
return (char*)&szFolderName;
}
char* CFileStream::GetFileName(char* TreePath)
{
int len = strlen(TreePath);
for(int i=len;i>-1;i--)
{
if(TreePath[i] == '/')
return &TreePath[i+1];
}
return NULL;
}
memory_tree_s* CFileStream::RecursionFileExists(char* TreePath,memory_tree_s* DirTree)
{
char* pszFolderName = GetFolderName(TreePath);
if(pszFolderName)
{
DWORD hashvalue = GetHashValue(pszFolderName);
int listsize = DirTree->dataList.size();
if(listsize)
{
for(int i=0;i<listsize;i++)
{
if(DirTree->dataList[i]->bDirectory && DirTree->dataList[i]->dwHashValue == hashvalue && m_strcmp(DirTree->dataList[i]->nStringIdx,pszFolderName))
{
char* nextdir = &TreePath[strlen(pszFolderName)+1];
return RecursionFileExists(nextdir,DirTree->dataList[i]);
}
}
}
else
{
return NULL;
}
}
else
{
int listsize = DirTree->dataList.size();
if(listsize)
{
DWORD hashvalue = GetHashValue(TreePath);
for(int i=0;i<listsize;i++)
{
if(!DirTree->dataList[i]->bDirectory)
{
if( DirTree->dataList[i]->dwHashValue == hashvalue &&
m_strcmp(DirTree->dataList[i]->nStringIdx,TreePath))
return DirTree->dataList[i];
}
}
}
else
{
return NULL;
}
}
return NULL;
}
memory_tree_t * CFileStream::FileIsExists(char* TreePath)
{
static char szPath[MAX_PATH];
char* szChars;
char* pszFolderName;
if(TreePath && TreePath[0] == '/')
{
strcpy(szPath,TreePath);
szChars = (char*)&szPath;
if(memoryTreeRoot.dataList.size() == 0)
{
return NULL;
}
szChars++;
pszFolderName = GetFolderName(szChars);
if(pszFolderName)
{
int listsize = memoryTreeRoot.dataList.size();
if(listsize)
{
DWORD hashvalue = GetHashValue(pszFolderName);
for(int i=0;i<listsize;i++)
{
if(memoryTreeRoot.dataList[i]->bDirectory &&
memoryTreeRoot.dataList[i]->dwHashValue == hashvalue &&
m_strcmp(memoryTreeRoot.dataList[i]->nStringIdx,pszFolderName))
{
char* nextdir = &szChars[strlen(pszFolderName)+1];
return RecursionFileExists(nextdir,memoryTreeRoot.dataList[i]);
}
}
}
return NULL;
}
else
{
int listsize = memoryTreeRoot.dataList.size();
if(listsize)
{
DWORD hashvalue = GetHashValue(szChars);
for(int i=0;i<listsize;i++)
{
if(!memoryTreeRoot.dataList[i]->bDirectory &&
memoryTreeRoot.dataList[i]->dwHashValue == hashvalue &&
m_strcmp(memoryTreeRoot.dataList[i]->nStringIdx,szChars)
)
{
return memoryTreeRoot.dataList[i];
}
}
}
}
}
return NULL;
}
bool CFileStream::RecursionInsertFile(char* treepath,memory_tree_s* fileTree,memory_tree_s* DirTree)
{
char TreeRoot[MAX_PATH];
if(treepath[0] == '/')
{
treepath++;
return RecursionInsertFile(treepath,fileTree,&memoryTreeRoot);
}
if(DirTree)
{
strcpy(TreeRoot,treepath);
char * folderName = GetFolderName(TreeRoot);
if(folderName)
{
int listsize = DirTree->dataList.size();
if(listsize)
{
DWORD hashvalue = GetHashValue(folderName);
for(int i=0;i<listsize;i++)
{
if(DirTree->dataList[i]->bDirectory &&
DirTree->dataList[i]->dwHashValue == hashvalue &&
m_strcmp(DirTree->dataList[i]->nStringIdx,folderName))
{
char* nextdir = &treepath[strlen(folderName)+1];
return RecursionInsertFile(nextdir,fileTree,DirTree->dataList[i]);
}
}
memory_tree_s* newdir = new memory_tree_s;
newdir->bDirectory = TRUE;
newdir->nStringIdx = AllocString(folderName);
newdir->dataSize = 0;
newdir->dataOffset = 0;
newdir->dwHashValue = GetHashValue(folderName);
DirTree->dataList.push_back(newdir);
char* nextdir = &treepath[strlen(folderName)+1];
return RecursionInsertFile(nextdir,fileTree,newdir);
}
else
{
memory_tree_s* newdir = new memory_tree_s;
newdir->bDirectory = TRUE;
newdir->nStringIdx = AllocString(folderName);
newdir->dataSize = 0;
newdir->dataOffset = 0;
newdir->dwHashValue = GetHashValue(folderName);
DirTree->dataList.push_back(newdir);
char* nextdir = &treepath[strlen(folderName)+1];
return RecursionInsertFile(nextdir,fileTree,newdir);
}
}
else
{
DirTree->dataList.push_back(fileTree);
return true;
}
}
return false;
}
int CFileStream::AllocString(char* str)
{
char fileName[32];
strcpy(fileName,str);
stringtable_s * string = new stringtable_s;
string->size = strlen(fileName) + 1;
string->data = new char[string->size];
strcpy(string->data,fileName);
memoryString.push_back(string);
return memoryString.size() - 1;
}
bool CFileStream::AddFile(char* pszFilePath,char* treepath)
{
HANDLE addFileHandle;
DWORD fileSize;
DWORD readSize;
if(FileIsExists(treepath))
return false;
addFileHandle = CreateFile(pszFilePath,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(addFileHandle != INVALID_HANDLE_VALUE)
{
memory_tree_s* fileTree = new memory_tree_s;
fileSize = GetFileSize(addFileHandle,&fileSize);
fileTree->bDirectory = FALSE;
fileTree->dataSize = fileSize;
fileTree->dataOffset = new BYTE[fileSize];
fileTree->dwHashValue = GetHashValue(GetFileName(treepath));
fileTree->nStringIdx = AllocString(GetFileName(treepath));
ReadFile(addFileHandle,fileTree->dataOffset,fileSize,&readSize,NULL);
CloseHandle(addFileHandle);
if(RecursionInsertFile(treepath,fileTree))
return true;
}
return false;
}
char* CFileStream::GetName(int idx)
{
return (char*)memoryString[idx]->data;
}
memory_tree_s* CFileStream::GetFile(char* treepath)
{
return FileIsExists(treepath);
}
void CFileStream::RecursionTreeList(memory_tree_s* root,save_data_t* save)
{
save->treeList = (disk_tree_s*)realloc((void*)save->treeList,save->treeSize + sizeof(disk_tree_s));
disk_tree_s* tree = (disk_tree_s*)((DWORD)save->treeList + save->treeSize);
tree->bDirectory = root->bDirectory;
tree->dwHashValue = root->dwHashValue;
tree->nStringIdx = root->nStringIdx;
save->treeSize += sizeof(disk_tree_s);
if(root->bDirectory)
{
int listsize = root->dataList.size();
tree->fileCount = listsize;
tree->dataOffset = save->treeSize;
for(int i=0;i<listsize;i++)
{
RecursionTreeList(root->dataList[i],save);
}
}
else
{
tree->fileCount = 0;
tree->dataSize = root->dataSize;
tree->dataOffset = save->treeDataSize;
save->treeData = realloc(save->treeData,save->treeDataSize + root->dataSize);
memcpy((void*)((DWORD)save->treeData + save->treeDataSize),root->dataOffset,root->dataSize);
save->treeDataSize += root->dataSize;
}
}
void CFileStream::RecursionTreeList(disk_tree_s* tree,void* treedata,PDWORD offset,DWORD startaddr,memory_tree_s* List)
{
*offset += sizeof(disk_tree_s);
if(tree->nStringIdx==0)
{
memoryTreeRoot.bDirectory = tree->bDirectory;
memoryTreeRoot.dataOffset = NULL;
memoryTreeRoot.dataSize = NULL;
memoryTreeRoot.dwHashValue = tree->dwHashValue;
memoryTreeRoot.nStringIdx = tree->nStringIdx;
for(DWORD i=0;i<tree->fileCount;i++)
{
RecursionTreeList((disk_tree_s*)((DWORD)tree+*offset),treedata,offset,(DWORD)tree,&memoryTreeRoot);
}
}
else
{
memory_tree_s* m_list = new memory_tree_s;
List->dataList.push_back(m_list);
m_list->bDirectory = tree->bDirectory;
m_list->dwHashValue = tree->dwHashValue;
m_list->nStringIdx = tree->nStringIdx;
if(tree->bDirectory)
{
m_list->dataOffset = NULL;
m_list->dataSize = NULL;
for(DWORD i=0;i<tree->fileCount;i++)
{
RecursionTreeList((disk_tree_s*)(startaddr+*offset),treedata,offset,startaddr,m_list);
}
}
else
{
m_list->dataOffset =(PBYTE)( tree->dataOffset + (DWORD)treedata);
m_list->dataSize = tree->dataSize;
}
}
}
bool CFileStream::SaveToStream(BOOL bCompress)
{
int stringCount = memoryString.size();
int dataCount = memoryTreeRoot.dataList.size();
save_data_t save_data;
DWORD fileSize;
PBYTE fileData = (PBYTE)malloc(0);
file_header_s * fileHeader;
save_data.treeSize = 0;
save_data.treeDataSize = 0;
save_data.treeList = (disk_tree_s*)malloc(0);
save_data.treeData = malloc(0);
save_data.strData = (char*)malloc(0);
save_data.strCount = stringCount;
save_data.strSize = 0;
for(int i=0;i<stringCount;i++)
{
save_data.strData = (char*)realloc(save_data.strData,save_data.strSize+memoryString[i]->size);
strcpy(save_data.strData+save_data.strSize,memoryString[i]->data);
save_data.strSize += memoryString[i]->size;
}
RecursionTreeList(&memoryTreeRoot,&save_data);
fileData = (PBYTE)realloc(fileData,sizeof(file_header_s));
fileSize = sizeof(file_header_s);
fileHeader = (file_header_s*)fileData;
memset(fileHeader->Sign,0,sizeof(fileHeader->Sign));
strcpy(fileHeader->Sign,SIGN_STRING);
fileHeader->strCount = save_data.strCount;
fileHeader->strData = fileSize;
fileData = (PBYTE)realloc(fileData,fileSize+save_data.strSize);
memcpy(&fileData[fileSize],save_data.strData,save_data.strSize);
fileSize += save_data.strSize;
fileHeader = (file_header_s*)fileData;
fileHeader->treeList = fileSize;
fileData = (PBYTE)realloc(fileData,fileSize+save_data.treeSize);
memcpy(&fileData[fileSize],save_data.treeList,save_data.treeSize);
fileSize += save_data.treeSize;
PBYTE compBuffer;
if(bCompress)
{
save_data.treeCompSize = compressBound(save_data.treeDataSize);
compBuffer = new BYTE[save_data.treeCompSize];
if(compress(compBuffer,&save_data.treeCompSize,(PBYTE)save_data.treeData,save_data.treeDataSize)==Z_OK)
{
fileData = (PBYTE)realloc(fileData,fileSize+save_data.treeCompSize);
fileHeader = (file_header_s*)fileData;
fileHeader->treeData = fileSize;
fileHeader->treeCompSize = save_data.treeCompSize;
fileHeader->treeDataSize = save_data.treeDataSize;
memcpy(&fileData[fileSize],compBuffer,save_data.treeCompSize);
}
else
{
MessageBox(NULL,"ѹʧ","",MB_OK);
abort();
}
fileSize += save_data.treeCompSize;
}
else
{
fileData = (PBYTE)realloc(fileData,fileSize+save_data.treeDataSize);
fileHeader = (file_header_s*)fileData;
fileHeader->treeData = fileSize;
fileHeader->treeCompSize = NULL;
fileHeader->treeDataSize = save_data.treeDataSize;
memcpy(&fileData[fileSize],save_data.treeData,save_data.treeDataSize);
fileSize += save_data.treeDataSize;
}
SetFilePointer(fileHandle,0,NULL,FILE_BEGIN);
DWORD nWriteSize;
WriteFile(fileHandle,fileData,fileSize,&nWriteSize,NULL);
free(fileData);
free(save_data.treeList);
free(save_data.treeData);
free(save_data.strData);
if(bCompress) delete compBuffer;
return true;
}
BOOL CFileStream::RecursionDirectory(char* lpszDir ,int start)
{
int i=0;
if( ::PathIsDirectory( lpszDir ) ) return TRUE;
char szPreDir[MAX_PATH];
int len = strlen(lpszDir);
szPreDir[0] = 0;
for(i=start;i<len;i++)
{
if(lpszDir[i] == '/')
{
memcpy(szPreDir,lpszDir,i);
szPreDir[i] = 0;
break;
}
}
i++;
if(szPreDir[0] == 0)
{
strcpy(szPreDir,lpszDir);
}
if( !::PathIsDirectory( szPreDir ) )
{
CreateDirectory( szPreDir,NULL );
}
if(lpszDir[i] != 0)
{
RecursionDirectory(lpszDir,i);
}
return TRUE;
}
bool CFileStream::LoadFromStream()
{
file_header_s* fileHeader = (file_header_s*)memoryData;
fileHeader->strData += (DWORD)memoryData;
fileHeader->treeData += (DWORD)memoryData;
fileHeader->treeList += (DWORD)memoryData;
if(strcmp(fileHeader->Sign,SIGN_STRING)==0)
{
DWORD nCount = 0;
DWORD readOffset = 0;
for(nCount = 0;nCount < fileHeader->strCount;nCount++)
{
AllocString((char*)fileHeader->strData + readOffset);
readOffset += strlen((char*)fileHeader->strData + readOffset) +1;
}
DWORD offset=0;
if(fileHeader->treeCompSize)
{
PBYTE pTreeData = new BYTE[fileHeader->treeDataSize];
if(uncompress(pTreeData,&fileHeader->treeDataSize,(PBYTE)fileHeader->treeData,fileHeader->treeCompSize)==Z_OK)
{
RecursionTreeList((disk_tree_s*)fileHeader->treeList,(void*)pTreeData,&offset);
return true;
}
}
else
{
RecursionTreeList((disk_tree_s*)fileHeader->treeList,(void*)fileHeader->treeData,&offset);
return true;
}
}
return false;
} | 412 | 0.909123 | 1 | 0.909123 | game-dev | MEDIA | 0.509295 | game-dev | 0.996918 | 1 | 0.996918 |
Planimeter/hl2sb-src | 21,853 | src/game/server/hl2/npc_cranedriver.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "ai_network.h"
#include "ai_default.h"
#include "ai_schedule.h"
#include "ai_hull.h"
#include "ai_node.h"
#include "ai_task.h"
#include "ai_senses.h"
#include "ai_navigator.h"
#include "ai_route.h"
#include "entitylist.h"
#include "soundenvelope.h"
#include "gamerules.h"
#include "ndebugoverlay.h"
#include "soundflags.h"
#include "trains.h"
#include "globalstate.h"
#include "vehicle_base.h"
#include "npc_vehicledriver.h"
#include "vehicle_crane.h"
#include "saverestore_utlvector.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar g_debug_vehicledriver;
//=========================================================
// Custom schedules
//=========================================================
enum
{
SCHED_CRANE_RANGE_ATTACK1 = LAST_VEHICLEDRIVER_SCHED,
SCHED_CRANE_FIND_LARGE_OBJECT,
SCHED_CRANE_PICKUP_OBJECT,
SCHED_CRANE_FORCED_GO,
SCHED_CRANE_CHASE_ENEMY,
SCHED_CRANE_FORCED_DROP,
};
//=========================================================
// Custom tasks
//=========================================================
enum
{
TASK_CRANE_GET_POSITION_OVER_ENEMY = LAST_VEHICLEDRIVER_TASK,
TASK_CRANE_GET_POSITION_OVER_LASTPOSITION,
TASK_CRANE_GET_POSITION_OVER_OBJECT,
TASK_CRANE_TURN_MAGNET_OFF,
TASK_CRANE_FIND_OBJECT_TO_PICKUP,
TASK_CRANE_DROP_MAGNET,
TASK_END_FORCED_DROP,
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CNPC_CraneDriver : public CNPC_VehicleDriver
{
DECLARE_CLASS( CNPC_CraneDriver, CNPC_VehicleDriver );
public:
DECLARE_DATADESC();
DEFINE_CUSTOM_AI;
void Spawn( void );
void Activate( void );
// AI
int RangeAttack1Conditions( float flDot, float flDist );
int TranslateSchedule( int scheduleType );
int SelectSchedule( void );
void StartTask( const Task_t *pTask );
void RunTask( const Task_t *pTask );
void SetDesiredPosition( const Vector &vecPosition );
// Driving
void DriveVehicle( void );
bool OverrideMove( float flInterval );
// Inputs
void InputForcePickup( inputdata_t &inputdata );
void InputForceDrop( inputdata_t &inputdata );
protected:
CHandle<CPropCrane> m_hCrane;
EHANDLE m_hPickupTarget;
float m_flDistanceToTarget;
CUtlVector< EHANDLE > m_PreviouslyPickedUpObjects;
bool m_bForcedPickup;
bool m_bForcedDropoff;
float m_flDropWait;
float m_flReleasePause;
float m_flReleaseAt;
// Outputs
COutputEvent m_OnPickedUpObject;
COutputEvent m_OnDroppedObject;
COutputEvent m_OnPausingBeforeDrop;
};
BEGIN_DATADESC( CNPC_CraneDriver )
// Inputs
DEFINE_INPUTFUNC( FIELD_STRING, "ForcePickup", InputForcePickup ),
DEFINE_INPUTFUNC( FIELD_STRING, "ForceDrop", InputForceDrop ),
//DEFINE_FIELD( m_hCrane, FIELD_EHANDLE ),
DEFINE_FIELD( m_hPickupTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_flDistanceToTarget, FIELD_FLOAT ),
DEFINE_UTLVECTOR( m_PreviouslyPickedUpObjects, FIELD_EHANDLE ),
DEFINE_FIELD( m_bForcedPickup, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForcedDropoff, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flDropWait, FIELD_FLOAT ),
DEFINE_KEYFIELD( m_flReleasePause, FIELD_FLOAT, "releasepause" ),
DEFINE_FIELD( m_flReleaseAt, FIELD_FLOAT ),
// Outputs
DEFINE_OUTPUT( m_OnPickedUpObject, "OnPickedUpObject" ),
DEFINE_OUTPUT( m_OnDroppedObject, "OnDroppedObject" ),
DEFINE_OUTPUT( m_OnPausingBeforeDrop, "OnPausingBeforeDrop" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( npc_cranedriver, CNPC_CraneDriver );
//------------------------------------------------------------------------------
// Purpose :
//------------------------------------------------------------------------------
void CNPC_CraneDriver::Spawn( void )
{
BaseClass::Spawn();
CapabilitiesClear();
CapabilitiesAdd( bits_CAP_INNATE_RANGE_ATTACK1 );
m_flDistTooFar = 2048.0;
SetDistLook( 2048 );
m_PreviouslyPickedUpObjects.Purge();
m_hPickupTarget = NULL;
m_bForcedPickup = false;
m_bForcedDropoff = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::Activate( void )
{
BaseClass::Activate();
m_hCrane = dynamic_cast<CPropCrane*>((CBaseEntity*)m_hVehicleEntity);
if ( !m_hCrane )
{
Warning( "npc_cranedriver %s couldn't find his crane named %s.\n", STRING(GetEntityName()), STRING(m_iszVehicleName) );
UTIL_Remove( this );
return;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_CraneDriver::RangeAttack1Conditions( float flDot, float flDist )
{
if ( !HasCondition( COND_SEE_ENEMY ) )
return COND_NONE;
// Do our distance check in 2D
Vector2D vecOrigin2D( m_hCrane->GetAbsOrigin().x, m_hCrane->GetAbsOrigin().y );
Vector2D vecEnemy2D( GetEnemy()->GetAbsOrigin().x, GetEnemy()->GetAbsOrigin().y );
flDist = (vecOrigin2D - vecEnemy2D).Length();
// Maximum & Minimum size of the crane's reach
if ( flDist > MAX_CRANE_FLAT_REACH )
return COND_TOO_FAR_TO_ATTACK;
// Crane can't reach any closer than this
if ( flDist < MIN_CRANE_FLAT_REACH )
return COND_TOO_CLOSE_TO_ATTACK;
return COND_CAN_RANGE_ATTACK1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_CraneDriver::SelectSchedule( void )
{
if ( HasSpawnFlags(SF_VEHICLEDRIVER_INACTIVE) )
return BaseClass::SelectSchedule();
// If we've got an object to pickup, so go get it
if ( m_hPickupTarget )
{
// Only clear the pickup target if we managed to pick something up
if ( m_hCrane->GetTotalMassOnCrane() > 0 )
{
if ( m_bForcedPickup )
{
m_OnPickedUpObject.FireOutput( m_hPickupTarget, this );
}
// Remember what we dropped so we go try something else if we can.
m_PreviouslyPickedUpObjects.AddToTail( m_hPickupTarget );
m_hPickupTarget = NULL;
}
else
{
if ( m_NPCState == NPC_STATE_IDLE )
{
SetIdealState( NPC_STATE_ALERT );
}
return SCHED_CRANE_PICKUP_OBJECT;
}
}
// If we're currently being forced to pickup something, do only that
if ( m_bForcedPickup )
{
if ( m_hPickupTarget )
return SCHED_CRANE_PICKUP_OBJECT;
// We've picked up our target, we're waiting to be told where to put it
return SCHED_IDLE_STAND;
}
// If we've been told to drop something off, do that
if ( m_bForcedDropoff )
return SCHED_CRANE_FORCED_DROP;
switch ( m_NPCState )
{
case NPC_STATE_IDLE:
break;
case NPC_STATE_ALERT:
break;
case NPC_STATE_COMBAT:
if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
// Do we have anything on the crane? If not, look for something
if ( m_hCrane->GetTotalMassOnCrane() == 0 )
return SCHED_CRANE_FIND_LARGE_OBJECT;
// We've got something on the crane, so try and drop it on the enemy
return SCHED_CRANE_RANGE_ATTACK1;
}
// We can't attack him, so if we don't have anything on the crane, grab something
if ( m_hCrane->GetTotalMassOnCrane() == 0 )
return SCHED_CRANE_FIND_LARGE_OBJECT;
}
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_CraneDriver::TranslateSchedule( int scheduleType )
{
switch ( scheduleType )
{
case SCHED_COMBAT_FACE:
// Vehicles can't rotate, so don't try and face
return TranslateSchedule( SCHED_CHASE_ENEMY );
case SCHED_ALERT_FACE:
// Vehicles can't rotate, so don't try and face
return SCHED_ALERT_STAND;
case SCHED_FORCED_GO:
return SCHED_CRANE_FORCED_GO;
case SCHED_CHASE_ENEMY:
return SCHED_CRANE_CHASE_ENEMY;
}
return BaseClass::TranslateSchedule(scheduleType);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_WAIT_FOR_MOVEMENT:
break;
case TASK_CRANE_GET_POSITION_OVER_ENEMY:
{
if ( !GetEnemy() )
{
TaskFail(FAIL_NO_ROUTE);
return;
}
SetDesiredPosition( GetEnemy()->GetAbsOrigin() );
TaskComplete();
}
break;
case TASK_CRANE_GET_POSITION_OVER_OBJECT:
{
if ( !m_hPickupTarget )
{
TaskFail("No object to pickup!");
return;
}
SetDesiredPosition( m_hPickupTarget->GetAbsOrigin() );
TaskComplete();
}
break;
case TASK_CRANE_GET_POSITION_OVER_LASTPOSITION:
{
SetDesiredPosition( m_vecLastPosition );
TaskComplete();
}
break;
case TASK_CRANE_TURN_MAGNET_OFF:
{
// If we picked up something, and we were being forced to pick something up, fire our output
if ( m_hCrane->GetTotalMassOnCrane() > 0 && m_bForcedDropoff )
{
// Are we supposed to pause first?
if ( m_flReleasePause )
{
m_flReleaseAt = gpGlobals->curtime + m_flReleasePause;
m_OnPausingBeforeDrop.FireOutput( this, this );
return;
}
m_OnDroppedObject.FireOutput( this, this );
}
m_hCrane->TurnMagnetOff();
TaskComplete();
}
break;
case TASK_END_FORCED_DROP:
{
m_bForcedDropoff = false;
TaskComplete();
}
break;
case TASK_CRANE_FIND_OBJECT_TO_PICKUP:
{
Vector2D vecOrigin2D( m_hCrane->GetAbsOrigin().x, m_hCrane->GetAbsOrigin().y );
// Find a large physics object within our reach to pickup
float flLargestMass = 0;
CBaseEntity *pLargestEntity = NULL;
CBaseEntity *pList[1024];
Vector delta( m_flDistTooFar, m_flDistTooFar, m_flDistTooFar*2 );
int count = UTIL_EntitiesInBox( pList, 1024, m_hCrane->GetAbsOrigin() - delta, m_hCrane->GetAbsOrigin() + delta, 0 );
for ( int i = 0; i < count; i++ )
{
if ( !pList[i] )
continue;
// Ignore the crane & the magnet
if ( pList[i] == m_hCrane || pList[i] == m_hCrane->GetMagnet() )
continue;
if ( m_PreviouslyPickedUpObjects.Find( pList[i] ) != m_PreviouslyPickedUpObjects.InvalidIndex() )
continue;
// Get the VPhysics object
IPhysicsObject *pPhysics = pList[i]->VPhysicsGetObject();
if ( pPhysics && pList[i]->GetMoveType() == MOVETYPE_VPHYSICS )
{
float flMass = pPhysics->GetMass();
if ( flMass > flLargestMass && (flMass < MAXIMUM_CRANE_PICKUP_MASS) && (flMass > MINIMUM_CRANE_PICKUP_MASS) )
{
// Biggest one we've found so far
// Now make sure it's within our reach
// Do our distance check in 2D
Vector2D vecOrigin2D( m_hCrane->GetAbsOrigin().x, m_hCrane->GetAbsOrigin().y );
Vector2D vecEnemy2D( pList[i]->GetAbsOrigin().x, pList[i]->GetAbsOrigin().y );
float flDist = (vecOrigin2D - vecEnemy2D).Length();
// Maximum & Minimum size of the crane's reach
if ( flDist > MAX_CRANE_FLAT_REACH )
continue;
if ( flDist < MIN_CRANE_FLAT_REACH )
continue;
flLargestMass = flMass;
pLargestEntity = pList[i];
}
}
}
// If we didn't find anything new, clear our list of targets
if ( !pLargestEntity )
{
m_PreviouslyPickedUpObjects.Purge();
}
if ( !pLargestEntity )
{
TaskFail("Couldn't find anything to pick up!");
return;
}
m_hPickupTarget = pLargestEntity;
TaskComplete();
}
break;
case TASK_CRANE_DROP_MAGNET:
{
// Drop the magnet, but only end the task once the magnet's back up
m_pVehicleInterface->NPC_SecondaryFire();
// Don't check to see if drop's finished until this time is up.
// This is necessary because the crane won't start dropping this
// frame, and our cranedriver will think it's finished immediately.
m_flDropWait = gpGlobals->curtime + 0.5;
}
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_WAIT_FOR_MOVEMENT:
{
// Is the magnet over the target, and are we not moving too fast?
AngularImpulse angVel;
Vector vecVelocity;
CBaseEntity *pMagnet = m_hCrane->GetMagnet();
IPhysicsObject *pVehiclePhysics = pMagnet->VPhysicsGetObject();
pVehiclePhysics->GetVelocity( &vecVelocity, &angVel );
float flVelocity = 100;
float flDistance = 90;
// More accurate on forced drops
if ( m_bForcedPickup || m_bForcedDropoff )
{
flVelocity = 10;
flDistance = 30;
}
if ( m_flDistanceToTarget < flDistance && m_hCrane->GetTurnRate() < 0.1 && vecVelocity.Length() < flVelocity )
{
TaskComplete();
}
}
break;
case TASK_CRANE_DROP_MAGNET:
{
// Wait for the magnet to get back up
if ( m_flDropWait < gpGlobals->curtime && !m_hCrane->IsDropping() )
{
TaskComplete();
}
}
break;
case TASK_CRANE_TURN_MAGNET_OFF:
{
// We're waiting for the pause length before dropping whatever's on our magnet
if ( gpGlobals->curtime > m_flReleaseAt )
{
if ( m_bForcedDropoff )
{
m_OnDroppedObject.FireOutput( this, this );
}
m_hCrane->TurnMagnetOff();
TaskComplete();
}
}
break;
default:
BaseClass::RunTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CNPC_CraneDriver::OverrideMove( float flInterval )
{
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::SetDesiredPosition( const Vector &vecPosition )
{
m_vecDesiredPosition = vecPosition;
m_flDistanceToTarget = 999;
}
//-----------------------------------------------------------------------------
// Purpose: This takes the current place the NPC's trying to get to, figures out
// what keys to press to get the vehicle to go there, and then sends
// them to the vehicle.
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::DriveVehicle( void )
{
// No targets?
if ( !GetEnemy() && m_vecDesiredPosition == vec3_origin )
return;
Vector vecTarget = m_vecDesiredPosition;
// Track our targets
if ( m_hPickupTarget )
{
vecTarget = m_hPickupTarget->GetAbsOrigin();
}
else if ( !m_bForcedPickup && !m_bForcedDropoff && GetEnemy() )
{
vecTarget = GetEnemy()->GetAbsOrigin();
}
// Move the crane over the target
// Use the crane type as a targeting point
Vector vecCraneTip = m_hCrane->GetCraneTipPosition();
Vector2D vecCraneTip2D( vecCraneTip.x, vecCraneTip.y );
Vector2D vecTarget2D( vecTarget.x, vecTarget.y );
Vector2D vecOrigin2D( m_hCrane->GetAbsOrigin().x, m_hCrane->GetAbsOrigin().y );
if ( g_debug_vehicledriver.GetInt() )
{
NDebugOverlay::Box( vecTarget, -Vector(50,50,50), Vector(50,50,50), 0,255,0, true, 0.1 );
NDebugOverlay::Box( vecCraneTip, -Vector(2,2,5000), Vector(2,2,5), 0,255,0, true, 0.1 );
NDebugOverlay::Box( vecTarget, -Vector(2,2,5), Vector(2,2,5000), 0,255,0, true, 0.1 );
}
// Store off the distance to our target
m_flDistanceToTarget = (vecTarget2D - vecCraneTip2D).Length();
// First determine whether we need to extend / retract the arm
float flDistToTarget = (vecOrigin2D - vecTarget2D).LengthSqr();
float flDistToCurrent = (vecOrigin2D - vecCraneTip2D).LengthSqr();
float flDelta = fabs(flDistToTarget - flDistToCurrent);
// Slow down as we get closer, but do it based upon our current extension rate
float flMinDelta = 50 + (50 * fabs(m_hCrane->GetExtensionRate() / CRANE_EXTENSION_RATE_MAX));
flMinDelta *= flMinDelta;
if ( flDelta > flMinDelta )
{
if ( flDistToCurrent > flDistToTarget )
{
// Retract
m_pVehicleInterface->NPC_ThrottleReverse();
}
else if ( flDistToCurrent < flDistToTarget )
{
// Extend
m_pVehicleInterface->NPC_ThrottleForward();
}
}
else
{
m_pVehicleInterface->NPC_ThrottleCenter();
}
// Then figure out if we need to rotate. Do it all in 2D space.
Vector vecRight, vecForward;
m_hCrane->GetVectors( &vecForward, &vecRight, NULL );
vecRight.z = 0;
vecForward.z = 0;
VectorNormalize( vecRight );
VectorNormalize( vecForward );
Vector vecToTarget = ( vecTarget - m_hCrane->GetAbsOrigin() );
vecToTarget.z = 0;
VectorNormalize( vecToTarget );
float flDotRight = DotProduct( vecRight, vecToTarget );
float flDotForward = DotProduct( vecForward, vecToTarget );
// Start slowing if we're going to hit the point soon
float flTurnInDeg = RAD2DEG( acos(flDotForward) );
float flSpeed = m_hCrane->GetMaxTurnRate() * (flTurnInDeg / 15.0);
flSpeed = MIN( m_hCrane->GetMaxTurnRate(), flSpeed );
if ( fabs(flSpeed) < 0.05 )
{
// We're approaching the target, so stop turning
m_pVehicleInterface->NPC_TurnCenter();
}
else
{
if ( flDotRight < 0 )
{
// Turn right
m_pVehicleInterface->NPC_TurnRight( flSpeed );
}
else if ( flDotRight > 0 )
{
// Turn left
m_pVehicleInterface->NPC_TurnLeft( flSpeed );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Force the driver to pickup a specific entity
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::InputForcePickup( inputdata_t &inputdata )
{
string_t iszPickupName = inputdata.value.StringID();
if ( iszPickupName != NULL_STRING )
{
// Turn the magnet off now to drop anything we might have already on the magnet
m_hCrane->TurnMagnetOff();
m_hPickupTarget = gEntList.FindEntityByName( NULL, iszPickupName, NULL, inputdata.pActivator, inputdata.pCaller );
m_bForcedPickup = true;
m_bForcedDropoff = false;
SetCondition( COND_PROVOKED );
CLEARBITS( m_spawnflags, SF_VEHICLEDRIVER_INACTIVE );
}
}
//-----------------------------------------------------------------------------
// Purpose: Force the driver to drop his held entity at a specific point
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_CraneDriver::InputForceDrop( inputdata_t &inputdata )
{
string_t iszDropName = inputdata.value.StringID();
if ( iszDropName != NULL_STRING )
{
CBaseEntity *pEntity = gEntList.FindEntityByName( NULL, iszDropName, NULL, inputdata.pActivator, inputdata.pCaller );
if ( !pEntity )
{
Warning("Crane couldn't find entity named %s\n", STRING(iszDropName) );
return;
}
m_bForcedPickup = false;
m_bForcedDropoff = true;
SetDesiredPosition( pEntity->GetAbsOrigin() );
SetCondition( COND_PROVOKED );
CLEARBITS( m_spawnflags, SF_VEHICLEDRIVER_INACTIVE );
}
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_cranedriver, CNPC_CraneDriver )
//Tasks
DECLARE_TASK( TASK_CRANE_GET_POSITION_OVER_ENEMY )
DECLARE_TASK( TASK_CRANE_GET_POSITION_OVER_LASTPOSITION )
DECLARE_TASK( TASK_CRANE_GET_POSITION_OVER_OBJECT )
DECLARE_TASK( TASK_CRANE_TURN_MAGNET_OFF )
DECLARE_TASK( TASK_END_FORCED_DROP )
DECLARE_TASK( TASK_CRANE_FIND_OBJECT_TO_PICKUP )
DECLARE_TASK( TASK_CRANE_DROP_MAGNET )
//Schedules
//==================================================
// SCHED_ANTLION_CHASE_ENEMY_BURROW
//==================================================
DEFINE_SCHEDULE
(
SCHED_CRANE_RANGE_ATTACK1,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY"
" TASK_CRANE_GET_POSITION_OVER_ENEMY 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_CRANE_TURN_MAGNET_OFF 0"
" "
" Interrupts"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_ENEMY_OCCLUDED"
" COND_ENEMY_TOO_FAR"
" COND_PROVOKED"
)
DEFINE_SCHEDULE
(
SCHED_CRANE_FIND_LARGE_OBJECT,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY"
" TASK_CRANE_FIND_OBJECT_TO_PICKUP 0"
" "
" Interrupts"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_ENEMY_OCCLUDED"
" COND_ENEMY_TOO_FAR"
)
DEFINE_SCHEDULE
(
SCHED_CRANE_PICKUP_OBJECT,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY"
" TASK_CRANE_GET_POSITION_OVER_OBJECT 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_CRANE_DROP_MAGNET 0"
" "
" Interrupts"
" COND_ENEMY_DEAD"
" COND_NEW_ENEMY"
" COND_ENEMY_OCCLUDED"
" COND_ENEMY_TOO_FAR"
" COND_PROVOKED"
)
DEFINE_SCHEDULE
(
SCHED_CRANE_FORCED_GO,
" Tasks"
" TASK_CRANE_GET_POSITION_OVER_LASTPOSITION 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_CRANE_TURN_MAGNET_OFF 0"
" TASK_WAIT 2"
" "
" Interrupts"
)
DEFINE_SCHEDULE
(
SCHED_CRANE_CHASE_ENEMY,
" Tasks"
" TASK_CRANE_GET_POSITION_OVER_ENEMY 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_WAIT 5"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_CAN_RANGE_ATTACK1"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_TASK_FAILED"
" COND_LOST_ENEMY"
" COND_PROVOKED"
)
DEFINE_SCHEDULE
(
SCHED_CRANE_FORCED_DROP,
" Tasks"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_CRANE_TURN_MAGNET_OFF 0"
" TASK_END_FORCED_DROP 0"
" TASK_WAIT 2"
" "
" Interrupts"
)
AI_END_CUSTOM_NPC()
| 412 | 0.983792 | 1 | 0.983792 | game-dev | MEDIA | 0.954372 | game-dev | 0.973883 | 1 | 0.973883 |
GaijinEntertainment/DagorEngine | 2,217 | prog/gameLibs/publicInclude/render/wind/clusterWind.h | //
// Dagor Engine 6.5 - Game Libraries
// Copyright (C) Gaijin Games KFT. All rights reserved.
//
#pragma once
#include <generic/dag_tab.h>
#include <math/dag_Point3.h>
#include <math/dag_Point4.h>
#include <generic/dag_carray.h>
#include <EASTL/unique_ptr.h>
#include <render/wind/clusterWindCascade.h>
#include <osApiWrappers/dag_spinlock.h>
#define MAX_CLUSTER_CPP 254
class DataBlock;
class ClusterWindRenderer;
class float3;
class ClusterWind
{
public:
struct ClusterDesc // used for cpu
{
Point4 sphere;
float power; // mult bending [1,4]
float time;
float maxTime;
};
explicit ClusterWind(bool need_historical_buffer);
~ClusterWind();
private:
eastl::unique_ptr<ClusterWindRenderer> clusterWindRenderer;
carray<ClusterDesc, MAX_CLUSTER_CPP> clusterWinds;
int actualClusterWindsCount;
bool isInit;
OSSpinlock clusterToGridSpinLock;
bool checkAndFillGridBox(const IPoint2 &boxXY, int cascadeNo, int clusterId);
bool isPriority(const ClusterDesc &value, const ClusterDesc &toCompare, int boxId, int cascadeNo);
void updateAfterPositionChange(ClusterWindCascade::ClusterWindGridUpdateResult gridPoisitionResult, int cascadeNo);
int addClusterToList(const Point3 &pos, float r, float power);
void removeClusterFromList(int id);
void recalculateWholeCascade(const Point3 &pos, int cascadeNo);
public:
float particlesForceMul = 1.f;
int actualDirectionnalClusterWindCount;
carray<int, MAX_CLUSTER_CPP> directionnalWindId; // for faster directionnal wind search
Tab<ClusterWindCascade> clusterWindCascades;
void addClusterToGrid(const Point3 &pos, float r, float power, int clusterId = -1);
void initClusterWinds(Tab<ClusterWindCascade::Desc> &desc);
void updateGridPosition(const Point3 &pos);
void updateClusterWinds(float dt);
ClusterWind::ClusterDesc getClusterDescAt(int at);
float3 getBlastAtPosForParticle(const float3 &pos);
Point3 getBlastAtPosForParticle(const Point3 &pos);
Point3 getBlastAtPosForAntenna(const Point3 &pos);
void loadBendingMultConst(float treeMult, float impostorMult, float grassMult, float treeAnimationMult, float grassAnimationMult);
void updateRenderer();
void flipClusterWindSimArray();
};
| 412 | 0.927232 | 1 | 0.927232 | game-dev | MEDIA | 0.168339 | game-dev | 0.568198 | 1 | 0.568198 |
mimilewis/MapleStory143 | 4,208 | src/main/java/scripting/item/ItemActionManager.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package scripting.item;
import client.MapleClient;
import client.inventory.Item;
import client.skills.Skill;
import client.skills.SkillFactory;
import constants.ItemConstants;
import constants.JobConstants;
import constants.ScriptType;
import scripting.npc.NPCConversationManager;
import server.MapleInventoryManipulator;
import tools.MaplePacketCreator;
import javax.script.Invocable;
/**
* @author PlayDK
*/
public class ItemActionManager extends NPCConversationManager {
private final Item item;
/**
* @param c
* @param npc
* @param item
* @param iv
*/
public ItemActionManager(MapleClient c, int npc, Item item, Invocable iv) {
super(c, npc, String.valueOf(item.getItemId()), ScriptType.ITEM, iv);
this.item = item;
}
@Override
public void dispose() {
dispose(-1);
}
public void dispose(int remove) {
if (remove == 0) {
this.usedAll();
} else if (remove > 0) {
this.used(remove);
}
ItemScriptManager.getInstance().dispose(getClient());
}
/**
* @return
*/
public Item getItem() {
return item;
}
/**
* @return
*/
public int getItemId() {
return item.getItemId();
}
public short getPosition() {
return item.getPosition();
}
public boolean used() {
return used(1);
}
public boolean used(int q) {
return MapleInventoryManipulator.removeFromSlot(getClient(), ItemConstants.getInventoryType(getItemId()), getPosition(), (short) q, true, false);
}
/**
* 删除一个道具
*/
public void remove() {
remove(1);
}
/**
* 删除指定数量的道具
*
* @param quantity 数量
*/
public void remove(int quantity) {
used(quantity);
}
public boolean usedAll() {
return MapleInventoryManipulator.removeFromSlot(getClient(), ItemConstants.getInventoryType(getItemId()), getPosition(), item.getQuantity(), true, false);
}
public String getSkillMenu(int skillMaster) {
StringBuilder sb = new StringBuilder();
getPlayer().getSkills().forEach((key, value) -> {
Skill skill = SkillFactory.getSkill(key);
if (JobConstants.getSkillBookByJob(key / 10000) > 2 && skill.getMaxLevel() > 10 && value.masterlevel < skill.getMaxLevel()) {
if (skillMaster > 20) {
if (value.masterlevel < 30 && value.masterlevel >= 20 && skill.getMaxLevel() > 20) {
sb.append("\r\n#L").append(key).append("# #s").append(key).append("# #fn黑体##fs14##e#q").append(key).append("##n#fs##fn##l");
}
} else if (value.masterlevel < 20) {
sb.append("\r\n#L").append(key).append("# #s").append(key).append("# #fn黑体##fs14##e#q").append(key).append("##n#fs##fn##l");
}
}
});
return sb.toString();
}
public boolean canUseSkillBook(int skillId, int masterLevel) {
if (masterLevel > 0) {
Skill skill = SkillFactory.getSkill(skillId);
if (getPlayer().getSkillLevel(skill) >= skill.getMaxLevel()) {
return false;
}
int skillLevel = getPlayer().getSkillLevel(skill);
if (skillLevel >= 5 && masterLevel == 20 || skillLevel >= 15 && masterLevel == 30) {
return true;
}
}
return false;
}
public void useSkillBook(int skillId, int masterLevel) {
Skill skill = SkillFactory.getSkill(skillId);
masterLevel = masterLevel > skill.getMaxLevel() ? skill.getMaxLevel() : masterLevel;
getPlayer().changeSingleSkillLevel(skill, getPlayer().getSkillLevel(skill), (byte) masterLevel);
getPlayer().getMap().broadcastMessage(MaplePacketCreator.useSkillBook(getPlayer(), 0, 0, true, true));
enableActions();
}
public void useFailed() {
getMap().broadcastMessage(MaplePacketCreator.useSkillBook(getPlayer(), 0, 0, true, false));
enableActions();
}
}
| 412 | 0.710543 | 1 | 0.710543 | game-dev | MEDIA | 0.948241 | game-dev | 0.938852 | 1 | 0.938852 |
ChaoticOnyx/OnyxBay | 22,296 | code/modules/mining/mine_turfs.dm | var/list/mining_walls = list()
var/list/mining_floors = list()
/**********************Mineral deposits**************************/
/turf/unsimulated/mineral
name = "impassable rock"
icon = 'icons/turf/walls.dmi'
icon_state = "rock-dark"
blocks_air = 1
density = 1
opacity = 1
/turf/simulated/mineral //Rock piece
name = "rock"
icon = 'icons/turf/walls.dmi'
icon_state = "rock"
initial_gas = null
opacity = 1
density = 1
blocks_air = 1
temperature = 0 CELSIUS
var/mined_turf = /turf/simulated/floor/asteroid
var/ore/mineral
var/last_act = 0
var/rock_type = ""
var/durability = 100 //How many hits can our rock take
var/datum/geosample/geologic_data
var/excavation_level = 0
var/list/finds
var/next_rock = 0
var/archaeo_overlay = ""
var/excav_overlay = ""
var/obj/item/last_find
var/datum/artifact_find/artifact_find
var/image/ore_overlay
has_resources = 1
var/ore_left = 0
/turf/simulated/mineral/medium
icon_state = "rock-medium"
rock_type = "-medium"
durability = 200
/turf/simulated/mineral/hard
icon_state = "rock-hard"
rock_type = "-hard"
durability = 300
/turf/simulated/mineral/Initialize()
. = ..()
if (!mining_walls["[src.z]"])
mining_walls["[src.z]"] = list()
mining_walls["[src.z]"] += src
update_icon()
/turf/simulated/mineral/Destroy()
if (mining_walls["[src.z]"])
mining_walls["[src.z]"] -= src
return ..()
/turf/simulated/mineral/can_build_cable()
return !density
/turf/simulated/mineral/is_plating()
return 1
/turf/simulated/mineral/on_update_icon(update_neighbors)
if(!mineral)
SetName(initial(name))
icon_state = initial(icon_state)
else
SetName("[mineral.display_name] deposit")
ClearOverlays()
for(var/direction in GLOB.cardinal)
var/turf/turf_to_check = get_step(src,direction)
if(update_neighbors && istype(turf_to_check, /turf/simulated/floor/asteroid))
var/turf/simulated/floor/asteroid/T = turf_to_check
T.updateMineralOverlays()
else if(istype(turf_to_check, /turf/space) || istype(turf_to_check, /turf/simulated/floor) || istype(turf_to_check, /turf/simulated/open))
var/image/rock_side = image('icons/turf/walls.dmi', "rock_side[rock_type]", dir = turn(direction, 180))
rock_side.turf_decal_layerise()
switch(direction)
if(NORTH)
rock_side.pixel_y += world.icon_size
if(SOUTH)
rock_side.pixel_y -= world.icon_size
if(EAST)
rock_side.pixel_x += world.icon_size
if(WEST)
rock_side.pixel_x -= world.icon_size
AddOverlays(rock_side)
if(ore_overlay)
AddOverlays(ore_overlay)
if(excav_overlay)
AddOverlays(excav_overlay)
if(archaeo_overlay)
AddOverlays(archaeo_overlay)
/turf/simulated/mineral/ex_act(severity)
switch(severity)
if(2.0)
if(prob(70))
if(mineral)
ore_left -= 1 //Some of the stuff gets blown up
GetDrilled()
if(1.0)
if(mineral)
ore_left -= 2 //Some of the stuff gets blown up
GetDrilled()
/turf/simulated/mineral/bullet_act(obj/item/projectile/Proj)
// Emitter blasts
if(istype(Proj, /obj/item/projectile/beam/emitter))
durability -= 30
if(durability <= 0) // 3 blasts per basic tile
if(mineral)
ore_left -= 1
GetDrilled()
/turf/simulated/mineral/Bumped(AM)
. = ..()
if(istype(AM,/mob/living/carbon/human))
var/mob/living/carbon/human/H = AM
if((istype(H.l_hand, /obj/item/pickaxe/drill)) && (!H.hand))
attackby(H.l_hand, H)
else if((istype(H.r_hand, /obj/item/pickaxe/drill)) && H.hand)
attackby(H.r_hand, H)
else if(istype(AM,/mob/living/silicon/robot))
var/mob/living/silicon/robot/R = AM
if(istype(R.module_active, /obj/item/pickaxe/drill))
attackby(R.module_active, R)
else if(istype(AM, /obj/mecha))
var/obj/mecha/M = AM
if(istype(M.selected, /obj/item/mecha_parts/mecha_equipment/tool/drill))
M.selected.action(src)
/turf/simulated/mineral/proc/MineralSpread()
if(mineral && mineral.spread)
for(var/trydir in GLOB.cardinal)
if(prob(mineral.spread_chance))
var/turf/simulated/mineral/target_turf = get_step(src, trydir)
if(istype(target_turf) && !target_turf.mineral)
target_turf.mineral = mineral
target_turf.UpdateMineral()
target_turf.MineralSpread()
/turf/simulated/mineral/proc/UpdateMineral()
clear_ore_effects()
ore_overlay = image('icons/obj/mining.dmi', "rock_[mineral.icon_tag]")
ore_overlay.appearance_flags = DEFAULT_APPEARANCE_FLAGS | RESET_COLOR
ore_overlay.turf_decal_layerise()
ore_left = mineral.result_amount
update_icon()
if(mineral.icon_tag == "diamond")
explosion_block = 3
//Not even going to touch this pile of spaghetti
/turf/simulated/mineral/attackby(obj/item/W, mob/user)
if(!user.IsAdvancedToolUser())
to_chat(usr, FEEDBACK_YOU_LACK_DEXTERITY)
return
if(istype(W, /obj/item/device/core_sampler))
geologic_data.UpdateNearbyArtifactInfo(src)
var/obj/item/device/core_sampler/C = W
C.sample_item(src, user)
return
if(istype(W, /obj/item/device/depth_scanner))
var/obj/item/device/depth_scanner/D = W
D.scan_atom(user, src)
return
if(istype(W, /obj/item/device/measuring_tape))
var/obj/item/device/measuring_tape/P = W
user.visible_message(SPAN_NOTICE("\The [user] extends [P] towards [src]."), SPAN_NOTICE("You extend [P] towards [src].</span>"))
if(do_after(user, 10, src))
to_chat(user, SPAN_NOTICE("\The [src] has been excavated to a depth of [excavation_level]cm."))
return
if(istype(W, /obj/item/pickaxe))
if(!istype(user.loc, /turf))
return
var/obj/item/pickaxe/P = W
if(!istype(P, /obj/item/pickaxe/drill))
user.setClickCooldown(DEFAULT_ATTACK_COOLDOWN)
else
var/obj/item/pickaxe/drill/D = P
if(last_act + D.digspeed > world.time) //Prevents message spam
return
last_act = world.time
playsound(user, P.drill_sound, 20, 1)
var/newDepth = excavation_level + P.excavation_amount // Used commonly below
//handle any archaeological finds we might uncover
var/fail_message = ""
if(finds && finds.len)
var/datum/find/F = finds[1]
if(newDepth > F.excavation_required) // Digging too deep can break the item. At least you won't summon a Balrog (probably)
fail_message = ". <b>[pick("There is a crunching noise", "[W] collides with some different rock", "Part of the rock face crumbles away", "Something breaks under [W]")]</b>"
to_chat(user, "<span class='notice'>You are digging \the [src][fail_message].</span>")
if(fail_message && prob(90))
if(prob(25))
excavate_find(prob(5), finds[1])
else if(prob(50))
finds.Remove(finds[1])
if(prob(50))
artifact_debris()
if(istype(P, /obj/item/pickaxe/drill))
var/obj/item/pickaxe/drill/D = P
if(!do_after(user, D.digspeed, src))
return
durability -= P.power
if(finds && finds.len)
var/datum/find/F = finds[1]
if(newDepth == F.excavation_required) // When the pick hits that edge just right, you extract your find perfectly, it's never confined in a rock
excavate_find(1, F)
else if(newDepth > F.excavation_required - F.clearance_range) // Not quite right but you still extract your find, the closer to the bottom the better, but not above 80%
excavate_find(prob(80 * (F.excavation_required - newDepth) / F.clearance_range), F)
if(istype(P, /obj/item/pickaxe/drill))
to_chat(user, "<span class='notice'>You finish [P.drill_verb] \the [src].</span>")
if(newDepth >= 200)
excavation_level = 200
if(durability <= 0 || excavation_level >= 200) // This means the rock is mined out fully
var/obj/structure/boulder/B
if(artifact_find)
if(excavation_level > 0 || prob(15))
//boulder with an artifact inside
B = new(src)
if(artifact_find)
B.artifact_find = artifact_find
else
artifact_debris(1)
else if(prob(5))
//Empty boulder
B = new(src)
if(B)
GetDrilled(0)
else
GetDrilled(1)
return
else if(mineral && durability < initial(durability) - initial(durability) / max(ore_left, 1))
DropMineral(user.dir)
excavation_level += P.excavation_amount
var/updateIcon = 0
//Archaeo overlays
if(!archaeo_overlay && finds && finds.len)
var/datum/find/F = finds[1]
if(F.excavation_required <= excavation_level + F.view_range)
archaeo_overlay = "overlay_archaeo[rand(1,3)]"
updateIcon = 1
else if(archaeo_overlay && (!finds || !finds.len))
archaeo_overlay = null
updateIcon = 1
//There's got to be a better way to do this
var/update_excav_overlay = FALSE
if (excavation_level >= 150 && (excavation_level - P.excavation_amount < 150) || \
excavation_level >= 100 && (excavation_level - P.excavation_amount < 100) || \
excavation_level >= 50 && (excavation_level - P.excavation_amount < 50))
update_excav_overlay = TRUE
//update overlays displaying excavation level
if( !(excav_overlay && excavation_level > 0) || update_excav_overlay )
var/excav_quadrant = round(excavation_level / 50) + 1
excav_overlay = "overlay_excv[excav_quadrant]_[rand(1,3)]"
updateIcon = 1
if(updateIcon)
update_icon()
//drop some rocks
next_rock += P.excavation_amount
while(next_rock > 50)
next_rock -= 50
var/obj/item/ore/O = new(src)
geologic_data.UpdateNearbyArtifactInfo(src)
O.geologic_data = geologic_data
if(istype(W, /obj/item/autochisel))
if(last_act + 80 > world.time)//prevents message spam
return
last_act = world.time
to_chat(user, "<span class='warning'>You start chiselling [src] into a sculptable block.</span>")
if(!do_after(user,80))
return
if (!istype(src, /turf/simulated/mineral))
return
to_chat(user, "<span class='notice'>You finish chiselling [src] into a sculptable block.</span>")
new /obj/structure/sculpting_block(src)
GetDrilled(1)
else
return ..()
/turf/simulated/mineral/proc/clear_ore_effects()
CutOverlays(ore_overlay)
ore_overlay = null
/turf/simulated/mineral/proc/DropMineral(direction = null)
if(!mineral || ore_left <= 0)
return
var/obj/item/ore/O = null
if(direction)
O = new mineral.ore(get_step(src, turn(direction, 180)))
else
O = new mineral.ore(src)
ore_left -= 1
if(!ore_left)
clear_ore_effects()
if(O && geologic_data && istype(O))
geologic_data.UpdateNearbyArtifactInfo(src)
O.geologic_data = geologic_data
return O
/turf/simulated/mineral/proc/GetDrilled(artifact_fail = 0)
//var/destroyed = 0 //used for breaking strange rocks
if(mineral && ore_left)
while(ore_left > 0)
DropMineral()
if(artifact_find && artifact_fail)
for(var/mob/living/M in range(src, 200))
to_chat(M, "<font color='red'><b>[pick("A high pitched [pick("keening","wailing","whistle")]","A rumbling noise like [pick("thunder","heavy machinery")]")] somehow penetrates your mind before fading away!</b></font>")
//Add some rubble, you did just clear out a big chunk of rock.
var/turf/simulated/floor/asteroid/N = ChangeTurf(mined_turf)
if(istype(N))
N.overlay_detail = "asteroid[rand(0,9)]"
N.updateMineralOverlays(1)
for(var/direction in GLOB.cardinal)
var/turf/simulated/mineral/T = get_step(src,direction)
if(istype(T))
T.update_icon()
/turf/simulated/mineral/proc/excavate_find(prob_clean = 0, datum/find/F)
//many finds are ancient and thus very delicate - luckily there is a specialised energy suspension field which protects them when they're being extracted
if(prob(F.prob_delicate))
var/obj/effect/suspension_field/S = locate() in src
if(!S)
visible_message("<span class='danger'>[pick("An object in the rock crumbles away into dust.","Something falls out of the rock and shatters onto the ground.")]</span>")
finds.Remove(F)
return
//with skill and luck, players can cleanly extract finds
//otherwise, they come out inside a chunk of rock
if(prob_clean)
var/find = get_archeological_find_by_findtype(F.find_type)
new find(src)
else
var/obj/item/ore/strangerock/rock = new(src, inside_item_type = F.find_type)
geologic_data.UpdateNearbyArtifactInfo(src)
rock.geologic_data = geologic_data
finds.Remove(F)
/turf/simulated/mineral/proc/artifact_debris(severity = 0)
//cael's patented random limited drop componentized loot system!
//sky's patented not-fucking-retarded overhaul!
//Give a random amount of loot from 1 to 3 or 5, varying on severity.
for(var/j in 1 to rand(1, 3 + max(min(severity, 1), 0) * 2))
switch(rand(1,7))
if(1)
var/obj/item/stack/rods/R = new(src)
R.amount = rand(5,25)
if(2)
var/obj/item/stack/material/plasteel/R = new(src)
R.amount = rand(5,25)
if(3)
var/obj/item/stack/material/steel/R = new(src)
R.amount = rand(5,25)
if(4)
var/obj/item/stack/material/plasteel/R = new(src)
R.amount = rand(5,25)
if(5)
var/quantity = rand(1,3)
for(var/i=0, i<quantity, i++)
new /obj/item/material/shard(src)
if(6)
var/quantity = rand(1,3)
for(var/i=0, i<quantity, i++)
new /obj/item/material/shard/plasma(src)
if(7)
var/obj/item/stack/material/uranium/R = new(src)
R.amount = rand(5,25)
/turf/simulated/mineral/random
name = "Mineral deposit"
var/mineralChance = 100 //10 //means 10% chance of this plot changing to a mineral deposit
var/mineralSpawnChanceList = list(
MATERIAL_URANIUM = 5,
MATERIAL_PLATINUM = 5,
MATERIAL_IRON = 35,
MATERIAL_CARBON = 35,
MATERIAL_DIAMOND = 1,
MATERIAL_GOLD = 5,
MATERIAL_SILVER = 5,
MATERIAL_PLASMA = 10
)
/turf/simulated/mineral/random/Initialize()
. = ..()
if(prob(mineralChance) && !mineral)
var/mineral_name = util_pick_weight(mineralSpawnChanceList) //temp mineral name
mineral_name = lowertext(mineral_name)
if(mineral_name && (mineral_name in GLOB.ore_data))
mineral = GLOB.ore_data[mineral_name]
UpdateMineral()
MineralSpread()
/turf/simulated/mineral/random/high_chance
mineralChance = 100 //25
mineralSpawnChanceList = list(
MATERIAL_URANIUM = 10,
MATERIAL_PLATINUM = 10,
MATERIAL_IRON = 20,
MATERIAL_CARBON = 20,
MATERIAL_DIAMOND = 2,
MATERIAL_GOLD = 10,
MATERIAL_SILVER = 10,
MATERIAL_PLASMA = 20
)
/turf/simulated/mineral/frozen //Rock piece
name = "rock"
icon = 'icons/turf/walls.dmi'
icon_state = "rock"
initial_gas = list("oxygen" = MOLES_O2STANDARD, "nitrogen" = MOLES_N2STANDARD)
opacity = 1
density = 1
blocks_air = 1
temperature = 0 CELSIUS
mined_turf = /turf/simulated/floor/natural/frozenground/cave
/turf/simulated/mineral/frozen/medium
icon_state = "rock-medium"
rock_type = "-medium"
durability = 200
/turf/simulated/mineral/frozen/hard
icon_state = "rock-hard"
rock_type = "-hard"
durability = 300
/turf/simulated/mineral/frozen/random
name = "Mineral deposit"
var/mineralChance = 100 //10 //means 10% chance of this plot changing to a mineral deposit
var/mineralSpawnChanceList = list(
MATERIAL_URANIUM = 5,
MATERIAL_PLATINUM = 5,
MATERIAL_IRON = 35,
MATERIAL_CARBON = 35,
MATERIAL_DIAMOND = 1,
MATERIAL_GOLD = 5,
MATERIAL_SILVER = 5,
MATERIAL_PLASMA = 10
)
/turf/simulated/mineral/frozen/random/Initialize()
. = ..()
if(prob(mineralChance) && !mineral)
var/mineral_name = util_pick_weight(mineralSpawnChanceList) //temp mineral name
mineral_name = lowertext(mineral_name)
if(mineral_name && (mineral_name in GLOB.ore_data))
mineral = GLOB.ore_data[mineral_name]
UpdateMineral()
MineralSpread()
/turf/simulated/mineral/frozen/random/high_chance
mineralChance = 100 //25
mineralSpawnChanceList = list(
MATERIAL_URANIUM = 10,
MATERIAL_PLATINUM = 10,
MATERIAL_IRON = 20,
MATERIAL_CARBON = 20,
MATERIAL_DIAMOND = 2,
MATERIAL_GOLD = 10,
MATERIAL_SILVER = 10,
MATERIAL_PLASMA = 20
)
/turf/simulated/mineral/air
name = "rock"
icon = 'icons/turf/walls.dmi'
icon_state = "rock"
initial_gas = list("oxygen" = MOLES_O2STANDARD, "nitrogen" = MOLES_N2STANDARD)
opacity = 1
density = 1
blocks_air = 1
temperature = 30 CELSIUS
mined_turf = /turf/simulated/floor/asteroid/air
/**********************Asteroid**************************/
// Setting icon/icon_state initially will use these values when the turf is built on/replaced.
// This means you can put grass on the asteroid etc.
/turf/simulated/floor/asteroid
name = "sand"
desc = "Gritty and unpleasant."
icon = 'icons/turf/flooring/asteroid.dmi'
icon_state = "asteroid"
base_name = "sand"
base_desc = "Gritty and unpleasant."
base_icon = 'icons/turf/flooring/asteroid.dmi'
base_icon_state = "asteroid"
initial_flooring = null
initial_gas = null
temperature = TCMB
var/dug = 0 //0 = has not yet been dug, 1 = has already been dug
var/overlay_detail
has_resources = 1
footstep_sound = SFX_FOOTSTEP_ASTEROID
/turf/simulated/floor/asteroid/Initialize()
. = ..()
if (!mining_floors["[src.z]"])
mining_floors["[src.z]"] = list()
mining_floors["[src.z]"] += src
if(prob(20))
overlay_detail = "asteroid[rand(0,9)]"
updateMineralOverlays()
/turf/simulated/floor/asteroid/Destroy()
if (mining_floors["[src.z]"])
mining_floors["[src.z]"] -= src
return ..()
/turf/simulated/floor/asteroid/ex_act(severity)
switch(severity)
if(3.0)
return
if(2.0)
if (prob(70))
gets_dug()
if(1.0)
gets_dug()
return
/turf/simulated/floor/asteroid/is_plating()
return !density
/turf/simulated/floor/asteroid/attackby(obj/item/W as obj, mob/user as mob)
if(!W || !user)
return 0
var/list/usable_tools = list(
/obj/item/shovel,
/obj/item/pickaxe/drill/diamonddrill,
/obj/item/pickaxe/drill,
/obj/item/pickaxe/drill/borgdrill
)
var/valid_tool
for(var/valid_type in usable_tools)
if(istype(W,valid_type))
valid_tool = 1
break
if(valid_tool)
if (dug)
to_chat(user, "<span class='warning'>This area has already been dug</span>")
return
var/turf/T = user.loc
if (!(istype(T)))
return
to_chat(user, "<span class='warning'>You start digging.</span>")
if(!do_after(user,40, src)) return
to_chat(user, "<span class='notice'>You dug a hole.</span>")
gets_dug()
else if(istype(W,/obj/item/storage/ore))
var/obj/item/storage/ore/S = W
if(S.collection_mode)
for(var/obj/item/ore/O in contents)
O.attackby(W,user)
return
else if(istype(W,/obj/item/storage/bag/fossils))
var/obj/item/storage/bag/fossils/S = W
if(S.collection_mode)
for(var/obj/item/fossil/F in contents)
F.attackby(W,user)
return
else
..(W,user)
return
/turf/simulated/floor/asteroid/proc/gets_dug()
if(dug)
return
for(var/i=0;i<(rand(3)+2);i++)
new /obj/item/ore/glass(src)
dug = 1
icon_state = "asteroid_dug"
return
/turf/simulated/floor/asteroid/proc/updateMineralOverlays(update_neighbors)
ClearOverlays()
var/list/step_overlays = list("n" = NORTH, "s" = SOUTH, "e" = EAST, "w" = WEST)
for(var/direction in step_overlays)
if(istype(get_step(src, step_overlays[direction]), /turf/space))
var/image/aster_edge = image('icons/turf/flooring/asteroid.dmi', "asteroid_edges", dir = step_overlays[direction])
aster_edge.turf_decal_layerise()
AddOverlays(aster_edge)
//todo cache
if(overlay_detail)
var/image/floor_decal = image(icon = 'icons/turf/flooring/decals.dmi', icon_state = overlay_detail)
floor_decal.turf_decal_layerise()
AddOverlays(floor_decal)
if(update_neighbors)
var/list/all_step_directions = list(NORTH,NORTHEAST,EAST,SOUTHEAST,SOUTH,SOUTHWEST,WEST,NORTHWEST)
for(var/direction in all_step_directions)
var/turf/simulated/floor/asteroid/A
if(istype(get_step(src, direction), /turf/simulated/floor/asteroid))
A = get_step(src, direction)
A.updateMineralOverlays()
/turf/simulated/floor/asteroid/Entered(atom/movable/M as mob|obj)
..()
if(istype(M,/mob/living/silicon/robot))
var/mob/living/silicon/robot/R = M
if(R.module)
if(istype(R.module_state_1,/obj/item/storage/ore))
attackby(R.module_state_1,R)
else if(istype(R.module_state_2,/obj/item/storage/ore))
attackby(R.module_state_2,R)
else if(istype(R.module_state_3,/obj/item/storage/ore))
attackby(R.module_state_3,R)
if (istype(R.module,/obj/item/robot_module/miner/adv))
var/obj/item/robot_rack/miner/C
if(istype(R.module_state_1,/obj/item/robot_rack/miner))
C = R.module_state_1
if (length(C.held))
var/obj/structure/ore_box/OB = locate(/obj/structure/ore_box) in C
for(var/obj/item/ore/ore in R.loc)
ore.Move(OB)
else if(istype(R.module_state_2,/obj/item/robot_rack/miner))
C = R.module_state_2
if (length(C.held))
var/obj/structure/ore_box/OB = locate(/obj/structure/ore_box) in C
for(var/obj/item/ore/ore in R.loc)
ore.Move(OB)
else if(istype(R.module_state_3,/obj/item/robot_rack/miner))
C = R.module_state_3
if (length(C.held))
var/obj/structure/ore_box/OB = locate(/obj/structure/ore_box) in C
for(var/obj/item/ore/ore in R.loc)
ore.Move(OB)
/turf/simulated/floor/asteroid/air
initial_gas = list("oxygen" = MOLES_O2STANDARD, "nitrogen" = MOLES_N2STANDARD)
// Contains extra CO2 for better breathing.
/turf/simulated/floor/asteroid/air/prison
initial_gas = list("oxygen" = 1.05 * MOLES_O2STANDARD, "nitrogen" = 1.05 * MOLES_N2STANDARD, "carbon_dioxide" = MOLES_CELLSTANDARD * 0.1)
temperature = 30 CELSIUS
/turf/simulated/floor/asteroid/swamp_dirt
name = "sand"
desc = "Gritty and unpleasant."
icon = 'icons/turf/flooring/swamp.dmi'
icon_state = "dirt"
base_name = "dirt"
base_desc = "Gritty and unpleasant."
base_icon = 'icons/turf/flooring/swamp.dmi'
base_icon_state = "dirt"
footstep_sound = SFX_FOOTSTEP_GRASS
temperature = 30 CELSIUS
initial_gas = list("oxygen" = 1.05 * MOLES_O2STANDARD, "nitrogen" = 1.05 * MOLES_N2STANDARD, "carbon_dioxide" = MOLES_CELLSTANDARD * 0.1)
/turf/simulated/floor/asteroid/swamp_dirt/Initialize()
. = ..()
if(prob(25))
set_light(0.25, 1, 2.5, 1.5, "#dbbfbf")
/turf/simulated/mineral/swamp
name = "rock"
icon = 'icons/turf/walls.dmi'
icon_state = "swamp_rock"
temperature = 0 CELSIUS
mined_turf = /turf/simulated/floor/asteroid/swamp_dirt
/turf/unsimulated/swamp_bedrock
name = "rock"
icon = 'icons/turf/walls.dmi'
icon_state = "swamp_rock"
/turf/simulated/floor/asteroid/swamp
name = "water"
desc = "Smells awfully."
icon = 'icons/turf/flooring/swamp.dmi'
temperature = 30 CELSIUS
icon_state = "swamp"
footstep_sound = SFX_FOOTSTEP_WATER
temperature = 30 CELSIUS
initial_gas = list("oxygen" = 1.05 * MOLES_O2STANDARD, "nitrogen" = 1.05 * MOLES_N2STANDARD, "carbon_dioxide" = MOLES_CELLSTANDARD * 0.1)
| 412 | 0.963135 | 1 | 0.963135 | game-dev | MEDIA | 0.994214 | game-dev | 0.978318 | 1 | 0.978318 |
ghostinthecamera/IGCS-GITC | 5,787 | Cameras/Deprecated/Ace Combat 7/InjectableGenericCameraSystem/Globals.h | ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Part of Injectable Generic Camera System
// Copyright(c) 2017, Frans Bouma
// All rights reserved.
// https://github.com/FransBouma/InjectableGenericCameraSystem
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and / or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include "Gamepad.h"
#include "GameConstants.h"
#include "Defaults.h"
#include "CDataFile.h"
extern "C" BYTE g_cameraEnabled;
extern "C" BYTE g_gamePaused;
extern "C" BYTE g_ultraWidefix;
namespace IGCS
{
struct Settings
{
bool invertY;
bool allowCameraMovementWhenMenuIsUp;
bool hudandtimestop;
bool ultrawidefix;
float fastMovementMultiplier;
float slowMovementMultiplier;
float movementUpMultiplier;
float movementSpeed;
float rotationSpeed;
float fovChangeSpeed;
float resolutionScale; //50.0-200.0
float fov;
int frameskip;
float slomoMult;
float clampFloat(float value, float min, float default)
{
return value < min ? default : value;
}
void loadFromFile()
{
CDataFile iniFile;
if (!iniFile.Load(IGCS_SETTINGS_INI_FILENAME))
{
// doesn't exist
return;
}
invertY = iniFile.GetBool("invertY", "CameraSettings");
hudandtimestop = iniFile.GetBool("hudandtimestop", "CameraSettings");
allowCameraMovementWhenMenuIsUp = iniFile.GetBool("allowCameraMovementWhenMenuIsUp", "CameraSettings");
fastMovementMultiplier = clampFloat(iniFile.GetFloat("fastMovementMultiplier", "CameraSettings"), 0.0f, FASTER_MULTIPLIER);
slowMovementMultiplier = clampFloat(iniFile.GetFloat("slowMovementMultiplier", "CameraSettings"), 0.0f, SLOWER_MULTIPLIER);
movementUpMultiplier = clampFloat(iniFile.GetFloat("movementUpMultiplier", "CameraSettings"), 0.0f, DEFAULT_UP_MOVEMENT_MULTIPLIER);
movementSpeed = clampFloat(iniFile.GetFloat("movementSpeed", "CameraSettings"), 0.0f, DEFAULT_MOVEMENT_SPEED);
rotationSpeed = clampFloat(iniFile.GetFloat("rotationSpeed", "CameraSettings"), 0.0f, DEFAULT_ROTATION_SPEED);
fovChangeSpeed = clampFloat(iniFile.GetFloat("fovChangeSpeed", "CameraSettings"), 0.0f, DEFAULT_FOV_SPEED);
}
void saveToFile()
{
CDataFile iniFile;
iniFile.SetBool("invertY", invertY, "", "CameraSettings");
iniFile.SetBool("allowCameraMovementWhenMenuIsUp", allowCameraMovementWhenMenuIsUp, "", "CameraSettings");
iniFile.SetBool("hudandtimestop", hudandtimestop, "", "CameraSettings");
iniFile.SetFloat("fastMovementMultiplier", fastMovementMultiplier, "", "CameraSettings");
iniFile.SetFloat("slowMovementMultiplier", slowMovementMultiplier, "", "CameraSettings");
iniFile.SetFloat("movementUpMultiplier", movementUpMultiplier, "", "CameraSettings");
iniFile.SetFloat("movementSpeed", movementSpeed, "", "CameraSettings");
iniFile.SetFloat("rotationSpeed", rotationSpeed, "", "CameraSettings");
iniFile.SetFloat("fovChangeSpeed", fovChangeSpeed, "", "CameraSettings");
iniFile.SetFileName(IGCS_SETTINGS_INI_FILENAME);
iniFile.Save();
}
void init()
{
invertY = CONTROLLER_Y_INVERT;
fastMovementMultiplier = FASTER_MULTIPLIER;
slowMovementMultiplier = SLOWER_MULTIPLIER;
movementUpMultiplier = DEFAULT_UP_MOVEMENT_MULTIPLIER;
movementSpeed = DEFAULT_MOVEMENT_SPEED;
rotationSpeed = DEFAULT_ROTATION_SPEED;
fovChangeSpeed = DEFAULT_FOV_SPEED;
resolutionScale = 100.0f;
frameskip = 15;
slomoMult = 0.05f;
allowCameraMovementWhenMenuIsUp = false;
hudandtimestop = false;
}
};
class Globals
{
public:
Globals();
~Globals();
static Globals& instance();
void saveSettingsIfRequired(float delta);
void markSettingsDirty();
bool inputBlocked() const { return _inputBlocked; }
void inputBlocked(bool value) { _inputBlocked = value; }
bool systemActive() const { return _systemActive; }
void systemActive(bool value) { _systemActive = value; }
HWND mainWindowHandle() const { return _mainWindowHandle; }
void mainWindowHandle(HWND handle) { _mainWindowHandle = handle; }
Gamepad& gamePad() { return _gamePad; }
Settings& settings() { return _settings; }
private:
bool _inputBlocked = false;
volatile bool _systemActive = false;
Gamepad _gamePad;
HWND _mainWindowHandle;
Settings _settings;
float _settingsDirtyTimer=0.0f; // when settings are marked dirty, this is set with a value > 0 and decremented each frame. If 0, settings are saved. In seconds.
};
} | 412 | 0.741298 | 1 | 0.741298 | game-dev | MEDIA | 0.830891 | game-dev | 0.594055 | 1 | 0.594055 |
djefrey/Colorwheel | 6,119 | common/src/main/java/dev/djefrey/colorwheel/engine/ClrwlDrawManager.java | package dev.djefrey.colorwheel.engine;
import com.mojang.datafixers.util.Pair;
import dev.djefrey.colorwheel.engine.embed.EnvironmentStorage;
import dev.engine_room.flywheel.api.backend.Engine;
import dev.engine_room.flywheel.api.backend.RenderContext;
import dev.engine_room.flywheel.api.instance.Instance;
import dev.engine_room.flywheel.api.instance.InstanceType;
import dev.engine_room.flywheel.api.model.Model;
import dev.engine_room.flywheel.api.task.Plan;
import dev.engine_room.flywheel.backend.FlwBackend;
import dev.engine_room.flywheel.backend.engine.GroupKey;
import dev.engine_room.flywheel.backend.engine.LightStorage;
import dev.engine_room.flywheel.backend.engine.embed.Environment;
import dev.engine_room.flywheel.lib.task.ForEachPlan;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import net.minecraft.client.resources.model.ModelBakery;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
public abstract class ClrwlDrawManager<N extends ClrwlAbstractInstancer<?>>
{
private static final boolean WARN_EMPTY_MODELS = Boolean.getBoolean("flywheel.warnEmptyModels");
/**
* A map of instancer keys to instancers.
* <br>
* This map is populated as instancers are requested and contains both initialized and uninitialized instancers.
*/
protected final Map<ClrwlInstancerKey<?>, N> instancers = new ConcurrentHashMap<>();
/**
* A list of instancers that have not yet been initialized.
* <br>
* All new instancers land here before having resources allocated in {@link #prepareFrame}.
*/
protected final Queue<UninitializedInstancer<N, ?>> initializationQueue = new ConcurrentLinkedQueue<>();
public <I extends Instance> ClrwlAbstractInstancer<I> getInstancer(ClrwlInstanceVisual visual, Environment environment, InstanceType<I> type, Model model, int bias)
{
return getInstancer(new ClrwlInstancerKey<>(visual, environment, type, model, bias));
}
@SuppressWarnings("unchecked")
public <I extends Instance> ClrwlAbstractInstancer<I> getInstancer(ClrwlInstancerKey<I> key)
{
return (ClrwlAbstractInstancer<I>) instancers.computeIfAbsent(key, this::createAndDeferInit);
}
public Plan<RenderContext> createFramePlan()
{
// Go wide on instancers to process deletions in parallel.
return ForEachPlan.of(() -> new ArrayList<>(instancers.values()), ClrwlAbstractInstancer::parallelUpdate);
}
public void prepareFrame(LightStorage lightStorage, EnvironmentStorage environmentStorage)
{
// Thread safety: flush is called from the render thread after all visual updates have been made,
// so there are no:tm: threads we could be racing with.
for (var init : initializationQueue) {
var instancer = init.instancer();
if (instancer.instanceCount() > 0) {
initialize(init.key(), instancer);
} else {
instancers.remove(init.key());
}
}
initializationQueue.clear();
}
public abstract void renderSolid();
public abstract void renderTranslucent();
public void onRenderOriginChanged()
{
instancers.values()
.forEach(ClrwlAbstractInstancer::clear);
}
public abstract void renderCrumbling(List<Engine.CrumblingBlock> crumblingBlocks);
protected abstract <I extends Instance> N create(ClrwlInstancerKey<I> type);
protected abstract <I extends Instance> void initialize(ClrwlInstancerKey<I> key, N instancer);
private N createAndDeferInit(ClrwlInstancerKey<?> key)
{
var out = create(key);
// Only queue the instancer for initialization if it has anything to render.
if (checkAndWarnEmptyModel(key.model())) {
// Thread safety: this method is called atomically from within computeIfAbsent,
// so you'd think we don't need extra synchronization to protect the queue, but
// somehow threads can race here and wind up never initializing an instancer.
initializationQueue.add(new UninitializedInstancer<>(key, out));
}
return out;
}
private static boolean checkAndWarnEmptyModel(Model model)
{
if (!model.meshes().isEmpty()) {
return true;
}
if (WARN_EMPTY_MODELS) {
StringBuilder builder = new StringBuilder();
builder.append("Creating an instancer for a model with no meshes! Stack trace:");
StackWalker.getInstance()
.forEach(f -> builder.append("\n\t")
.append(f.toString()));
FlwBackend.LOGGER.warn(builder.toString());
}
return false;
}
@FunctionalInterface
protected interface State2Instancer<I extends ClrwlAbstractInstancer<?>>
{
// I tried using a plain Function<State<?>, I> here, but it exploded with type errors.
@Nullable I apply(ClrwlInstanceHandle.State<?> state);
}
protected static <I extends ClrwlAbstractInstancer<?>> Map<GroupKey<?>, Int2ObjectMap<List<Pair<I, ClrwlInstanceHandle<?>>>>> doCrumblingSort(List<Engine.CrumblingBlock> crumblingBlocks, State2Instancer<I> cast)
{
Map<GroupKey<?>, Int2ObjectMap<List<Pair<I, ClrwlInstanceHandle<?>>>>> byType = new HashMap<>();
for (Engine.CrumblingBlock block : crumblingBlocks)
{
int progress = block.progress();
if (progress < 0 || progress >= ModelBakery.DESTROY_TYPES.size())
{
continue;
}
for (Instance instance : block.instances())
{
// Filter out instances that weren't created by this engine.
// If all is well, we probably shouldn't take the `continue`
// branches but better to do checked casts.
if (!(instance.handle() instanceof ClrwlInstanceHandle<?> impl))
{
continue;
}
var instancer = cast.apply(impl.state);
if (instancer == null)
{
continue;
}
byType.computeIfAbsent(new GroupKey<>(instancer.type, instancer.environment), $ -> new Int2ObjectArrayMap<>())
.computeIfAbsent(progress, $ -> new ArrayList<>())
.add(Pair.of(instancer, impl));
}
}
return byType;
}
public void delete()
{
instancers.clear();
initializationQueue.clear();
}
public abstract void triggerFallback();
protected record UninitializedInstancer<N, I extends Instance>(ClrwlInstancerKey<I> key, N instancer) {
}
}
| 412 | 0.898804 | 1 | 0.898804 | game-dev | MEDIA | 0.491214 | game-dev | 0.894986 | 1 | 0.894986 |
goldeneye-source/ges-code | 9,342 | game/server/ges/ent/ent_geexplosion.cpp | ///////////// Copyright � 2008 LodleNet. All rights reserved. /////////////
//
// Project : Server (GES)
// File : ent_geexplosion.cpp
// Description :
// [TODO: Write the purpose of ent_geexplosion.cpp.]
//
// Created On: 12/30/2008 5:04:07 PM
// Created By: Mark Chandler <mailto:admin@lodle.net>
// Edited By: Jonathan White (Killermonkey)
////////////////////////////////////////////////////////////////////////////
#include "cbase.h"
#include "ent_geexplosion.h"
#include "particle_system.h"
#include "engine/IEngineSound.h"
#include "soundent.h"
#include "steamjet.h"
#include "ge_gamerules.h"
#include "ge_shareddefs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define GE_EXP_SMALL_SIZE 80.0f // If you change this make sure you change gamerules.cpp line 466
#define GE_EXP_SPAWN_DELAY 0.25f
#define GE_EXP_DIE_DELAY 0.5f
#define GE_EXP_DMG_TIME 2.5f
extern short g_sModelIndexFireball; // (in combatweapon.cpp) holds the index for the fireball
extern short g_sModelIndexWExplosion; // (in combatweapon.cpp) holds the index for the underwater explosion
#define PAINTBALL_BOMB "PaintballBombSplats"
extern ConVar ge_paintball;
class CGE_Explosion : public CParticleSystem
{
public:
DECLARE_CLASS( CGE_Explosion, CParticleSystem );
DECLARE_DATADESC();
CGE_Explosion();
void Precache();
void Spawn();
void Activate();
void CreateInitialBlast();
void Think();
void SetDamage( float dmg );
void SetDamageRadius( float dmgR );
void SetOwner( CBaseEntity *owner );
void SetActivator( CBaseEntity *activator);
bool IsSmallExp() { return m_flDamageRadius <= GE_EXP_SMALL_SIZE; };
protected:
void CreateHeatWave( void );
void DestroyHeatWave( void );
private:
float m_flDamage;
float m_flDamageRadius;
float m_flDieTime;
float m_flShakeTime;
EHANDLE m_hOwner;
EHANDLE m_hActivator;
EHANDLE m_hHeatWave;
};
LINK_ENTITY_TO_CLASS( ge_explosion, CGE_Explosion );
BEGIN_DATADESC( CGE_Explosion )
DEFINE_THINKFUNC(Think),
END_DATADESC()
CGE_Explosion::CGE_Explosion()
{
m_flDamage = 320;
m_flDamageRadius = 260;
m_flShakeTime = 0;
m_flDieTime = 0;
}
void CGE_Explosion::SetDamage( float dmg )
{
m_flDamage = dmg;
}
void CGE_Explosion::SetDamageRadius( float dmgR )
{
m_flDamageRadius = dmgR;
}
void CGE_Explosion::SetActivator( CBaseEntity *activator)
{
m_hActivator.Set( activator );
}
void CGE_Explosion::SetOwner( CBaseEntity *owner)
{
m_hOwner.Set( owner );
}
void CGE_Explosion::Precache()
{
PrecacheScriptSound( "Explosion.small" );
PrecacheScriptSound( "Explosion.large" );
BaseClass::Precache();
}
void CGE_Explosion::Spawn()
{
m_takedamage = DAMAGE_NO;
KeyValue( "start_active", "1" );
if ( IsSmallExp() )
KeyValue( "effect_name", "GES_Explosion_B_Tiny" );
else
KeyValue( "effect_name", "GES_Explosion_B" );
BaseClass::Spawn();
}
void CGE_Explosion::Activate()
{
BaseClass::Activate();
if ( !IsSmallExp() )
{
m_flDieTime = gpGlobals->curtime + GE_EXP_DMG_TIME;
EmitSound("Explosion.large");
}
else
{
m_flDieTime = gpGlobals->curtime + GE_EXP_DMG_TIME;
EmitSound("Explosion.small");
}
m_flShakeTime = gpGlobals->curtime;
// Start off with a BANG ;-)
CreateInitialBlast();
SetThink( &CGE_Explosion::Think );
SetNextThink( gpGlobals->curtime );
}
// Create a HL2 Generic Blast to start off the fireworks. This does NO DAMAGE and doesn't display smoke.
void CGE_Explosion::CreateInitialBlast( void )
{
trace_t tr, tr2;
Vector vecAbsOrigin = GetAbsOrigin();
int contents = UTIL_PointContents ( vecAbsOrigin );
Vector dirs[5] = { Vector(0, 0, 48), Vector(0, 48, 0), Vector(0, -48, 0), Vector(48, 0, 0), Vector(-48, 0, 0) };
// Don't hit anything that isn't the world
// Start with a straight down trace, only colliding with the world. Slightly longer so that the floor is favored when explosions hit corners.
UTIL_TraceLine(vecAbsOrigin, vecAbsOrigin + Vector(0, 0, -64), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr);
// Run through each direction comparing each trace length to the current longest in order to find the shortest one.
// Then use that one for the rest of the code.
for (int i = 0; i < 5; i++)
{
UTIL_TraceLine(vecAbsOrigin, vecAbsOrigin + dirs[i], MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr2);
if (tr2.fraction < tr.fraction)
tr = tr2;
}
if ( tr.fraction != 1.0 )
{
Vector vecNormal = tr.plane.normal;
surfacedata_t *pdata = physprops->GetSurfaceData( tr.surface.surfaceProps );
CPASFilter filter( vecAbsOrigin );
te->Explosion( filter, -1.0, // don't apply cl_interp delay
&vecAbsOrigin,
!( contents & MASK_WATER ) ? g_sModelIndexFireball : g_sModelIndexWExplosion,
MIN(m_flDamageRadius, 500) * 0.03f,
25,
TE_EXPLFLAG_NOFIREBALLSMOKE | TE_EXPLFLAG_NOSOUND,
MIN(m_flDamageRadius, 500) * 0.8f,
0.0f,
&vecNormal,
(char) pdata->game.material );
}
else
{
CPASFilter filter( vecAbsOrigin );
te->Explosion( filter, -1.0, // don't apply cl_interp delay
&vecAbsOrigin,
!( contents & MASK_WATER ) ? g_sModelIndexFireball : g_sModelIndexWExplosion,
MIN(m_flDamageRadius, 500) * 0.03f,
25,
TE_EXPLFLAG_NOFIREBALLSMOKE | TE_EXPLFLAG_NOSOUND,
MIN(m_flDamageRadius, 500) * 0.8f,
0.0f );
}
CSoundEnt::InsertSound( SOUND_DANGER, GetAbsOrigin(), MIN(m_flDamageRadius, 500)*1.5f, GE_EXP_DMG_TIME, this );
//Wreak paintball havok if paintball mode is on
//otherwise just place a scorch mark down
if( ge_paintball.GetBool() )
{
//Paint the big splat where the bomb went off
UTIL_DecalTrace( &tr, PAINTBALL_BOMB );
//Create a bunch of impacts around
int splatCount = random->RandomInt( 3, 5 );
for( int i = 0; i < splatCount; i++ )
{
Vector vecStart, vecStop, vecDir;
// Snap our facing to where we are heading
QAngle randAngle;
randAngle.Random( 0, 360 );
// get the vectors
vecStart = GetAbsOrigin();
vecStop = vecStart + vecDir * 150;
AngleVectors( randAngle, &vecDir );
UTIL_TraceLine( vecStart, vecStop, MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr );
// check to see if we hit something
if ( tr.m_pEnt )
if ( tr.m_pEnt->IsWorld() || tr.m_pEnt->IsPlayer() )
{
//Paint the big splat where the bomb went off
UTIL_DecalTrace( &tr, PAINTBALL_BOMB );
}
}
}
else
UTIL_DecalTrace( &tr, "Scorch" );
// Generate the heat effects
CreateHeatWave();
}
void CGE_Explosion::Think()
{
if ( gpGlobals->curtime > m_flDieTime + GE_EXP_DIE_DELAY )
{
StopParticleSystem();
UTIL_Remove(this);
}
else if ( gpGlobals->curtime < m_flDieTime )
{
// Only apply damage if our owner and activator are still valid
if ( m_hActivator.Get() && m_hOwner.Get() && m_flDamageRadius > 0 && m_flDamage > 0 )
{
CTakeDamageInfo info( m_hActivator.Get(), m_hOwner.Get(), vec3_origin, GetAbsOrigin(), m_flDamage, DMG_BLAST );
g_pGameRules->RadiusDamage( info, GetAbsOrigin(), m_flDamageRadius, CLASS_NONE, NULL );
}
if ( gpGlobals->curtime > m_flShakeTime && gpGlobals->curtime < m_flDieTime + 1.0f )
{
float radius = (m_flDamageRadius > 0) ? ( MIN(m_flDamageRadius, 300) * (IsSmallExp() ? 0.75f : 1.0f)) : 45.0f;
float freq = IsSmallExp() ? 50.0f : 100.0f;
float amp = IsSmallExp() ? 3.0 : 7.0;
m_flShakeTime = gpGlobals->curtime + 1.0f;
UTIL_ScreenShake( GetAbsOrigin(), amp, freq, 1.0f, radius, SHAKE_START );
}
// Apply another round of damage in 1/3 of a second
SetNextThink( gpGlobals->curtime + 0.1f );
}
else
{
DestroyHeatWave();
SetNextThink( gpGlobals->curtime + 0.1f );
}
}
void CGE_Explosion::CreateHeatWave( void )
{
return; // We can't afford to have this effect anymore, we're pushing things as it is.
static Vector offset( -40.0f, 0, 70.0f );
float scale = 1.0f;
if ( m_flDamageRadius <= GE_EXP_SMALL_SIZE )
scale = 0.4f;
CSteamJet *pHeatWave = (CSteamJet*)CBaseEntity::CreateNoSpawn( "env_steam", GetAbsOrigin() + offset, vec3_angle, this );
pHeatWave->m_nType = STEAM_HEATWAVE;
pHeatWave->m_SpreadSpeed = 20.0f;
pHeatWave->m_Speed = 120.0f;
pHeatWave->m_StartSize = 30.0f * scale;
pHeatWave->m_EndSize = 45.0f * scale;
pHeatWave->m_Rate = 26.0f;
pHeatWave->m_JetLength = 80.0f * scale;
pHeatWave->m_InitialState = true;
pHeatWave->m_bIsForExplosion = true;
pHeatWave->m_flStartFadeTime = gpGlobals->curtime + GE_EXP_DMG_TIME - 0.5f;
pHeatWave->m_flFadeDuration = 0.5f;
DispatchSpawn( pHeatWave );
m_hHeatWave = pHeatWave;
}
void CGE_Explosion::DestroyHeatWave( void )
{
return; // Can't destroy what we don't have.
if ( m_hHeatWave.Get() )
{
m_hHeatWave->Remove();
m_hHeatWave = NULL;
}
}
CBaseEntity* Create_GEExplosion( CBaseEntity* owner, CBaseEntity* activator, const Vector pos, float dmg, float dmgRadius )
{
// We must have an owner
if ( !owner )
return NULL;
CGE_Explosion *pExp = (CGE_Explosion*)CreateEntityByName( "ge_explosion" );
if ( pExp )
{
pExp->SetOwner( owner );
pExp->SetActivator( activator == NULL ? owner : activator );
pExp->SetDamage( dmg );
pExp->SetDamageRadius( dmgRadius );
pExp->SetAbsOrigin( pos );
DispatchSpawn( pExp );
pExp->Activate();
}
return pExp;
}
CBaseEntity* Create_GEExplosion( CBaseEntity* owner, const Vector pos, float dmg, float dmgRadius )
{
return Create_GEExplosion( owner, NULL, pos, dmg, dmgRadius );
}
| 412 | 0.947063 | 1 | 0.947063 | game-dev | MEDIA | 0.985363 | game-dev | 0.865851 | 1 | 0.865851 |
JACoders/OpenJK | 48,148 | codeJK2/cgame/FxPrimitives.cpp | /*
===========================================================================
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK 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, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#if !defined(FX_SCHEDULER_H_INC)
#include "FxScheduler.h"
#endif
#include "cg_media.h"
extern int drawnFx;
extern int mParticles;
extern int mOParticles;
extern int mLines;
extern int mTails;
// Helper function
//-------------------------
void ClampVec( vec3_t dat, byte *res )
{
int r;
// clamp all vec values, then multiply the normalized values by 255 to maximize the result
for ( int i = 0; i < 3; i++ )
{
r = Q_ftol(dat[i] * 255.0f);
if ( r < 0 )
{
r = 0;
}
else if ( r > 255 )
{
r = 255;
}
res[i] = (unsigned char)r;
}
}
void GetOrigin( int clientID, vec3_t org )
{
if ( clientID >=0 )
{
centity_t *cent = &cg_entities[clientID];
if ( cent && cent->gent && cent->gent->client )
{
VectorCopy( cent->gent->client->renderInfo.muzzlePoint, org );
}
}
}
void GetDir( int clientID, vec3_t org )
{
if ( clientID >=0 )
{
centity_t *cent = &cg_entities[clientID];
if ( cent && cent->gent && cent->gent->client )
{
VectorCopy( cent->gent->client->renderInfo.muzzleDir, org );
}
}
}
//--------------------------
//
// Base Effect Class
//
//--------------------------
//--------------------------
//
// Derived Particle Class
//
//--------------------------
void CParticle::Die()
{
if ( mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT) )
{
vec3_t norm;
// Man, this just seems so, like, uncool and stuff...
VectorSet( norm, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f));
VectorNormalize( norm );
theFxScheduler.PlayEffect( mDeathFxID, mOrigin1, norm );
}
}
//----------------------------
bool CParticle::Cull()
{
vec3_t dir;
// Get the direction to the view
VectorSubtract( mOrigin1, cg.refdef.vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 )
{
return true;
}
float len = VectorLengthSquared( dir );
// Can't be too close
if ( len < 16 * 16 )
{
return true;
}
return false;
}
//----------------------------
void CParticle::Draw()
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
// Add our refEntity to the scene
VectorCopy( mOrigin1, mRefEnt.origin );
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
mParticles++;
}
//----------------------------
// Update
//----------------------------
bool CParticle::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD )
{
// we are somehow not bolted even though the flag is on?
return false;
}
vec3_t dir, org = { 0.0f };
vec3_t realVel, realAccel;
float time = (theFxHelper.mTime - mTimeStart) * 0.001f;
// Get our current position and direction
GetOrigin( mClientID, org );
GetDir( mClientID, dir );
vec3_t ang, ax[3];
vectoangles( dir, ang );
AngleVectors( ang, ax[0], ax[1], ax[2] );
// VectorCopy( dir, ax[0] );
// CrossProduct( up, ax[0], ax[1] );
// VectorNormalize( ax[1] );
// CrossProduct( ax[0], ax[1], ax[2] );
VectorMA( org, mOrgOffset[0], ax[0], org );
VectorMA( org, mOrgOffset[1], ax[1], org );
VectorMA( org, mOrgOffset[2], ax[2], org );
// calc the real velocity and accel vectors
VectorScale( ax[0], mVel[0], realVel );
VectorMA( realVel, mVel[1], ax[1], realVel );
VectorMA( realVel, mVel[2], ax[2], realVel );
realVel[2] += 0.5f * mGravity * time;
VectorScale( ax[0], mAccel[0], realAccel );
VectorMA( realAccel, mAccel[1], ax[1], realAccel );
VectorMA( realAccel, mAccel[2], ax[2], realAccel );
// Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise
VectorMA( realVel, time, realAccel, realVel );
// Now move us to where we should be at the given time
VectorMA( org, time, realVel, mOrigin1 );
}
else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull())
{
UpdateSize();
UpdateRGB();
UpdateAlpha();
UpdateRotation();
Draw();
}
return true;
}
//----------------------------
// Update Origin
//----------------------------
bool CParticle::UpdateOrigin()
{
vec3_t new_origin;
// float ftime, time2;
UpdateVelocity();
// Calc the time differences
// ftime = theFxHelper.mFrameTime * 0.001f;
//time2 = ftime * ftime * 0.5f;
// time2=0;
// Predict the new position
new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0];// + time2 * mVel[0];
new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1];// + time2 * mVel[1];
new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2];// + time2 * mVel[2];
// Only perform physics if this object is tagged to do so
if ( (mFlags & FX_APPLY_PHYSICS) )
{
bool solid;
if ( mFlags & FX_EXPENSIVE_PHYSICS )
{
solid = true; // by setting this to true, we force a real trace to happen
}
else
{
// if this returns solid, we need to do a trace
solid = !!(CG_PointContents( new_origin, ENTITYNUM_WORLD ) & ( MASK_SHOT | CONTENTS_WATER ));
}
if ( solid )
{
trace_t trace;
float dot;
if ( mFlags & FX_USE_BBOX )
{
theFxHelper.Trace( &trace, mOrigin1, mMin, mMax, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) );
}
else
{
theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) );
}
if ( trace.startsolid || trace.allsolid || trace.fraction == 1.0)
{
}
else
{
// Hit something
if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT ))
{
theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal );
}
if ( mFlags & FX_KILL_ON_IMPACT )
{
// time to die
return false;
}
VectorMA( mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel );
dot = DotProduct( mVel, trace.plane.normal );
VectorMA( mVel, -2 * dot, trace.plane.normal, mVel );
VectorScale( mVel, mElasticity, mVel );
// If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid
// doing expensive operations when they aren't needed
if ( trace.plane.normal[2] > 0 && mVel[2] < 4 )
{
VectorClear( mVel );
VectorClear( mAccel );
mFlags &= ~(FX_APPLY_PHYSICS|FX_IMPACT_RUNS_FX);
}
// Set the origin to the exact impact point
VectorCopy( trace.endpos, mOrigin1 );
return true;
}
}
}
// No physics were done to this object, move it
VectorCopy( new_origin, mOrigin1 );
return true;
}
//----------------------------
// Update Size
//----------------------------
void CParticle::UpdateSize()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( (mFlags & FX_SIZE_LINEAR) )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart)
/ (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR )
{
if ( theFxHelper.mTime > mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm)
/ (float)(mTimeEnd - mSizeParm);
}
if ( mFlags & FX_SIZE_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm );
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP )
{
if ( theFxHelper.mTime < mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSizeParm - theFxHelper.mTime)
/ (float)(mSizeParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( (mFlags & FX_SIZE_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if (( mFlags & FX_SIZE_RAND ))
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
mRefEnt.radius = (mSizeStart * perc1) + (mSizeEnd * (1.0f - perc1));
}
//----------------------------
// Update RGB
//----------------------------
void CParticle::UpdateRGB()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
vec3_t res;
if ( (mFlags & FX_RGB_LINEAR) )
{
// calculate element biasing
perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart )
/ (float)( mTimeEnd - mTimeStart );
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR )
{
if ( theFxHelper.mTime > mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm )
/ (float)( mTimeEnd - mRGBParm );
}
if ( (mFlags & FX_RGB_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm );
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP )
{
if ( theFxHelper.mTime < mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mRGBParm - theFxHelper.mTime)
/ (float)(mRGBParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if (( mFlags & FX_RGB_LINEAR ))
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if (( mFlags & FX_RGB_RAND ))
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
// Now get the correct color
VectorScale( mRGBStart, perc1, res );
VectorMA( res, (1.0f - perc1), mRGBEnd, mRefEnt.angles ); // angles is a temp storage, will get clamped to a byte in the UpdateAlpha section
}
//----------------------------
// Update Alpha
//----------------------------
void CParticle::UpdateAlpha()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_ALPHA_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart)
/ (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP
if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_NONLINEAR )
{
if ( theFxHelper.mTime > mAlphaParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm)
/ (float)(mTimeEnd - mAlphaParm);
}
if ( mFlags & FX_ALPHA_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mAlphaParm );
}
else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_CLAMP )
{
if ( theFxHelper.mTime < mAlphaParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mAlphaParm - theFxHelper.mTime)
/ (float)(mAlphaParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_ALPHA_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
perc1 = (mAlphaStart * perc1) + (mAlphaEnd * (1.0f - perc1));
// We should be in the right range, but clamp to ensure
if ( perc1 < 0.0f )
{
perc1 = 0.0f;
}
else if ( perc1 > 1.0f )
{
perc1 = 1.0f;
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( (mFlags & FX_ALPHA_RAND) )
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
if ( mFlags & FX_USE_ALPHA )
{
// should use this when using art that has an alpha channel
ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) );
mRefEnt.shaderRGBA[3] = (byte)(perc1 * 0xff);
}
else
{
// Modulate the rgb fields by the alpha value to do the fade, works fine for additive blending
VectorScale( mRefEnt.angles, perc1, mRefEnt.angles );
ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) );
}
}
//--------------------------------
//
// Derived Oriented Particle Class
//
//--------------------------------
//----------------------------
bool COrientedParticle::Cull()
{
vec3_t dir;
// Get the direction to the view
VectorSubtract( mOrigin1, cg.refdef.vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 )
{
return true;
}
float len = VectorLengthSquared( dir );
// Can't be too close
if ( len < 24 * 24 )
{
return true;
}
return false;
}
//----------------------------
void COrientedParticle::Draw()
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set
mRefEnt.renderfx |= RF_DEPTHHACK;
}
// Add our refEntity to the scene
VectorCopy( mOrigin1, mRefEnt.origin );
VectorCopy( mNormal, mRefEnt.axis[0] );
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
mOParticles++;
}
//----------------------------
// Update
//----------------------------
bool COrientedParticle::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull())
{
UpdateSize();
UpdateRGB();
UpdateAlpha();
UpdateRotation();
Draw();
}
return true;
}
//----------------------------
//
// Derived Line Class
//
//----------------------------
bool CLine::Cull( void )
{
vec3_t dir;
VectorSubtract( mOrigin1, cg.refdef.vieworg, dir );
//Check if it's in front of the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) >= 0 )
{
return false; //don't cull
}
VectorSubtract( mOrigin2, cg.refdef.vieworg, dir );
//Check if it's in front of the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) >= 0 )
{
return false;
}
return true; //all points behind viewer
}
//----------------------------
void CLine::Draw()
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
VectorCopy( mOrigin2, mRefEnt.oldorigin );
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
mLines++;
}
//----------------------------
bool CLine::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( mFlags & FX_RELATIVE )
{
if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD )
{
// we are somehow not bolted even though the flag is on?
return false;
}
vec3_t dir = { 0.0f }, end;
trace_t trace;
// Get our current position and direction
GetOrigin( mClientID, mOrigin1 );
GetDir( mClientID, dir );
if ( mFlags & FX_APPLY_PHYSICS )
{
VectorMA( mOrigin1, 2048, dir, end );
theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, end, mClientID, MASK_SHOT );
VectorCopy( trace.endpos, mOrigin2 );
if ( mImpactFxID > 0 )
{
theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal );
}
}
else
{
VectorMA( mOrigin1, mOrgOffset[0], dir, mOrigin2 );
}
}
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
return true;
}
//----------------------------
//
// Derived Electricity Class
//
//----------------------------
void CElectricity::Initialize()
{
mRefEnt.frame = Q_flrand(0.0f, 1.0f) * 1265536;
mRefEnt.endTime = cg.time + (mTimeEnd - mTimeStart);
if ( mFlags & FX_DEPTH_HACK )
{
mRefEnt.renderfx |= RF_DEPTHHACK;
}
if ( mFlags & FX_BRANCH )
{
mRefEnt.renderfx |= RF_FORKED;
}
if ( mFlags & FX_TAPER )
{
mRefEnt.renderfx |= RF_TAPERED;
}
if ( mFlags & FX_GROW )
{
mRefEnt.renderfx |= RF_GROW;
}
}
//----------------------------
void CElectricity::Draw()
{
VectorCopy( mOrigin1, mRefEnt.origin );
VectorCopy( mOrigin2, mRefEnt.oldorigin );
mRefEnt.angles[0] = mChaos;
mRefEnt.angles[1] = mTimeEnd - mTimeStart;
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
mLines++; // NOT REALLY A LINE!
}
//----------------------------
bool CElectricity::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
return true;
}
//----------------------------
//
// Derived Tail Class
//
//----------------------------
bool CTail::Cull()
{
vec3_t dir;
// Get the direction to the view
VectorSubtract( mOrigin1, cg.refdef.vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 )
{
return true;
}
return false;
}
//----------------------------
void CTail::Draw()
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
mTails++;
}
//----------------------------
bool CTail::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
if ( !fx_freeze.integer )
{
VectorCopy( mOrigin1, mOldOrigin );
}
if ( mFlags & FX_RELATIVE )
{
if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD )
{
// the thing we are bolted to is no longer valid, so we may as well just die.
return false;
}
vec3_t dir, org = { 0.0f };
// vec3_t right, up;
vec3_t realVel, realAccel;
// Get our current position and direction
GetOrigin( mClientID, org );
GetDir( mClientID, dir );
vec3_t ang, ax[3];
vectoangles( dir, ang );
AngleVectors( ang, ax[0], ax[1], ax[2] );
VectorMA( org, mOrgOffset[0], ax[0], org );
VectorMA( org, mOrgOffset[1], ax[1], org );
VectorMA( org, mOrgOffset[2], ax[2], org );
// calc the real velocity and accel vectors
// FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra work
VectorScale( ax[0], mVel[0], realVel );
VectorMA( realVel, mVel[1], ax[1], realVel );
VectorMA( realVel, mVel[2], ax[2], realVel );
VectorScale( ax[0], mAccel[0], realAccel );
VectorMA( realAccel, mAccel[1], ax[1], realAccel );
VectorMA( realAccel, mAccel[2], ax[2], realAccel );
// Get our real velocity at the current time, taking into account the effects of acceleration. NOTE: not sure if this is even 100% correct math-wise
VectorMA( realVel, (theFxHelper.mTime - mTimeStart) * 0.001f, realAccel, realVel );
// Now move us to where we should be at the given time
VectorMA( org, (theFxHelper.mTime - mTimeStart) * 0.001f, realVel, mOrigin1 );
// Just calc an old point some time in the past, doesn't really matter when
VectorMA( org, ((theFxHelper.mTime - mTimeStart) - 3) * 0.001f, realVel, mOldOrigin );
}
else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
if ( !Cull() )
{
UpdateSize();
UpdateLength();
UpdateRGB();
UpdateAlpha();
CalcNewEndpoint();
Draw();
}
return true;
}
//----------------------------
void CTail::UpdateLength()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_LENGTH_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart)
/ (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_NONLINEAR )
{
if ( theFxHelper.mTime > mLengthParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm)
/ (float)(mTimeEnd - mLengthParm);
}
if ( mFlags & FX_LENGTH_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mLengthParm );
}
else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_CLAMP )
{
if ( theFxHelper.mTime < mLengthParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mLengthParm - theFxHelper.mTime)
/ (float)(mLengthParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_LENGTH_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_LENGTH_RAND )
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
mLength = (mLengthStart * perc1) + (mLengthEnd * (1.0f - perc1));
}
//----------------------------
void CTail::CalcNewEndpoint()
{
vec3_t temp;
// FIXME: Hmmm, this looks dumb when physics are on and a bounce happens
VectorSubtract( mOldOrigin, mOrigin1, temp );
// I wish we didn't have to do a VectorNormalize every frame.....
VectorNormalize( temp );
VectorMA( mOrigin1, mLength, temp, mRefEnt.oldorigin );
}
//----------------------------
//
// Derived Cylinder Class
//
//----------------------------
void CCylinder::Draw()
{
if ( mFlags & FX_DEPTH_HACK )
{
// Not sure if first person needs to be set, but it can't hurt?
mRefEnt.renderfx |= RF_DEPTHHACK;
}
VectorCopy( mOrigin1, mRefEnt.origin );
VectorMA( mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin );
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
}
//----------------------------
// Update Size2
//----------------------------
void CCylinder::UpdateSize2()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_SIZE2_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart)
/ (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_NONLINEAR )
{
if ( theFxHelper.mTime > mSize2Parm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm)
/ (float)(mTimeEnd - mSize2Parm);
}
if ( (mFlags & FX_SIZE2_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSize2Parm );
}
else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_CLAMP )
{
if ( theFxHelper.mTime < mSize2Parm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSize2Parm - theFxHelper.mTime)
/ (float)(mSize2Parm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_SIZE2_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_SIZE2_RAND )
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
mRefEnt.backlerp = (mSize2Start * perc1) + (mSize2End * (1.0f - perc1));
}
//----------------------------
bool CCylinder::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
UpdateSize();
UpdateSize2();
UpdateLength();
UpdateRGB();
UpdateAlpha();
Draw();
return true;
}
//----------------------------
//
// Derived Emitter Class
//
//----------------------------
//----------------------------
// Draw
//----------------------------
void CEmitter::Draw()
{
// Emitters don't draw themselves, but they may need to add an attached model
if ( mFlags & FX_ATTACHED_MODEL )
{
mRefEnt.nonNormalizedAxes = qtrue;
VectorCopy( mOrigin1, mRefEnt.origin );
// ensure that we are sized
for ( int i = 0; i < 3; i++ )
{
VectorScale( mRefEnt.axis[i], mRefEnt.radius, mRefEnt.axis[i] );
}
theFxHelper.AddFxToScene( &mRefEnt );
}
// If we are emitting effects, we had better be careful because just calling it every cgame frame could
// either choke up the effects system on a fast machine, or look really nasty on a low end one.
if ( mFlags & FX_EMIT_FX )
{
vec3_t org, v;
float ftime, time2,
step;
int i, t, dif;
#define TRAIL_RATE 8 // we "think" at about a 60hz rate
// Pick a target step distance and square it
step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance;
step *= step;
dif = 0;
for ( t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE )
{
dif += TRAIL_RATE;
// ?Not sure if it's better to update this before or after updating the origin
VectorMA( mOldVelocity, dif * 0.001f, mAccel, v );
// Calc the time differences
ftime = dif * 0.001f;
time2 = ftime * ftime * 0.5f;
// Predict the new position
for ( i = 0 ; i < 3 ; i++ )
{
org[i] = mOldOrigin[i] + ftime * v[i] + time2 * v[i];
}
// Only perform physics if this object is tagged to do so
if ( (mFlags & FX_APPLY_PHYSICS) )
{
bool solid;
if ( mFlags & FX_EXPENSIVE_PHYSICS )
{
solid = true; // by setting this to true, we force a real trace to happen
}
else
{
// if this returns solid, we need to do a trace
solid = !!(CG_PointContents( org, ENTITYNUM_WORLD ) & MASK_SHOT);
}
if ( solid )
{
trace_t trace;
if ( mFlags & FX_USE_BBOX )
{
theFxHelper.Trace( &trace, mOldOrigin, mMin, mMax, org, -1, MASK_SHOT );
}
else
{
theFxHelper.Trace( &trace, mOldOrigin, NULL, NULL, org, -1, MASK_SHOT );
}
// Hit something
if ( trace.fraction < 1.0f || trace.startsolid || trace.allsolid )
{
return;
}
}
}
// Is it time to draw an effect?
if ( DistanceSquared( org, mOldOrigin ) >= step )
{
// Pick a new target step distance and square it
step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance;
step *= step;
// We met the step criteria so, we should add in the effect
theFxScheduler.PlayEffect( mEmitterFxID, org, mRefEnt.axis );
VectorCopy( org, mOldOrigin );
VectorCopy( v, mOldVelocity );
dif = 0;
mOldTime = t;
}
}
}
drawnFx++;
}
//----------------------------
bool CEmitter::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
// Use this to track if we've stopped moving
VectorCopy( mOrigin1, mOldOrigin );
VectorCopy( mVel, mOldVelocity );
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
// If the thing is no longer moving, kill the angle delta, but don't do it too quickly or it will
// look very artificial. Don't do it too slowly or it will look like there is no friction.
if ( VectorCompare( mOldOrigin, mOrigin1 ))
{
VectorScale( mAngleDelta, 0.7f, mAngleDelta );
}
UpdateAngles();
UpdateSize();
// UpdateRGB(); // had wanted to do something slick whereby an emitted effect could somehow inherit these
// UpdateAlpha(); // values, but it's not a priority right now.
Draw();
return true;
}
//----------------------------
void CEmitter::UpdateAngles()
{
VectorMA( mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, mAngles ); // was 0.001f, but then you really have to jack up the delta to even notice anything
AnglesToAxis( mAngles, mRefEnt.axis );
}
//--------------------------
//
// Derived Light Class
//
//--------------------------
//----------------------------
// Update
//----------------------------
bool CLight::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
UpdateSize();
UpdateRGB();
Draw();
return true;
}
//----------------------------
// Update Size
//----------------------------
void CLight::UpdateSize()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
if ( mFlags & FX_SIZE_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart)
/ (float)(mTimeEnd - mTimeStart);
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR )
{
if ( theFxHelper.mTime > mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm)
/ (float)(mTimeEnd - mSizeParm);
}
if ( (mFlags & FX_SIZE_LINEAR) )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm );
}
else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP )
{
if ( theFxHelper.mTime < mSizeParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mSizeParm - theFxHelper.mTime)
/ (float)(mSizeParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_SIZE_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_SIZE_RAND )
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
mRefEnt.radius = (mSizeStart * perc1) + (mSizeEnd * (1.0f - perc1));
}
//----------------------------
// Update RGB
//----------------------------
void CLight::UpdateRGB()
{
// completely biased towards start if it doesn't get overridden
float perc1 = 1.0f, perc2 = 1.0f;
vec3_t res;
if ( mFlags & FX_RGB_LINEAR )
{
// calculate element biasing
perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart )
/ (float)( mTimeEnd - mTimeStart );
}
// We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE
if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR )
{
if ( theFxHelper.mTime > mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm )
/ (float)( mTimeEnd - mRGBParm );
}
if ( mFlags & FX_RGB_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE )
{
// wave gen, with parm being the frequency multiplier
perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm );
}
else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP )
{
if ( theFxHelper.mTime < mRGBParm )
{
// get percent done, using parm as the start of the non-linear fade
perc2 = (float)(mRGBParm - theFxHelper.mTime)
/ (float)(mRGBParm - mTimeStart);
}
else
{
perc2 = 0.0f; // make it full size??
}
if ( mFlags & FX_RGB_LINEAR )
{
// do an even blend
perc1 = perc1 * 0.5f + perc2 * 0.5f;
}
else
{
// just copy it over...sigh
perc1 = perc2;
}
}
// If needed, RAND can coexist with linear and either non-linear or wave.
if ( mFlags & FX_RGB_RAND )
{
// Random simply modulates the existing value
perc1 = Q_flrand(0.0f, 1.0f) * perc1;
}
// Now get the correct color
VectorScale( mRGBStart, perc1, res );
mRefEnt.lightingOrigin[0] = res[0] + ( 1.0f - perc1 ) * mRGBEnd[0];
mRefEnt.lightingOrigin[1] = res[1] + ( 1.0f - perc1 ) * mRGBEnd[1];
mRefEnt.lightingOrigin[2] = res[2] + ( 1.0f - perc1 ) * mRGBEnd[2];
}
//--------------------------
//
// Derived Trail Class
//
//--------------------------
#define NEW_MUZZLE 0
#define NEW_TIP 1
#define OLD_TIP 2
#define OLD_MUZZLE 3
//----------------------------
void CTrail::Draw()
{
polyVert_t verts[3];
// vec3_t color;
// build the first tri out of the new muzzle...new tip...old muzzle
VectorCopy( mVerts[NEW_MUZZLE].origin, verts[0].xyz );
VectorCopy( mVerts[NEW_TIP].origin, verts[1].xyz );
VectorCopy( mVerts[OLD_MUZZLE].origin, verts[2].xyz );
// VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color );
verts[0].modulate[0] = mVerts[NEW_MUZZLE].rgb[0];
verts[0].modulate[1] = mVerts[NEW_MUZZLE].rgb[1];
verts[0].modulate[2] = mVerts[NEW_MUZZLE].rgb[2];
verts[0].modulate[3] = mVerts[NEW_MUZZLE].alpha;
// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color );
verts[1].modulate[0] = mVerts[NEW_TIP].rgb[0];
verts[1].modulate[1] = mVerts[NEW_TIP].rgb[1];
verts[1].modulate[2] = mVerts[NEW_TIP].rgb[2];
verts[1].modulate[3] = mVerts[NEW_TIP].alpha;
// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color );
verts[2].modulate[0] = mVerts[OLD_MUZZLE].rgb[0];
verts[2].modulate[1] = mVerts[OLD_MUZZLE].rgb[1];
verts[2].modulate[2] = mVerts[OLD_MUZZLE].rgb[2];
verts[2].modulate[3] = mVerts[OLD_MUZZLE].alpha;
verts[0].st[0] = mVerts[NEW_MUZZLE].curST[0];
verts[0].st[1] = mVerts[NEW_MUZZLE].curST[1];
verts[1].st[0] = mVerts[NEW_TIP].curST[0];
verts[1].st[1] = mVerts[NEW_TIP].curST[1];
verts[2].st[0] = mVerts[OLD_MUZZLE].curST[0];
verts[2].st[1] = mVerts[OLD_MUZZLE].curST[1];
// Add this tri
theFxHelper.AddPolyToScene( mShader, 3, verts );
// build the second tri out of the old muzzle...old tip...new tip
VectorCopy( mVerts[OLD_MUZZLE].origin, verts[0].xyz );
VectorCopy( mVerts[OLD_TIP].origin, verts[1].xyz );
VectorCopy( mVerts[NEW_TIP].origin, verts[2].xyz );
// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color );
verts[0].modulate[0] = mVerts[OLD_MUZZLE].rgb[0];
verts[0].modulate[1] = mVerts[OLD_MUZZLE].rgb[1];
verts[0].modulate[2] = mVerts[OLD_MUZZLE].rgb[2];
verts[0].modulate[3] = mVerts[OLD_MUZZLE].alpha;
// VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color );
verts[1].modulate[0] = mVerts[OLD_TIP].rgb[0];
verts[1].modulate[1] = mVerts[OLD_TIP].rgb[1];
verts[1].modulate[2] = mVerts[OLD_TIP].rgb[2];
verts[0].modulate[3] = mVerts[OLD_TIP].alpha;
// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color );
verts[2].modulate[0] = mVerts[NEW_TIP].rgb[0];
verts[2].modulate[1] = mVerts[NEW_TIP].rgb[1];
verts[2].modulate[2] = mVerts[NEW_TIP].rgb[2];
verts[0].modulate[3] = mVerts[NEW_TIP].alpha;
verts[0].st[0] = mVerts[OLD_MUZZLE].curST[0];
verts[0].st[1] = mVerts[OLD_MUZZLE].curST[1];
verts[1].st[0] = mVerts[OLD_TIP].curST[0];
verts[1].st[1] = mVerts[OLD_TIP].curST[1];
verts[2].st[0] = mVerts[NEW_TIP].curST[0];
verts[2].st[1] = mVerts[NEW_TIP].curST[1];
// Add this tri
theFxHelper.AddPolyToScene( mShader, 3, verts );
drawnFx++;
}
//----------------------------
// Update
//----------------------------
bool CTrail::Update()
{
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
float perc = (float)(mTimeEnd - theFxHelper.mTime) / (float)(mTimeEnd - mTimeStart);
for ( int t = 0; t < 4; t++ )
{
// mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc );
// if ( mVerts[t].curAlpha < 0.0f )
// {
// mVerts[t].curAlpha = 0.0f;
// }
// VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB );
// VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB );
mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * ( 1.0f - perc );
if ( mVerts[t].curST[0] > 1.0f )
{
mVerts[t].curST[0] = 1.0f;
}
mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * ( 1.0f - perc );
}
Draw();
return true;
}
//--------------------------
//
// Derived Poly Class
//
//--------------------------
bool CPoly::Cull()
{
vec3_t dir;
// Get the direction to the view
VectorSubtract( mOrigin1, cg.refdef.vieworg, dir );
// Check if it's behind the viewer
if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 )
{
return true;
}
float len = VectorLengthSquared( dir );
// Can't be too close
if ( len < 24 * 24 )
{
return true;
}
return false;
}
//----------------------------
void CPoly::Draw()
{
polyVert_t verts[MAX_CPOLY_VERTS];
for ( int i = 0; i < mCount; i++ )
{
// Add our midpoint and vert offset to get the actual vertex
VectorAdd( mOrigin1, mOrg[i], verts[i].xyz );
// Assign the same color to each vert
verts[i].modulate[0] = mRefEnt.shaderRGBA[0];
verts[i].modulate[1] = mRefEnt.shaderRGBA[1];
verts[i].modulate[2] = mRefEnt.shaderRGBA[2];
verts[i].modulate[3] = mRefEnt.shaderRGBA[3];
// Copy the ST coords
VectorCopy2( mST[i], verts[i].st );
}
// Add this poly
theFxHelper.AddPolyToScene( mRefEnt.customShader, mCount, verts );
drawnFx++;
}
//----------------------------
void CPoly::CalcRotateMatrix()
{
float cosX, cosZ;
float sinX, sinZ;
float rad;
// rotate around Z
rad = DEG2RAD( mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f );
cosZ = cos( rad );
sinZ = sin( rad );
// rotate around X
rad = DEG2RAD( mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f );
cosX = cos( rad );
sinX = sin( rad );
/*Pitch - aroundx Yaw - around z
1 0 0 c -s 0
0 c -s s c 0
0 s c 0 0 1
*/
mRot[0][0] = cosZ;
mRot[1][0] = -sinZ;
mRot[2][0] = 0;
mRot[0][1] = cosX * sinZ;
mRot[1][1] = cosX * cosZ;
mRot[2][1] = -sinX;
mRot[0][2] = sinX * sinZ;
mRot[1][2] = sinX * cosZ;
mRot[2][2] = cosX;
/*
// ROLL is not supported unless anyone complains, if it needs to be added, use this format
Roll
c 0 s
0 1 0
-s 0 c
*/
mLastFrameTime = theFxHelper.mFrameTime;
}
//--------------------------------
void CPoly::Rotate()
{
vec3_t temp[MAX_CPOLY_VERTS];
float dif = fabs( (double)(mLastFrameTime - theFxHelper.mFrameTime) );
// Very generous check with frameTimes
if ( dif > 0.5f * mLastFrameTime )
{
CalcRotateMatrix();
}
// Multiply our rotation matrix by each of the offset verts to get their new position
for ( int i = 0; i < mCount; i++ )
{
VectorRotate( mOrg[i], mRot, temp[i] );
VectorCopy( temp[i], mOrg[i] );
}
}
//----------------------------
// Update
//----------------------------
bool CPoly::Update()
{
vec3_t mOldOrigin = { 0.0f };
// Game pausing can cause dumb time things to happen, so kill the effect in this instance
if ( mTimeStart > theFxHelper.mTime )
{
return false;
}
// If our timestamp hasn't exired yet, we won't even consider doing any kind of motion
if ( theFxHelper.mTime > mTimeStamp )
{
VectorCopy( mOrigin1, mOldOrigin );
if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false )
{
// we are marked for death
return false;
}
}
if ( !Cull() )
{
// only rotate when our start timestamp has expired
if ( theFxHelper.mTime > mTimeStamp )
{
// Only rotate whilst moving
if ( !VectorCompare( mOldOrigin, mOrigin1 ))
{
Rotate();
}
}
UpdateRGB();
UpdateAlpha();
Draw();
}
return true;
}
//----------------------------
void CPoly::PolyInit()
{
if ( mCount < 3 )
{
return;
}
int i;
vec3_t org={0,0,0};
// Find our midpoint
for ( i = 0; i < mCount; i++ )
{
VectorAdd( org, mOrg[i], org );
}
VectorScale( org, (float)(1.0f / mCount), org );
// now store our midpoint for physics purposes
VectorCopy( org, mOrigin1 );
// Now we process the passed in points and make it so that they aren't actually the point...
// rather, they are the offset from mOrigin1.
for ( i = 0; i < mCount; i++ )
{
VectorSubtract( mOrg[i], mOrigin1, mOrg[i] );
}
CalcRotateMatrix();
}
/*
-------------------------
CBezier
Bezier curve line
-------------------------
*/
//----------------------------
bool CBezier::Update( void )
{
float ftime, time2;
ftime = cg.frametime * 0.001f;
time2 = ftime * ftime * 0.5f;
for ( int i = 0; i < 3; i++ )
{
mControl1[i] = mControl1[i] + ftime * mControl1Vel[i] + time2 * mControl1Vel[i];
mControl2[i] = mControl2[i] + ftime * mControl2Vel[i] + time2 * mControl2Vel[i];
}
UpdateSize();
UpdateRGB();
UpdateAlpha();
Draw();
return true;
}
//----------------------------
inline void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texcoord2 )
{
vec3_t lineDir, cross, viewDir;
static vec3_t lastEnd[2];
polyVert_t verts[4];
float scale;
VectorSubtract( end, start, lineDir );
VectorSubtract( end, cg.refdef.vieworg, viewDir );
CrossProduct( lineDir, viewDir, cross );
VectorNormalize( cross );
scale = mRefEnt.radius * 0.5f;
//Construct the oriented quad
if ( mInit )
{
VectorCopy( lastEnd[0], verts[0].xyz );
VectorCopy( lastEnd[1], verts[1].xyz );
}
else
{
VectorMA( start, -scale, cross, verts[0].xyz );
VectorMA( start, scale, cross, verts[1].xyz );
}
verts[0].st[0] = 0.0f;
verts[0].st[1] = texcoord1;
verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 );
verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 );
verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 );
verts[0].modulate[3] = mRefEnt.shaderRGBA[3];
verts[1].st[0] = 1.0f;
verts[1].st[1] = texcoord1;
verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 );
verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 );
verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 );
verts[1].modulate[3] = mRefEnt.shaderRGBA[3];
if ( texcoord1 == 0.0f )
{
verts[0].modulate[0] = 0;
verts[0].modulate[1] = 0;
verts[0].modulate[2] = 0;
verts[0].modulate[3] = 0;
verts[1].modulate[0] = 0;
verts[1].modulate[1] = 0;
verts[1].modulate[2] = 0;
verts[1].modulate[3] = 0;
}
VectorMA( end, scale, cross, verts[2].xyz );
verts[2].st[0] = 1.0f;
verts[2].st[1] = texcoord2;
verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 );
verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 );
verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 );
verts[2].modulate[3] = mRefEnt.shaderRGBA[3];
VectorMA( end, -scale, cross, verts[3].xyz );
verts[3].st[0] = 0.0f;
verts[3].st[1] = texcoord2;
verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 );
verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 );
verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 );
verts[3].modulate[3] = mRefEnt.shaderRGBA[3];
cgi_R_AddPolyToScene( mRefEnt.customShader, 4, verts );
VectorCopy( verts[2].xyz, lastEnd[1] );
VectorCopy( verts[3].xyz, lastEnd[0] );
mInit = true;
}
const float BEZIER_RESOLUTION = 16.0f;
//----------------------------
void CBezier::Draw( void )
{
vec3_t pos, old_pos;
float mu, mum1;
float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2;
int i;
VectorCopy( mOrigin1, old_pos );
mInit = false; //Signify a new batch for vert gluing
// Calculate the texture coords so the texture can stretch along the whole bezier
// if ( mFlags & FXF_WRAP )
// {
// tex = m_stScale / 1.0f;
// }
float mum13, mu3, group1, group2;
tc1 = 0.0f;
for ( mu = incr; mu <= 1.0f; mu += incr )
{
//Four point curve
mum1 = 1 - mu;
mum13 = mum1 * mum1 * mum1;
mu3 = mu * mu * mu;
group1 = 3 * mu * mum1 * mum1;
group2 = 3 * mu * mu *mum1;
for ( i = 0; i < 3; i++ )
{
pos[i] = mum13 * mOrigin1[i] + group1 * mControl1[i] + group2 * mControl2[i] + mu3 * mOrigin2[i];
}
// if ( m_flags & FXF_WRAP )
// {
tc2 = mu * tex;
// }
// else
// {
// // Texture will get mapped onto each segement
// tc1 = 0.0f;
// tc2 = 1.0f;
// }
//Draw it
DrawSegment( old_pos, pos, tc1, tc2 );
VectorCopy( pos, old_pos );
tc1 = tc2;
}
drawnFx++;
mLines++; // NOT REALLY A LINE
}
/*
-------------------------
CFlash
Full screen flash
-------------------------
*/
//----------------------------
bool CFlash::Update( void )
{
UpdateRGB();
Draw();
return true;
}
//----------------------------
void CFlash::Init( void )
{
vec3_t dif;
float mod = 1.0f, dis;
VectorSubtract( mOrigin1, cg.refdef.vieworg, dif );
dis = VectorNormalize( dif );
mod = DotProduct( dif, cg.refdef.viewaxis[0] );
if ( dis > 600 || ( mod < 0.5f && dis > 100 ))
{
mod = 0.0f;
}
else if ( mod < 0.5f && dis <= 100 )
{
mod += 1.1f;
}
mod *= (1.0f - ((dis * dis) / (600.0f * 600.0f)));
VectorScale( mRGBStart, mod, mRGBStart );
VectorScale( mRGBEnd, mod, mRGBEnd );
}
//----------------------------
void CFlash::Draw( void )
{
// Interestingly, if znear is set > than this, then the flash
// doesn't appear at all.
const float FLASH_DISTANCE_FROM_VIEWER = 8.0f;
mRefEnt.reType = RT_SPRITE;
for ( int i = 0; i < 3; i++ )
{
if ( mRefEnt.lightingOrigin[i] > 1.0f )
{
mRefEnt.lightingOrigin[i] = 1.0f;
}
else if ( mRefEnt.lightingOrigin[i] < 0.0f )
{
mRefEnt.lightingOrigin[i] = 0.0f;
}
}
mRefEnt.shaderRGBA[0] = mRefEnt.lightingOrigin[0] * 255;
mRefEnt.shaderRGBA[1] = mRefEnt.lightingOrigin[1] * 255;
mRefEnt.shaderRGBA[2] = mRefEnt.lightingOrigin[2] * 255;
mRefEnt.shaderRGBA[3] = 255;
VectorCopy( cg.refdef.vieworg, mRefEnt.origin );
VectorMA( mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, cg.refdef.viewaxis[0], mRefEnt.origin );
// This is assuming that the screen is wider than it is tall.
mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan (DEG2RAD (cg.refdef.fov_x * 0.5f));
theFxHelper.AddFxToScene( &mRefEnt );
drawnFx++;
}
| 412 | 0.953288 | 1 | 0.953288 | game-dev | MEDIA | 0.714944 | game-dev,graphics-rendering | 0.975785 | 1 | 0.975785 |
crownengine/crown | 3,029 | tools/level_editor/user.vala | /*
* Copyright (c) 2012-2025 Daniele Bartolini et al.
* SPDX-License-Identifier: GPL-3.0-or-later
*/
namespace Crown
{
public class User
{
// Data
public Hashtable _data;
// Signals
public signal void recent_project_added(string source_dir, string name, string time);
public signal void recent_project_touched(string source_dir, string time);
public signal void recent_project_removed(string source_dir);
public User()
{
}
public void decode(Hashtable sjson)
{
_data = sjson;
_data.foreach((ee) => {
if (ee.key == "recent_projects") {
var recent_projects = ee.value as Gee.ArrayList<Value?>;
for (int ii = 0; ii < recent_projects.size; ++ii) {
Hashtable rp = recent_projects[ii] as Hashtable;
recent_project_added((string)rp["source_dir"]
, (string)rp["name"]
, (string)rp["mtime"]
);
}
} else {
logw("Unknown key: `%s`".printf(ee.key));
}
return true;
});
}
public Hashtable encode()
{
return _data;
}
public void load(string path)
{
try {
Hashtable sjson = SJSON.load_from_path(path);
decode(sjson);
} catch (JsonSyntaxError e) {
loge(e.message);
}
}
public void save(string path)
{
try {
SJSON.save(encode(), path);
} catch (JsonWriteError e) {
loge(e.message);
}
}
public void add_or_touch_recent_project(string source_dir, string name)
{
Gee.ArrayList<Value?> recent_projects = null;
Hashtable? project = null;
_data.foreach ((ee) => {
if (ee.key == "recent_projects") {
recent_projects = ee.value as Gee.ArrayList<Value?>;
for (int ii = 0; ii < recent_projects.size; ++ii) {
Hashtable rp = recent_projects[ii] as Hashtable;
if ((string)rp["source_dir"] == source_dir) {
project = rp;
return false; // break
}
}
}
return true;
});
if (recent_projects == null) {
recent_projects = new Gee.ArrayList<Value?>();
_data["recent_projects"] = recent_projects;
}
string mtime = new GLib.DateTime.now_utc().to_unix().to_string();
if (project == null) {
project = new Hashtable();
project["name"] = source_dir; // FIXME: store project name somewhere inside project directory
project["source_dir"] = source_dir;
project["mtime"] = mtime;
recent_projects.add(project);
recent_project_added(source_dir, source_dir, mtime);
} else {
project["mtime"] = mtime;
recent_project_touched(source_dir, mtime);
}
}
public void remove_recent_project(string source_dir)
{
_data.foreach((ee) => {
if (ee.key == "recent_projects") {
var recent_projects = ee.value as Gee.ArrayList<Value?>;
var it = recent_projects.iterator();
for (var has_next = it.next(); has_next; has_next = it.next()) {
Hashtable rp = it.get() as Hashtable;
if ((string)rp["source_dir"] == source_dir) {
it.remove();
recent_project_removed(source_dir);
return false; // break
}
}
}
return true;
});
}
}
} /* namespace Crown */
| 412 | 0.869587 | 1 | 0.869587 | game-dev | MEDIA | 0.474136 | game-dev,devops-infra | 0.758072 | 1 | 0.758072 |
egoal/darkest-pixel-dungeon | 4,453 | core/src/main/java/com/egoal/darkestpixeldungeon/GamesInProgress.kt | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.egoal.darkestpixeldungeon
import com.egoal.darkestpixeldungeon.actors.hero.HeroClass
import com.egoal.darkestpixeldungeon.actors.hero.HeroSubClass
import com.watabou.noosa.Game
import java.io.IOException
import java.util.*
object GamesInProgress {
private const val MAX_SLOT = 6 // enough to compatible with pre 0.6.0 saves
private val progresses = arrayOfNulls<Info?>(MAX_SLOT)
private fun gameFile(slot: Int) = "slot$slot.dat"
private fun depthFile(slot: Int, depth: Int) = "slot$slot-depth$depth.dat"
private fun backupGameFile(slot: Int) = "backup_slot$slot.dat"
private fun backupDepthFile(slot: Int) = "backup_level_slot$slot.dat"
// current
var curSlot: Int = 0
val curGameFile get() = gameFile(curSlot)
fun curDepthFile(depth: Int) = depthFile(curSlot, depth)
val curBackupGameFile get() = backupGameFile(curSlot)
val curBackupDepthFile get() = backupDepthFile(curSlot)
fun reloadAll(): Array<Info?> {
for (i in 0 until MAX_SLOT) {
if (progresses[i] == null)
progresses[i] = load(i)
}
// load old saves
//todo: remove this in later version
return progresses
}
private fun load(slot: Int): Info? {
var info: Info?
try {
val bundle = Dungeon.gameBundle(gameFile(slot))
info = Info()
Dungeon.preview(info, bundle)
} catch (e: IOException) {
info = null
}
return info
}
operator fun get(slot: Int) = progresses[slot]
operator fun set(slot: Int, info: Info?) {
progresses[slot] = info
}
fun delete(slot: Int, deleteLevels: Boolean, deleteBackup: Boolean) {
progresses[slot] = null
Game.instance.deleteFile(gameFile(slot))
if (deleteLevels) {
var depth = 0
while (Game.instance.deleteFile(depthFile(slot, depth))) {
depth++
}
}
if (deleteBackup) {
Game.instance.deleteFile(backupGameFile(slot))
Game.instance.deleteFile(backupDepthFile(slot))
}
}
// old
private val state = HashMap<HeroClass, Info?>()
fun check(cl: HeroClass): Info? {
if (state.containsKey(cl)) {
return state[cl]
} else {
var info: Info?
try {
val bundle = Dungeon.gameBundle(Dungeon.gameFile(cl))
info = Info()
Dungeon.preview(info, bundle)
} catch (e: IOException) {
try {
val bundle = Dungeon.gameBundle(Dungeon.backupGameFile(cl))
info = Info(true)
Dungeon.preview(info, bundle)
} catch (e: IOException) {
info = null
}
}
state[cl] = info
return info
}
}
// fun set(cl: HeroClass, depth: Int, level: Int, challenge: Challenge?) {
// val info = Info()
// info.depth = depth
// info.level = level
// info.challenge = challenge
// state[cl] = info
// }
fun setUnknown(cl: HeroClass) {
state.remove(cl)
}
fun delete(cl: HeroClass) {
state[cl] = null
}
class Info(val isBackup: Boolean = false) {
var name: String = "Unnamed"
var heroClass = HeroClass.ROGUE
var subClass = HeroSubClass.NONE
var depth = 0
var level = 0
var armorTier = 0
var challenges: List<Challenge> = listOf()
val isChallenged: Boolean get() = challenges.isNotEmpty()
}
}
| 412 | 0.886833 | 1 | 0.886833 | game-dev | MEDIA | 0.853543 | game-dev | 0.961337 | 1 | 0.961337 |
neraliu/tainted-phantomjs | 4,135 | src/qt/src/3rdparty/webkit/Source/WebCore/bindings/js/JSDOMStringMapCustom.cpp | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSDOMStringMap.h"
#include "DOMStringMap.h"
#include "Element.h"
#include "JSNode.h"
#include <wtf/text/AtomicString.h>
using namespace JSC;
namespace WebCore {
bool JSDOMStringMap::canGetItemsForName(ExecState*, DOMStringMap* impl, const Identifier& propertyName)
{
return impl->contains(identifierToAtomicString(propertyName));
}
JSValue JSDOMStringMap::nameGetter(ExecState* exec, JSValue slotBase, const Identifier& propertyName)
{
JSDOMStringMap* thisObj = static_cast<JSDOMStringMap*>(asObject(slotBase));
return jsString(exec, thisObj->impl()->item(identifierToAtomicString(propertyName)));
}
void JSDOMStringMap::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
Vector<String> names;
m_impl->getNames(names);
size_t length = names.size();
for (size_t i = 0; i < length; ++i)
propertyNames.add(Identifier(exec, stringToUString(names[i])));
Base::getOwnPropertyNames(exec, propertyNames, mode);
}
bool JSDOMStringMap::deleteProperty(ExecState* exec, const Identifier& propertyName)
{
// Only perform the custom delete if the object doesn't have a native property by this name.
// Since hasProperty() would end up calling canGetItemsForName() and be fooled, we need to check
// the native property slots manually.
PropertySlot slot;
if (getStaticValueSlot<JSDOMStringMap, Base>(exec, s_info.propHashTable(exec), this, propertyName, slot))
return false;
JSValue prototype = this->prototype();
if (prototype.isObject() && asObject(prototype)->hasProperty(exec, propertyName))
return false;
ExceptionCode ec = 0;
m_impl->deleteItem(identifierToString(propertyName), ec);
setDOMException(exec, ec);
return true;
}
bool JSDOMStringMap::putDelegate(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot&)
{
// Only perform the custom put if the object doesn't have a native property by this name.
// Since hasProperty() would end up calling canGetItemsForName() and be fooled, we need to check
// the native property slots manually.
PropertySlot slot;
if (getStaticValueSlot<JSDOMStringMap, Base>(exec, s_info.propHashTable(exec), this, propertyName, slot))
return false;
JSValue prototype = this->prototype();
if (prototype.isObject() && asObject(prototype)->hasProperty(exec, propertyName))
return false;
String stringValue = ustringToString(value.toString(exec));
if (exec->hadException())
return true;
ExceptionCode ec = 0;
impl()->setItem(identifierToString(propertyName), stringValue, ec);
setDOMException(exec, ec);
return true;
}
} // namespace WebCore
| 412 | 0.939001 | 1 | 0.939001 | game-dev | MEDIA | 0.487326 | game-dev | 0.945947 | 1 | 0.945947 |
francot514/FreeSims | 15,096 | SimsVille/SimsAntics/engine/VMSlotParser.cs | /*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using FSO.Files.Formats.IFF.Chunks;
using FSO.LotView.Model;
using FSO.Common.Utils;
using FSO.SimAntics.Model.Routing;
using FSO.SimAntics.NetPlay.Model;
using System.IO;
using FSO.SimAntics.Marshals.Threads;
namespace FSO.SimAntics.Engine
{
public class VMSlotParser
{
public const double ANGLE_ERROR = -0.1f;
public List<VMFindLocationResult> Results;
public VMRouteFailCode FailCode = VMRouteFailCode.NoValidGoals;
public VMEntity Blocker = null;
public SLOTItem Slot;
private static VMRouteFailCode[] FailPrio = {
VMRouteFailCode.NoValidGoals,
VMRouteFailCode.NoChair,
VMRouteFailCode.DestTileOccupiedPerson,
VMRouteFailCode.DestTileOccupied,
};
private SLOTFlags Flags;
private int MinProximity;
private int MaxProximity;
private int DesiredProximity;
private bool OnlySit
{
get
{
return (Slot.Sitting > 0 && Slot.Standing == 0);
}
}
public VMSlotParser(SLOTItem slot)
{
Slot = slot;
Flags = slot.Rsflags;
MinProximity = slot.MinProximity;
MaxProximity = slot.MaxProximity;
DesiredProximity = slot.OptimalProximity;
if (MaxProximity == 0) { MaxProximity = MinProximity; }
if (DesiredProximity == 0) { DesiredProximity = MinProximity; }
}
// TODO: float values may desync if devices are not both x86 or using a different C# library.
// Might need to replace with fixed point library for position and rotation
/// <summary>
/// This method will find all the avaliable locations within the criteria ordered by proximity to the optimal proximity
/// External functions can then decide which is most desirable. E.g. the nearest slot to the object may be the longest route if
/// its in another room.
/// </summary>
/// <param name="obj"></param>
/// <param name="slot"></param>
/// <param name="context"></param>
/// <returns></returns>
public List<VMFindLocationResult> FindAvaliableLocations(VMEntity obj, VMContext context, VMEntity caller)
{
/**
* Start at min proximity and circle around the object to find the avaliable locations.
* Then pick the one nearest to the optimal value
*/
/**
* ------ MAJOR TODO: ------
* Avoid vector math at all costs! Small differences in hardware could cause desyncs.
* This really goes for all areas of the SimAntics engine, but here it's particularly bad.
*/
Vector2 center;
if (OnlySit) FailCode = VMRouteFailCode.NoChair;
// if we need to use the average location of an object group, it needs to be calculated.
if (((Flags & SLOTFlags.UseAverageObjectLocation) > 0) && (obj.MultitileGroup.MultiTile)) {
center = new Vector2(0, 0);
var objs = obj.MultitileGroup.Objects;
for (int i = 0; i < objs.Count; i++)
{
center += new Vector2(objs[i].Position.x/16f, objs[i].Position.y/16f);
}
center /= objs.Count;
} else center = new Vector2(obj.Position.x/16f, obj.Position.y/16f);
//add offset of slot if it exists. must be rotated to be relative to object
var rotOff = Vector3.Transform(Slot.Offset, Matrix.CreateRotationZ(obj.RadianDirection));
var circleCtr = new Vector2(center.X + rotOff.X / 16, center.Y + rotOff.Y / 16);
ushort room = context.VM.Context.GetRoomAt(obj.Position);
Results = new List<VMFindLocationResult>();
if ((Flags & SLOTFlags.SnapToDirection) > 0)
{ //snap to the specified direction, on the specified point.
// double baseRot;
if (Slot.Facing > SLOTFacing.FaceAwayFromObject)
{
// bit of a legacy thing here. Facing field did not use to exist,
// which is why SnapToDirection was hacked to use the directional flags.
// now that it exists, it is used instead, to encode the same information...
// just transform back into old format.
Flags |= (SLOTFlags)(1 << (int)Slot.Facing);
}
else
{
if (((int)Flags & 255) == 0) Flags |= SLOTFlags.NORTH;
}
var flagRot = DirectionUtils.PosMod(obj.RadianDirection+FlagsAsRad(Flags), Math.PI*2);
if (flagRot > Math.PI) flagRot -= Math.PI * 2;
VerifyAndAddLocation(obj, circleCtr, center, Flags, Double.MaxValue, context, caller, (float)flagRot);
return Results;
}
else
{
if (((int)Flags & 255) == 0 || Slot.Offset != new Vector3())
{
//exact position
//Flags |= (SLOTFlags)255;
// special case, walk directly to point.
VerifyAndAddLocation(obj, circleCtr, center, Flags, Double.MaxValue, context, caller, float.NaN);
return Results;
}
var maxScore = Math.Max(DesiredProximity - MinProximity, MaxProximity - DesiredProximity) + (LotTilePos.Distance(obj.Position, caller.Position)+MaxProximity)/3 + 2;
var ignoreRooms = (Flags & SLOTFlags.IgnoreRooms) > 0;
var resolutionBound = (MaxProximity / Slot.Resolution) * Slot.Resolution;
for (int x = -resolutionBound; x <= resolutionBound; x += Slot.Resolution)
{
for (int y = -resolutionBound; y <= resolutionBound; y += Slot.Resolution)
{
var pos = new Vector2(circleCtr.X + x / 16.0f, circleCtr.Y + y / 16.0f);
double distance = Math.Sqrt(x * x + y * y);
if (distance >= MinProximity - 0.01 && distance <= MaxProximity + 0.01 && (ignoreRooms || context.VM.Context.GetRoomAt(new LotTilePos((short)Math.Round(pos.X * 16), (short)Math.Round(pos.Y * 16), obj.Position.Level)) == room)) //slot is within proximity
{
var routeEntryFlags = (GetSearchDirection(circleCtr, pos, obj.RadianDirection) & Flags); //the route needs to know what conditions it fulfilled
if (routeEntryFlags > 0) //within search location
{
double baseScore = ((maxScore - Math.Abs(DesiredProximity - distance)) + context.VM.Context.NextRandom(1024) / 1024.0f);
VerifyAndAddLocation(obj, pos, center, routeEntryFlags, baseScore, context, caller, float.NaN);
}
}
}
}
}
/** Sort by how close they are to desired proximity **/
if (Results.Count > 1) Results = Results.OrderBy(x => -x.Score).ToList(); //avoid sort because it acts incredibly unusually
if (Results.Count > 0) FailCode = VMRouteFailCode.Success;
return Results;
}
private void VerifyAndAddLocation(VMEntity obj, Vector2 pos, Vector2 center, SLOTFlags entryFlags, double score, VMContext context, VMEntity caller, float facingDir)
{
//note: verification is not performed if snap target slot is enabled.
var tpos = new LotTilePos((short)Math.Round(pos.X * 16), (short)Math.Round(pos.Y * 16), obj.Position.Level);
if (context.IsOutOfBounds(tpos)) return;
score -= LotTilePos.Distance(tpos, caller.Position)/3.0;
if (Slot.SnapTargetSlot < 0 && context.Architecture.RaycastWall(new Point((int)pos.X, (int)pos.Y), new Point(obj.Position.TileX, obj.Position.TileY), obj.Position.Level))
{
SetFail(VMRouteFailCode.WallInWay, null);
return;
}
bool faceAnywhere = false;
if (float.IsNaN(facingDir))
{
var obj3P = obj.Position.ToVector3();
var objP = new Vector2(obj3P.X, obj3P.Y);
switch (Slot.Facing)
{
case SLOTFacing.FaceTowardsObject:
facingDir = (float)GetDirectionTo(pos, objP); break;
case SLOTFacing.FaceAwayFromObject:
facingDir = (float)GetDirectionTo(objP, pos); break;
case SLOTFacing.FaceAnywhere:
faceAnywhere = true;
facingDir = 0.0f; break;
default:
int intDir = (int)Math.Round(Math.Log((double)obj.Direction, 2));
var rotatedF = ((int)Slot.Facing + intDir) % 8;
facingDir = (float)(((int)rotatedF > 4) ? ((double)rotatedF * Math.PI / 4.0) : (((double)rotatedF - 8.0) * Math.PI / 4.0)); break;
}
}
VMEntity chair = null;
if (Slot.SnapTargetSlot < 0)
{
var solid = caller.PositionValid(tpos, Direction.NORTH, context);
if (solid.Status != Model.VMPlacementError.Success)
{
if (solid.Object != null && solid.Object is VMGameObject)
{
if (Slot.Sitting > 0 && solid.Object.EntryPoints[26].ActionFunction != 0)
{
chair = solid.Object;
}
else
{
SetFail(VMRouteFailCode.DestTileOccupied, solid.Object);
return;
}
}
}
if (chair != null && (Math.Abs(DirectionUtils.Difference(chair.RadianDirection, facingDir)) > Math.PI / 4))
return; //not a valid goal.
if (chair == null && OnlySit) return;
}
Results.Add(new VMFindLocationResult
{
Position = new LotTilePos((short)Math.Round(pos.X * 16), (short)Math.Round(pos.Y * 16), obj.Position.Level),
Score = score * ((chair != null) ? Slot.Sitting : Slot.Standing), //todo: prefer closer?
RadianDirection = facingDir,
Chair = chair,
FaceAnywhere = faceAnywhere,
RouteEntryFlags = entryFlags
});
}
private void SetFail(VMRouteFailCode code, VMEntity blocker)
{
if (Array.IndexOf(FailPrio, code) > Array.IndexOf(FailPrio, FailCode))
{
FailCode = code;
Blocker = blocker;
}
}
private static double FlagsAsRad(SLOTFlags dir)
{
double value = Math.Round(Math.Log((int)dir & 255, 2))*Math.PI/4;
//if (value > Math.PI) value -= 2*Math.PI;
return value;
}
/// <summary>
/// Returns which search direction (n/s/e/w/ne/nw/se/sw) a target is in relation to an object. (absolute)
/// </summary>
/// <param name="pos1">The position of the source.</param>
/// <param name="pos2">The position of the target.</param>
/// <returns></returns>
public static SLOTFlags GetSearchDirection(Vector2 pos1, Vector2 pos2, float rotShift){
double dir = Math.Atan2(Math.Floor(pos2.X) - Math.Floor(pos1.X), Math.Floor(pos1.Y) - Math.Floor(pos2.Y)) * (180.0/Math.PI);
dir = DirectionUtils.NormalizeDegrees(dir - rotShift * (180.0 / Math.PI));
SLOTFlags result = (SLOTFlags)0;
if (dir >= -45.0 - ANGLE_ERROR && dir <= 45.0 + ANGLE_ERROR) result |= SLOTFlags.NORTH;
if (dir >= 0.0 - ANGLE_ERROR && dir <= 90.0 + ANGLE_ERROR) result |= SLOTFlags.NORTH_EAST;
if (dir >= 45.0 - ANGLE_ERROR && dir <= 135.0 + ANGLE_ERROR) result |= SLOTFlags.EAST;
if ((dir >= 90.0 - ANGLE_ERROR && dir <= 180.0 + ANGLE_ERROR) || (dir <= -180.0 + ANGLE_ERROR)) result |= SLOTFlags.SOUTH_EAST;
if (dir >= 135.0 - ANGLE_ERROR || dir <= -135.0 + ANGLE_ERROR) result |= SLOTFlags.SOUTH;
if ((dir >= -180.0 - ANGLE_ERROR && dir <= -135.0 + ANGLE_ERROR) || (dir >= 180.0 - ANGLE_ERROR)) result |= SLOTFlags.SOUTH_WEST;
if (dir >= -135.0 - ANGLE_ERROR && dir <= -45.0 + ANGLE_ERROR) result |= SLOTFlags.WEST;
if (dir >= -90.0 - ANGLE_ERROR && dir <= 0.0 + ANGLE_ERROR) result |= SLOTFlags.NORTH_WEST;
return result;
}
public static SLOTFlags RadianToFlags(double rad)
{
int result = (int)(Math.Round((rad / (Math.PI * 2)) * 8) + 80) % 8; //for best results, make sure rad is >-pi and <pi
return (SLOTFlags)(1 << result);
}
public static double GetDirectionTo(Vector2 pos1, Vector2 pos2)
{
return Math.Atan2(pos2.X - pos1.X, -(pos2.Y - pos1.Y));
}
}
public class VMFindLocationResult
{
public float RadianDirection;
public LotTilePos Position;
public double Score;
public bool FaceAnywhere = false;
public VMEntity Chair;
public SLOTFlags RouteEntryFlags = SLOTFlags.NORTH;
public VMFindLocationResult() { }
#region VM Marshalling Functions
public VMFindLocationResultMarshal Save()
{
return new VMFindLocationResultMarshal
{
RadianDirection = RadianDirection,
Position = Position,
Score = Score,
FaceAnywhere = FaceAnywhere,
Chair = (Chair == null) ? (short)0 : Chair.ObjectID,
RouteEntryFlags = RouteEntryFlags
};
}
public void Load(VMFindLocationResultMarshal input, VMContext context)
{
RadianDirection = input.RadianDirection;
Position = input.Position;
Score = input.Score;
FaceAnywhere = input.FaceAnywhere;
Chair = context.VM.GetObjectById(input.Chair);
RouteEntryFlags = input.RouteEntryFlags;
}
public VMFindLocationResult(VMFindLocationResultMarshal input, VMContext context)
{
Load(input, context);
}
#endregion
}
}
| 412 | 0.91243 | 1 | 0.91243 | game-dev | MEDIA | 0.859609 | game-dev,graphics-rendering | 0.951038 | 1 | 0.951038 |
KospY/BasSDK | 1,277 | Assets/SDK/Scripts/Catalog/Keyboard/KeyButton.cs | using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace ThunderRoad
{
[RequireComponent(typeof(BoxCollider))]
public class KeyButton : ThunderBehaviour
{
public string keyId;
public Canvas canvas;
public TextMeshPro textMesh;
private void OnValidate()
{
//add a canvas for images
if (gameObject.TryGetOrAddComponentInChildren<Canvas>(out var foundCanvas))
{
this.canvas = foundCanvas;
foundCanvas.name = "Canvas";
if (!foundCanvas.TryGetComponent<Image>(out var image))
{
image = this.canvas.gameObject.AddComponent<Image>();
image.color = Color.clear;
}
}
//add a textMeshPro for text
if (gameObject.TryGetOrAddComponentInChildren<TextMeshPro>(out var foundTextMesh))
{
textMesh = foundTextMesh;
textMesh.name = "TextMeshPro";
}
if (string.IsNullOrEmpty(keyId))
{
Debug.LogError($"Keyboard Key {this.name} does not have an ID set. Please set an ID and map it to a valid KeyboardData", this);
}
}
}
}
| 412 | 0.859146 | 1 | 0.859146 | game-dev | MEDIA | 0.522336 | game-dev,graphics-rendering | 0.967885 | 1 | 0.967885 |
floodfx/undead | 3,970 | src/main/java/run/undead/context/WsContext.java | package run.undead.context;
import run.undead.event.SimpleUndeadInfo;
import run.undead.event.UndeadEvent;
import run.undead.event.UndeadInfo;
import run.undead.protocol.Reply;
import run.undead.pubsub.PubSub;
import run.undead.template.UndeadTemplate;
import run.undead.view.Meta;
import run.undead.view.View;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* WsContext is an implementation of the {@link Context} for the WebSocket
* lifecycle.
*/
public class WsContext implements Context {
protected String id;
protected String url;
protected View view;
protected String joinRef;
protected String msgRef;
protected String csrfToken;
protected String redirect;
protected WsSender sender;
protected Map<String, String> subs; // topic to subId
protected PubSub pubsub;
protected UndeadTemplate lastTmpl;
protected List<UndeadEvent> events;
protected String title;
public WsContext(String id, String url, View view) {
this.id = id;
this.url = url;
this.view = view;
this.subs = new ConcurrentHashMap<>();
}
@Override
public String id() {
return this.id;
}
@Override
public String url() {
return this.url;
}
@Override
public Boolean connected() {
return true;
}
@Override
public void pageTitle(String newTitle) {
this.title = newTitle;
}
@Override
public void pushEvent(UndeadEvent event) {
this.events.add(event);
}
@Override
public void sendInfo(UndeadInfo info) {
this.view.handleInfo(this, info);
var content = this.view.render(new Meta());
this.sender.send(Reply.diff(this.id, diffParts(content)));
}
@Override
public void redirect(String url) {
this.redirect = url;
}
@Override
public void subscribe(String topic) {
if(this.pubsub == null) {
throw new RuntimeException("pubsub not set");
}
// check if already subscribed
if(this.subs.containsKey(topic)) {
return;
}
var subId = this.pubsub.subscribe(topic, (t, m) -> {
this.sendInfo(new SimpleUndeadInfo(t, m));
});
// save topic to sub mapping
this.subs.put(topic, subId);
}
@Override
public void unsubscribe(String topic) {
if(this.pubsub == null) {
throw new RuntimeException("pubsub not set");
}
// check if we have a subId for this topic
if(!this.subs.containsKey(topic)) {
return;
}
this.pubsub.unsubscribe(this.subs.get(topic));
}
@Override
public void publish(String topic, String data) {
if(this.pubsub == null) {
throw new RuntimeException("pubsub not set");
}
this.pubsub.publish(topic, data);
}
public void handleClose() {
if(this.pubsub != null) {
for(var topic : subs.keySet()) {
this.unsubscribe(topic);
}
}
if (this.view != null) {
this.view.shutdown();
}
}
public void handleError(Object err) {
// TODO send something to client to reload?
this.handleClose();
}
/**
* diffParts takes the new template and diffs it with the last template (if there was one)
* and returns the diff "parts" to send to the client. Additionally, this method will
* add the title and events to the parts if they are set.
* @param newTmpl the new template to diff with the last template
* @return the diff "parts" to send to the client
*/
public Map<String, Object> diffParts(UndeadTemplate newTmpl) {
var oldTmpl = this.lastTmpl;
this.lastTmpl = newTmpl;
var parts = newTmpl.toParts();
// if we have an old template diff with new template
if(oldTmpl != null) {
parts = UndeadTemplate.diff(oldTmpl.toParts(), newTmpl.toParts());
}
// add title if set
if(this.title != null) {
parts.put("t", this.title);
this.title = null;
}
// add events if set
if(this.events != null) {
parts.put("e", this.events);
this.events = null;
}
return parts;
}
}
| 412 | 0.890958 | 1 | 0.890958 | game-dev | MEDIA | 0.305292 | game-dev | 0.976141 | 1 | 0.976141 |
sezero/uhexen2 | 6,265 | gamecode/hc/portals/sunstaff.hc | /*
==============================================================================
Q:\art\models\weapons\sunstaff\final\newfinal\sunstaff.hc
MG
==============================================================================
*/
// For building the model
$cd Q:\art\models\weapons\sunstaff\final\newfinal
$origin 0 0 0
$base BASE skin
$skin skin
$flags 0
//
$frame fircyc1 fircyc2 fircyc3 fircyc4 fircyc5
$frame fircyc6 fircyc7 fircyc8 fircyc9 fircyc10
//
$frame fire1 fire2 fire3 fire4
//
$frame idle1 idle2 idle3 idle4 idle5
$frame idle6 idle7 idle8 idle9 idle10
$frame idle11 idle12 idle13 idle14 idle15
$frame idle16 idle17 idle18 idle19 idle20
$frame idle21 idle22 idle23 idle24 idle25
$frame idle26 idle27 idle28 idle29 idle30
$frame idle31
//
$frame select1 select2 select3 select4 select5
$frame select6 select7 select8 select9 select10
$frame select11 select12 select13 select14
//
$frame settle1 settle2 settle3 settle4 settle5
void FireSunstaff (vector dir, float ofs)
{
vector org1,org2, vec, dir, endspot,endplane;
float remainder, reflect_count,damg;
//Draw a larger pulsating transparent yellow beam,
//rotating, with a smaller solid white beam in the
//center. Player casts brightlight while using it.
//each point reflection has a double-sphere similar
//to the beam. Each reflection does 3/4 less damage.
//primary damage = 37?
if(self.attack_finished>time)
return;
if(self.t_width<time)
{
sound(self,CHAN_WEAPON,"crusader/sunhum.wav",1,ATTN_NORM);
self.t_width=time+0.2;
}
self.effects(+)EF_BRIGHTLIGHT;
if(self.artifact_active&ART_TOMEOFPOWER&&!ofs)
damg=17;
else
damg=7;
//If powered up, start a quake
if(!ofs)
remainder=1000;
else
remainder=750;
makevectors(self.v_angle);
org1 = self.origin + self.proj_ofs+ v_forward*7;
org2 = org1 + dir*20;
vec = org2 + dir*remainder;
traceline (org2, vec, TRUE, self);
endspot=trace_endpos;
endplane=trace_plane_normal;
remainder-=remainder*trace_fraction;
WriteByte (MSG_BROADCAST, SVC_TEMPENTITY);
WriteByte (MSG_BROADCAST, TE_STREAM_SUNSTAFF1);
WriteEntity (MSG_BROADCAST, self);
WriteByte (MSG_BROADCAST, ofs+STREAM_ATTACHED);
WriteByte (MSG_BROADCAST, 1);
WriteCoord (MSG_BROADCAST, org2_x);
WriteCoord (MSG_BROADCAST, org2_y);
WriteCoord (MSG_BROADCAST, org2_z);
WriteCoord (MSG_BROADCAST, trace_endpos_x);
WriteCoord (MSG_BROADCAST, trace_endpos_y);
WriteCoord (MSG_BROADCAST, trace_endpos_z);
LightningDamage (org1 - v_forward*7, trace_endpos+normalize(dir)*7, self, damg,"sunbeam");
while(remainder>0&&reflect_count<2)
{
org1 = endspot;
dir +=2*endplane;
vec = org1 + normalize(dir)*remainder;
//FIXME: what about reflective triggers?
traceline (org1,vec,TRUE,self);
endspot=trace_endpos;
endplane=trace_plane_normal;
remainder-=remainder*trace_fraction;
reflect_count+=1;
WriteByte (MSG_BROADCAST, SVC_TEMPENTITY);
WriteByte (MSG_BROADCAST, TE_STREAM_SUNSTAFF1);
WriteEntity (MSG_BROADCAST, self);
WriteByte (MSG_BROADCAST, ofs+reflect_count);
WriteByte (MSG_BROADCAST, 2);
WriteCoord (MSG_BROADCAST, org1_x);
WriteCoord (MSG_BROADCAST, org1_y);
WriteCoord (MSG_BROADCAST, org1_z);
WriteCoord (MSG_BROADCAST, trace_endpos_x);
WriteCoord (MSG_BROADCAST, trace_endpos_y);
WriteCoord (MSG_BROADCAST, trace_endpos_z);
LightningDamage (org1, trace_endpos+normalize(dir)*7, self, damg/2,"sunbeam");
}
}
void() FireSunstaffPower =
{
/*
Will fire a main thick beam that will reflect off walls
and cut through stuff.
Two beams on side will waver a bit and track at + & - 45 degrees.
If the main beam hits something, the two secondary beams will
pull forward and lock on as well.
*/
vector dir1,dir2;
makevectors(self.v_angle);
//NOTE: Maybe extra beams cycle around- rotate around 1st beam.
dir1=(v_forward+v_right)*0.5;
dir2=(v_forward+(v_right*-1))*0.5;
FireSunstaff(normalize(v_forward),0);
FireSunstaff(dir1,4);
FireSunstaff(dir2,8);
};
void()sunstaff_ready_loop;
void() Cru_Sun_Fire;
void sunstaff_fire_settle ()
{
self.wfs = advanceweaponframe($settle1,$settle5);
self.th_weapon=sunstaff_fire_settle;
if(self.wfs==WF_CYCLE_WRAPPED)
{
self.effects(-)EF_BRIGHTLIGHT;
self.last_attack=time;
sunstaff_ready_loop();
}
}
void sunstaff_fire_loop ()
{
self.wfs = advanceweaponframe($fircyc1,$fircyc10);
self.th_weapon=sunstaff_fire_loop;
if(self.attack_finished<=time&&self.button0&&self.greenmana>=2&&self.bluemana>=2)
{
if(self.artifact_active&ART_TOMEOFPOWER)
{
FireSunstaffPower();
self.greenmana-=2;
self.bluemana-=2;
}
else
{
makevectors(self.v_angle);
FireSunstaff(v_forward,0);
self.greenmana-=0.35;
self.bluemana-=0.35;
}
self.attack_finished=time + 0.05;
}
if(self.wfs==WF_CYCLE_WRAPPED&&(!self.button0||self.greenmana<2||self.bluemana<2))
{
self.effects(-)EF_BRIGHTLIGHT;
sunstaff_fire_settle();
}
}
void sunstaff_fire (void)
{
self.wfs = advanceweaponframe($fire1,$fire4);
self.th_weapon=sunstaff_fire;
if(self.wfs==WF_CYCLE_WRAPPED)
sunstaff_fire_loop();
}
void() Cru_Sun_Fire =
{
if(self.weaponframe<$idle1 || self.weaponframe>$idle31)
return;
sound (self, CHAN_AUTO, "crusader/sunstart.wav", 1, ATTN_NORM);
self.th_weapon=sunstaff_fire;
thinktime self : 0;
};
void sunstaff_ready_loop (void)
{
self.wfs = advanceweaponframe($idle1,$idle31);
self.th_weapon=sunstaff_ready_loop;
}
void sunstaff_select (void)
{
//go to ready loop, not relaxed?
self.wfs = advanceweaponframe($select1,$select14);
self.weaponmodel = "models/sunstaff.mdl";
self.th_weapon=sunstaff_select;
self.last_attack=time;
if(self.wfs==WF_CYCLE_WRAPPED)
{
self.attack_finished = time - 1;
sunstaff_ready_loop();
}
}
void sunstaff_deselect (void)
{
//go to ready loop, not relaxed?
self.wfs = advanceweaponframe($select14,$select1);
self.th_weapon=sunstaff_deselect;
if(self.wfs==WF_CYCLE_WRAPPED)
W_SetCurrentAmmo();
}
| 412 | 0.876403 | 1 | 0.876403 | game-dev | MEDIA | 0.891445 | game-dev | 0.977024 | 1 | 0.977024 |
mister91jiao/BundleMaster_IntegrateETTask | 2,219 | Assets/BundleMaster/NintendoAdapter/AssetComponentTools_Nintendo.cs | using System.IO;
using System.Text;
using ET;
namespace BM
{
#if Nintendo_Switch
public static partial class AssetComponent
{
/// <summary>
/// NintendoSwitch获取Bundle信息文件的路径
/// </summary>
internal static string BundleFileExistPath_Nintendo(string bundlePackageName, string fileName)
{
string path = Path.Combine(AssetComponentConfig.LocalBundlePath, bundlePackageName, fileName);
//string path = "rom:/Data/StreamingAssets/" + bundlePackageName + "/" + fileName;
return path;
}
internal static async ETTask<string> LoadNintendoFileText(string filePath)
{
nn.fs.FileHandle fileHandle = new nn.fs.FileHandle();
nn.fs.EntryType entryType = nn.fs.EntryType.File;
nn.Result result = nn.fs.FileSystem.GetEntryType(ref entryType, filePath);
if (nn.fs.FileSystem.ResultPathNotFound.Includes(result))
{
AssetLogHelper.LogError("初始化分包未找到要读取的文件: \t" + filePath);
result.abortUnlessSuccess();
return "";
}
result.abortUnlessSuccess();
result = nn.fs.File.Open(ref fileHandle, filePath, nn.fs.OpenFileMode.Read);
result.abortUnlessSuccess();
long fileSize = 0;
result = nn.fs.File.GetSize(ref fileSize, fileHandle);
result.abortUnlessSuccess();
byte[] data = new byte[fileSize];
result = nn.fs.File.Read(fileHandle, 0, data, fileSize);
result.abortUnlessSuccess();
nn.fs.File.Close(fileHandle);
MemoryStream memoryStream = new MemoryStream(data);
StreamReader streamReader = new StreamReader(memoryStream);
//异步读取内容
string str = await streamReader.ReadToEndAsync();
//关闭引用
streamReader.Close();
streamReader.Dispose();
memoryStream.Close();
await memoryStream.DisposeAsync();
return str;
}
}
#endif
}
| 412 | 0.964507 | 1 | 0.964507 | game-dev | MEDIA | 0.240338 | game-dev | 0.99517 | 1 | 0.99517 |
MagmaGuy/EliteMobs | 4,855 | src/main/java/com/magmaguy/elitemobs/items/itemconstructor/MaterialGenerator.java | package com.magmaguy.elitemobs.items.itemconstructor;
import com.magmaguy.elitemobs.combatsystem.CombatSystem;
import com.magmaguy.elitemobs.config.ItemSettingsConfig;
import com.magmaguy.elitemobs.config.ProceduralItemGenerationSettingsConfig;
import com.magmaguy.magmacore.util.Logger;
import org.bukkit.Material;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.bukkit.Material.*;
public class MaterialGenerator {
private static final ArrayList<Material> validProceduralMaterials = new ArrayList();
public static Material generateMaterial(Material material) {
return material;
}
public static Material generateMaterial(double itemTier) {
List<Material> localValidMaterials = (List<Material>) validProceduralMaterials.clone();
if (localValidMaterials.isEmpty()) initializeValidProceduralMaterials();
if (itemTier < CombatSystem.DIAMOND_TIER_LEVEL + ItemSettingsConfig.getMinimumProcedurallyGeneratedDiamondLootLevelPlusSeven())
localValidMaterials.remove(TRIDENT);
if (itemTier < CombatSystem.DIAMOND_TIER_LEVEL + ItemSettingsConfig.getMinimumProcedurallyGeneratedDiamondLootLevelPlusSeven()) {
localValidMaterials.remove(DIAMOND_AXE);
localValidMaterials.remove(DIAMOND_HORSE_ARMOR);
localValidMaterials.remove(DIAMOND_CHESTPLATE);
localValidMaterials.remove(DIAMOND_HELMET);
localValidMaterials.remove(DIAMOND_HOE);
localValidMaterials.remove(DIAMOND_LEGGINGS);
localValidMaterials.remove(DIAMOND_PICKAXE);
localValidMaterials.remove(DIAMOND_SHOVEL);
localValidMaterials.remove(DIAMOND_SWORD);
localValidMaterials.remove(DIAMOND_BOOTS);
}
if (itemTier < CombatSystem.IRON_TIER_LEVEL) {
localValidMaterials.remove(IRON_AXE);
localValidMaterials.remove(IRON_HORSE_ARMOR);
localValidMaterials.remove(IRON_BOOTS);
localValidMaterials.remove(IRON_CHESTPLATE);
localValidMaterials.remove(IRON_HELMET);
localValidMaterials.remove(IRON_HOE);
localValidMaterials.remove(IRON_LEGGINGS);
localValidMaterials.remove(IRON_PICKAXE);
localValidMaterials.remove(IRON_SHOVEL);
localValidMaterials.remove(IRON_SWORD);
localValidMaterials.remove(BOW);
localValidMaterials.remove(CROSSBOW);
localValidMaterials.remove(TURTLE_HELMET);
}
if (itemTier < CombatSystem.STONE_CHAIN_TIER_LEVEL) {
localValidMaterials.remove(CHAINMAIL_BOOTS);
localValidMaterials.remove(CHAINMAIL_CHESTPLATE);
localValidMaterials.remove(CHAINMAIL_HELMET);
localValidMaterials.remove(CHAINMAIL_LEGGINGS);
localValidMaterials.remove(STONE_SWORD);
localValidMaterials.remove(STONE_HOE);
localValidMaterials.remove(STONE_SHOVEL);
localValidMaterials.remove(STONE_PICKAXE);
localValidMaterials.remove(STONE_AXE);
}
if (itemTier < CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL) {
localValidMaterials.remove(GOLDEN_BOOTS);
localValidMaterials.remove(GOLDEN_CHESTPLATE);
localValidMaterials.remove(GOLDEN_HELMET);
localValidMaterials.remove(GOLDEN_LEGGINGS);
localValidMaterials.remove(GOLDEN_SWORD);
localValidMaterials.remove(GOLDEN_HOE);
localValidMaterials.remove(GOLDEN_SHOVEL);
localValidMaterials.remove(GOLDEN_PICKAXE);
localValidMaterials.remove(GOLDEN_AXE);
}
if (localValidMaterials.isEmpty()) return null;
return localValidMaterials.get(ThreadLocalRandom.current().nextInt(localValidMaterials.size()));
}
public static void initializeValidProceduralMaterials() {
validProceduralMaterials.clear();
if (ProceduralItemGenerationSettingsConfig.getValidMaterials().isEmpty()) {
ProceduralItemGenerationSettingsConfig.getInstance().cacheMaterials();
if (ProceduralItemGenerationSettingsConfig.getValidMaterials().isEmpty()) {
Logger.warn("No valid materials detected for the procedural item settings. If you are trying to disable" +
" them, use the 'dropProcedurallyGeneratedItems' option instead. Warn the developer.");
return;
}
}
for (String string : ProceduralItemGenerationSettingsConfig.getValidMaterials()) {
try {
validProceduralMaterials.add(getMaterial(string));
} catch (Exception e) {
Logger.info("Invalid material type detected: " + string);
}
}
}
}
| 412 | 0.791603 | 1 | 0.791603 | game-dev | MEDIA | 0.872776 | game-dev | 0.77645 | 1 | 0.77645 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.