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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rorywalsh/cabbage | 20,824 | Examples/FilePlayers/MincerFilePlayer.csd |
/* Attribution-NonCommercial-ShareAlike 4.0 International
Attribution - You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
NonCommercial - You may not use the material for commercial purposes.
ShareAlike - If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode */
; MincerFilePlayer.csd
; Written by Iain McCurdy, 2014
; Three modes of playback are offered:
; 1. Manual Pointer
; Pointer position is determined by the long horizontal slider 'Manual Pointer'.
; 2. Mouse Scrubber
; Pointer position is determined by the mouse's X position over the waveform view. Playback is also started and stopped using right-click.
; 3. Loop Region
; A region that has been highlighted using left-click and drag is looped using a method and speed chosen in the 'LOOP REGION' GUI area.
; Speed can be random-modulated by increasing Mod.Range. The nature of the modulation is changed using 'Rate 1' and 'Rate 2'. The random function generator is jspline.
; Transpose can be expressed either in semitones or a simple ratio. Select mode 'Semitones' or 'Ratio'
; MOD. POINTER section contains controls which modulate the pointer position using a 'sample-and-hold' type random function
;
; All three of the above methods are playable from a MIDI keyboard (first activate the 'MIDI' checkbox).
; Transposition for MIDI activated notes is governed bu both the MIDI key played and the setting for 'Transpose'
<Cabbage>
#define SLIDER_DESIGN colour( 40, 80, 80), trackerColour("white"), textColour("white"), markerColour("white")
form caption("Mincer File Player") size(1000,370), colour( 0, 0, 0) pluginId("Minc"), guiRefresh(10)
image bounds( 0, 0,1000,370), colour( 50,100,100), outlineColour("White"), line(3), shape("sharp")
soundfiler bounds( 5, 5, 990,140), channel("beg","len"), identChannel("filer1"), colour(0, 255, 255, 255), fontColour(160, 160, 160, 255),
label bounds( 6, 4, 998, 14), text(""), align(left), colour(0,0,0,0), fontColour(200,200,200), identChannel("stringbox")
hslider bounds( 0,138,1000, 30), channel("pointer"), range( 0, 1.00, 0.1), colour( 40, 80, 80), trackerColour("white"), fontColour("white")
label bounds( 0,160,1000, 12), text("Manual Pointer"), fontColour("white")
filebutton bounds( 5,185, 80, 22), text("Open File","Open File"), fontColour("white"), channel("filename"), shape("ellipse")
checkbox bounds( 5,218,120, 12), text("Manual Pointer"), channel("r1"), fontColour:0("white"), fontColour:1("white"), colour(yellow), radioGroup(1)
checkbox bounds( 5,232,120, 12), text("Mouse Scrubber"), channel("r2"), fontColour:0("white"), fontColour:1("white"), colour(yellow), radioGroup(1), value(1)
label bounds( 19,246,100, 10), text("[right click and drag]"), fontColour("white"), align("left")
checkbox bounds( 5,256,120, 12), text("Loop Region"), channel("r3"), fontColour:0("white"), fontColour:1("white"), colour(yellow), radioGroup(1)
label bounds( 19,270,100, 10), text("[left click and drag]"), fontColour("white"), align("left")
checkbox bounds(125,223, 60, 12), channel("lock"), text("Lock"), colour("yellow"), fontColour:0("white"), fontColour:1("white")
checkbox bounds(125,243, 60, 12), channel("MIDI"), text("MIDI"), colour("yellow"), fontColour:0("white"), fontColour:1("white")
label bounds(105,183, 48, 12), text("FFT Size"), fontColour("white")
combobox bounds( 95,195, 70, 20), channel("FFTSize"), text("32768", "16384", "8192", "4096", "2048", "1024", "512", "256", "128", "64", "32", "16", "8", "4"), value(5), fontColour("white")
combobox bounds(170,175, 80, 20), text("Semitone","Ratio"), channel("IntervalMode"), value(1)
image bounds(175,200, 70, 70), colour(0,0,0,0), plant("Semitones"), identChannel("SemitonesPlant_ident"), visible(1) {
rslider bounds( 0, 0, 70, 70), channel("Semitones"), range(-48, 48, 0,1,1), text("Semitones"), $SLIDER_DESIGN
}
image bounds(175,200, 70, 70), colour(0,0,0,0), plant("Ratio"), identChannel("RatioPlant_ident"), visible(0) {
nslider bounds( 20, 0, 25, 18), channel("Numerator"), range(1,99,3,1,1)
image bounds( 15, 26, 35, 1), shape("sharp")
nslider bounds( 20, 35, 25, 18), channel("Denominator"), range(1,99,2,1,1)
}
rslider bounds(240,200, 70, 70), channel("portamento"),range(0, 20,0.05,0.5,0.01), text("Port.Time"), $SLIDER_DESIGN
rslider bounds(305,200, 70, 70), channel("Stack"),range(1, 30, 1, 1, 1), text("Stack"), $SLIDER_DESIGN
rslider bounds(370,200, 70, 70), channel("StackIntvl"),range(-12, 12, 1), text("Interval"), $SLIDER_DESIGN
image bounds(450,188, 305,90), colour(0,0,0,0), outlineColour("silver"), outlineThickness(1), shape("sharp"), plant("LoopRegion") {
label bounds( 0, 2, 305,10), text("L O O P R E G I O N"), fontColour("white")
label bounds( 10, 24, 85, 12), text("Shape"), fontColour("white")
combobox bounds( 10, 37, 85, 20), channel("LoopMode"), text("Forward","Backward","Triangle","Sine"), value(1), fontColour:0("white")
checkbox bounds( 10, 63, 85, 14), channel("SpeedMult"), text("Speed x 10"), value(0), fontColour:0("white"), fontColour:1("white")
rslider bounds(100, 17, 70, 70), channel("Speed"), range(-2, 2, 1,1,0.001), text("Speed"), $SLIDER_DESIGN
nslider bounds(170, 35, 60, 30), channel("ModRange"), range(0,2,0,1,0.001), colour( 0, 0, 0), text("Mod.Range"), textColour("white")
nslider bounds(235, 20, 60, 30), channel("Rate1"), range(0,30,1,1,0.001), colour( 0, 0, 0), text("Rate 1"), textColour("white")
nslider bounds(235, 50, 60, 30), channel("Rate2"), range(0,30,2,1,0.001), colour( 0, 0, 0), text("Rate 2"), textColour("white")
}
image bounds(760,188, 145,90), colour(0,0,0,0), outlineColour("silver"), outlineThickness(1), shape("sharp"), plant("ModPtr") {
label bounds( 0, 2, 135,10), text("M O D. P O I N T E R"), fontColour("white")
nslider bounds( 10, 35, 60, 30), channel("PtrModRange"), range(0,1,0,1,0.001), colour( 0, 0, 0), text("Mod.Range"), textColour("white")
nslider bounds( 75, 20, 60, 30), channel("PtrRate1"), range(0,500,1,1,0.001), colour( 0, 0, 0), text("Rate 1"), textColour("white")
nslider bounds( 75, 50, 60, 30), channel("PtrRate2"), range(0,500,2,1,0.001), colour( 0, 0, 0), text("Rate 2"), textColour("white")
}
image bounds(915,200, 70, 70), colour(0,0,0,0), plant("output") {
rslider bounds( 0, 0, 70, 70), channel("level"), range( 0, 1.00, 1, 0.5), text("Level"), $SLIDER_DESIGN
}
image bounds( 5,290,195, 70), colour(0,0,0,0) {
rslider bounds( 0, 0, 70, 70), channel("AttTim"), range(0, 5, 0, 0.5, 0.001), text("Att.Tim"), $SLIDER_DESIGN
rslider bounds( 65, 0, 70, 70), channel("RelTim"), range(0.01, 5, 0.05, 0.5, 0.001), text("Rel.Tim"), $SLIDER_DESIGN
rslider bounds(130, 0, 70, 70), channel("MidiRef"), range(0,127,60, 1, 1), text("MIDI Ref."), $SLIDER_DESIGN
}
keyboard bounds(215,290,780, 75)
</Cabbage>
<CsoundSynthesizer>
<CsOptions>
-n -+rtmidi=NULL -M0 -d
</CsOptions>
<CsInstruments>
; sr set by host
ksmps = 64
nchnls = 2
0dbfs = 1
massign 0, 3
gichans init 0 ;
giReady init 0 ; flag to indicate function table readiness
giFFTSizes[] array 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4 ; an array is used to store FFT window sizes
giTriangle ftgen 0, 0, 4097, 7, 0, 2048, 1, 2048, 0
giRectSine ftgen 0, 0, 4097, 19, 1, 0.5, 0, 1
gSfilepath init ""
gkFileLen init 0
opcode FileNameFromPath,S,S ; Extract a file name (as a string) from a full path (also as a string)
Ssrc xin ; Read in the file path string
icnt strlen Ssrc ; Get the length of the file path string
LOOP: ; Loop back to here when checking for a backslash
iasc strchar Ssrc, icnt ; Read ascii value of current letter for checking
if iasc==92 igoto ESCAPE ; If it is a backslash, escape from loop
loop_gt icnt,1,0,LOOP ; Loop back and decrement counter which is also used as an index into the string
ESCAPE: ; Escape point once the backslash has been found
Sname strsub Ssrc, icnt+1, -1 ; Create a new string of just the file name
xout Sname ; Send it back to the caller instrument
endop
opcode mincerStack,a,akkikikkip
apointer, klevel, ktranspose, itable, klock, iFFTsize, kStackIntvl, kporttime, iStack, iCount xin
kStackIntvlL portk kStackIntvl, randomi:k(kporttime*0.5,kporttime*2,1,1), i(kStackIntvl)
a1 mincer apointer, klevel, ktranspose* semitone((iCount-1)*kStackIntvlL), itable, klock, iFFTsize, iStack
aMix = 0
if iCount<iStack then
aMix mincerStack apointer, klevel, ktranspose, itable, klock, iFFTsize, kStackIntvl, kporttime, iStack, iCount+1
endif
xout a1 + aMix
endop
instr 1 ; always on
/* PORTAMENTO TIME FUNCTION */
gkporttimeW chnget "portamento"
krampup linseg 0,0.001,1
kporttime = krampup * gkporttimeW
/* SHOW HIDE INTERVAL MODE (SEMITONES OR RATIO) WIDGETS */
kIntervalMode chnget "IntervalMode"
if changed(kIntervalMode)==1 then ; semitones mode
if kIntervalMode==1 then
chnset "visible(0)","RatioPlant_ident"
chnset "visible(1)","SemitonesPlant_ident"
else ; ratio mode
chnset "visible(1)","RatioPlant_ident"
chnset "visible(0)","SemitonesPlant_ident"
endif
endif
/* DEFINE TRANSPOSITION RATIO BASED ON INTERVAL MODE CHOICE */
if kIntervalMode==1 then ; semitones mode
kSemitones chnget "Semitones"
kSemitones portk kSemitones,kporttime
gktranspose = semitone(kSemitones)
else ; ratio mode
kNumerator chnget "Numerator"
kDenominator chnget "Denominator"
gkRatio = kNumerator/kDenominator
gktranspose portk gkRatio,kporttime
endif
gkr1 chnget "r1" ; pointer/note mode select (radio buttons): manual
gkr2 chnget "r2" ; mouse
gkr3 chnget "r3" ; loop
gkmode = (gkr1) + (gkr2*2) + (gkr3*3)
gkloop chnget "loop"
gkMIDI chnget "MIDI"
gklock chnget "lock"
gkfreeze chnget "freeze"
gkfreeze = 1 - gkfreeze
gklevel chnget "level"
gkFFTSize chnget "FFTSize"
gSfilepath chnget "filename"
kNewFileTrg changed gSfilepath ; if a new file is loaded generate a trigger
gkLoopStart chnget "beg" ; Click-and-drag region beginning in sample frames (in sample frames)
gkLoopLen chnget "len" ; Click-and-drag region length in sample frames
;printks "%f\t %f\n",1,gkLoopStart,gkLoopLen
; gkLoopLen limit gkLoopLen,1,gkFileLen
gkLoopMode chnget "LoopMode"
gkSpeed chnget "Speed"
if chnget:k("SpeedMult")==1 then
gkSpeed *= 10
endif
gkModRange chnget "ModRange"
if gkModRange>0 then
gkRate1 chnget "Rate1"
gkRate2 chnget "Rate2"
kMod jspline gkModRange,gkRate1,gkRate2
kSpeed2 = gkSpeed + kMod
gkSpeed = kSpeed2
endif
gkPtrModRange chnget "PtrModRange"
gkPtrRate1 chnget "PtrRate1"
gkPtrRate2 chnget "PtrRate2"
gkStack chnget "Stack"
gkStackIntvl chnget "StackIntvl"
gkMOUSE_DOWN_RIGHT chnget "MOUSE_DOWN_RIGHT" ; Read in mouse right click status
kStartScrub trigger gkMOUSE_DOWN_RIGHT,0.5,0 ; generate a momentary trigger whenver right mouse button is clicked
if gkMOUSE_DOWN_RIGHT==1 && gkmode==2 then
kMOUSE_X chnget "MOUSE_X"
kMOUSE_Y chnget "MOUSE_Y"
if kStartScrub==1 then ; prevent initial portamento when a new note is started using right click
reinit RAMP_FUNC
endif
RAMP_FUNC:
krampup linseg 0,0.001,1
rireturn
kMOUSE_X portk (kMOUSE_X - 5) / 990, kporttime ; Mouse X to pointer position
kMOUSE_Y limit ((kMOUSE_Y - 5) / 150), 0, 1 ; Mouse Y transposition
gapointer interp kMOUSE_X
kSemitones chnget "Semitones"
gktranspose portk ((kMOUSE_Y*2)-1)*kSemitones,kporttime ; Transposition is scaled using transposition value derived either from 'Semitone' slider or 'Ratio' nslideres
gktranspose = semitone(gktranspose)
gklevel portk kMOUSE_Y*gklevel + (1-gklevel), kporttime*krampup
schedkwhen kStartScrub,0,0,2,0,-1
else
kpointer chnget "pointer"
kpointer portk kpointer, kporttime
gapointer interp kpointer
endif
if kNewFileTrg==1 then ; if a new file has been loaded...
event "i",99,0,0 ; call instrument to update sample storage function table
endif
if changed(gkmode+gkMIDI)==1 then
if gkmode==1||gkmode==3&&gkMIDI==0 then
event "i",2,0,-1
endif
endif
endin
instr 99 ; load sound file
gichans filenchnls gSfilepath ; derive the number of channels (mono=1,stereo=2) in the sound file
gitableL ftgen 1,0,0,1,gSfilepath,0,0,1
if gichans==2 then
gitableR ftgen 2,0,0,1,gSfilepath,0,0,2
endif
giReady = 1 ; if no string has yet been loaded giReady will be zero
gkFileLen init ftlen(1)
Smessage sprintfk "file(%s)", gSfilepath ; print sound file image to fileplayer
chnset Smessage, "filer1"
/* WRITE FILE NAME TO GUI */
Sname FileNameFromPath gSfilepath ; Call UDO to extract file name from the full path
Smessage sprintfk "text(%s)",Sname
chnset Smessage, "stringbox"
endin
instr 2 ; non-midi
if gkmode!=1 && gkmode!=3 && gkMOUSE_DOWN_RIGHT!=1 || gkMIDI==1 then
turnoff
endif
if giReady = 1 then ; i.e. if a file has been loaded
aenv linsegr 0,0.01,1,0.01,0 ; simple de-click envelope
iFileLen filelen gSfilepath
if i(gkmode)==3 then
if gkLoopMode==1 then ; forward
apointer phasor (sr*gkSpeed)/gkLoopLen
elseif gkLoopMode==2 then ; backward
apointer phasor -(sr*gkSpeed)/gkLoopLen
elseif gkLoopMode==3 then ; tri
apointer poscil 1,(sr*gkSpeed)/gkLoopLen,giTriangle
elseif gkLoopMode==4 then ; sine
apointer poscil 1,(sr*gkSpeed)/gkLoopLen,giRectSine
endif
apointer = (apointer * (gkLoopLen/sr)) + (gkLoopStart/sr)
else
apointer = gapointer*iFileLen
endif
/* RANDOM POINTER MODULATION */
if gkPtrModRange>0 then
kRndPtrRate init random(i(gkPtrRate1),i(gkPtrRate2))
kRndPtrTrig metro kRndPtrRate
kRndPtrRate trandom kRndPtrTrig,gkPtrRate1,gkPtrRate2
kRndPtrPos trandom kRndPtrTrig,-gkPtrModRange*iFileLen,gkPtrModRange*iFileLen
apointer += interp(kRndPtrPos)
endif
ktrig changed gkFFTSize
if ktrig==1 then
reinit RESTART
endif
RESTART:
if gichans=1 then
if gkStack==1 then
a1 mincer apointer, gklevel, gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1]
else
if changed:k(gkStack)==1 then
reinit RESTART_STACK1
endif
RESTART_STACK1:
a1 mincerStack apointer, gklevel, gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
endif
outs a1 * aenv, a1 * aenv
elseif gichans=2 then
if gkStack==1 then
a1 mincer apointer, gklevel, gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1]
a2 mincer apointer, gklevel, gktranspose, gitableR, gklock, giFFTSizes[i(gkFFTSize)-1]
else
if changed:k(gkStack)==1 then
reinit RESTART_STACK1
endif
RESTART_STACK1:
a1 mincerStack apointer, gklevel, gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
a2 mincerStack apointer, gklevel, gktranspose, gitableR, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
endif
outs a1 * aenv, a2 * aenv
endif
endif
endin
instr 3 ; midi triggered instrument
if giReady==1 then ; i.e. if a file has been loaded
icps cpsmidi ; read in midi note data as cycles per second
iamp ampmidi 1 ; read in midi velocity (as a value within the range 0 - 1)
iMidiRef chnget "MidiRef" ; MIDI unison reference note
iFrqRatio = icps/cpsmidinn(iMidiRef) ; derive playback speed from note played in relation to a reference note (MIDI note 60 / middle C)
iAttTim chnget "AttTim" ; read in amplitude envelope attack time widget
iRelTim chnget "RelTim" ; read in amplitude envelope attack time widget
if iAttTim>0 then ;
kenv linsegr 0, iAttTim, 1, iRelTim, 0
else
kenv linsegr 1, iRelTim, 0 ; attack time is zero so ignore this segment of the envelope (a segment of duration zero is not permitted
endif
kenv expcurve kenv,8 ; remap amplitude value with a more natural curve
aenv interp kenv ; interpolate and create a-rate envelope
iFileLen filelen gSfilepath
if i(gkmode)==3 then
if gkLoopMode==1 then
apointer phasor (sr*gkSpeed)/gkLoopLen
elseif gkLoopMode==2 then
apointer phasor -(sr*gkSpeed)/gkLoopLen
elseif gkLoopMode==3 then
apointer poscil 1,(sr*gkSpeed*0.5)/gkLoopLen,giTriangle
elseif gkLoopMode==4 then
apointer poscil 1,(sr*gkSpeed*0.5)/gkLoopLen,giRectSine
endif
apointer = (apointer * (gkLoopLen/sr)) + (gkLoopStart/sr)
else
apointer = gapointer*iFileLen
endif
/* RANDOM POINTER MODULATION */
if gkPtrModRange>0 then
kRndPtrRate init random(i(gkPtrRate1),i(gkPtrRate2))
kRndPtrTrig metro kRndPtrRate
kRndPtrRate trandom kRndPtrTrig,gkPtrRate1,gkPtrRate2
kRndPtrPos trandom kRndPtrTrig,-gkPtrModRange*iFileLen,gkPtrModRange*iFileLen
apointer += interp(kRndPtrPos)
endif
ktrig changed gkFFTSize
if ktrig==1 then
reinit RESTART
endif
RESTART:
if gichans=1 then
if gkStack==1 then
a1 mincer apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1]
else
if changed:k(gkStack)==1 then
reinit RESTART_STACK1
endif
RESTART_STACK1:
a1 mincerStack apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
endif
outs a1 * aenv, a1 * aenv
elseif gichans=2 then
if gkStack==1 then
a1 mincer apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1]
a2 mincer apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableR, gklock, giFFTSizes[i(gkFFTSize)-1]
else
if changed:k(gkStack)==1 then
reinit RESTART_STACK1
endif
RESTART_STACK1:
a1 mincerStack apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableL, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
a1 mincerStack apointer, gklevel*iamp, iFrqRatio*gktranspose, gitableR, gklock, giFFTSizes[i(gkFFTSize)-1], gkStackIntvl, gkporttimeW, i(gkStack)
endif
outs a1 * aenv, a2 * aenv
endif
endif
endin
</CsInstruments>
<CsScore>
i 1 0 [60*60*24*7]
</CsScore>
</CsoundSynthesizer> | 412 | 0.881296 | 1 | 0.881296 | game-dev | MEDIA | 0.310312 | game-dev | 0.821909 | 1 | 0.821909 |
ssquadteam/ApiaryProxy | 7,047 | proxy/src/main/java/com/velocitypowered/proxy/util/ComponentUtils.java | /*
* Copyright (C) 2018-2024 Velocity Contributors
*
* 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/>.
*/
package com.velocitypowered.proxy.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.jetbrains.annotations.NotNull;
/**
* Serialize a component to a string.
*
* @author Elmar Blume
*/
public final class ComponentUtils {
// MiniMessage default: <#FFFFFF>
private static final Pattern BOXED_HEX_PATTERN = Pattern.compile("<#([A-Fa-f0-9]){6}>"); // <#FFFFFF>
private static final Pattern BOXED_MOJANG_PATTERN = Pattern.compile("<&#([A-Fa-f0-9]){6}>"); // <&#FFFFFF>
private static final Pattern UNBOXED_HEX_PATTERN = Pattern.compile("#([A-Fa-f0-9]){6}"); // #FFFFFF
private static final Pattern UNBOXED_MOJANG_PATTERN = Pattern.compile("&#([A-Fa-f0-9]){6}"); // &#FFFFFF
private static final List<Pattern> ODD_HEX_PATTERNS = Arrays.asList(
BOXED_MOJANG_PATTERN, // <&#FFFFFF>
BOXED_HEX_PATTERN, // <#FFFFFF>
UNBOXED_MOJANG_PATTERN, // &#FFFFFF
UNBOXED_HEX_PATTERN // #FFFFFF
); // <!> order matters
private static final List<Pattern> UNBOXED_PATTERNS = Arrays.asList(
UNBOXED_HEX_PATTERN,
UNBOXED_MOJANG_PATTERN
);
private static final List<Pattern> MOJANG_PATTERNS = Arrays.asList(
BOXED_MOJANG_PATTERN,
UNBOXED_MOJANG_PATTERN
);
private static final MiniMessage MINI = MiniMessage.builder()
.strict(false)
.build();
private static final Map<String, String> COLOR_MAP = new HashMap<>();
static {
COLOR_MAP.put("§", "&");
COLOR_MAP.put("&0", "<reset><black>");
COLOR_MAP.put("&1", "<reset><dark_blue>");
COLOR_MAP.put("&2", "<reset><dark_green>");
COLOR_MAP.put("&3", "<reset><dark_aqua>");
COLOR_MAP.put("&4", "<reset><dark_red>");
COLOR_MAP.put("&5", "<reset><dark_purple>");
COLOR_MAP.put("&6", "<reset><gold>");
COLOR_MAP.put("&7", "<reset><gray>");
COLOR_MAP.put("&8", "<reset><dark_gray>");
COLOR_MAP.put("&9", "<reset><blue>");
COLOR_MAP.put("&a", "<reset><green>");
COLOR_MAP.put("&b", "<reset><aqua>");
COLOR_MAP.put("&c", "<reset><red>");
COLOR_MAP.put("&d", "<reset><light_purple>");
COLOR_MAP.put("&e", "<reset><yellow>");
COLOR_MAP.put("&f", "<reset><white>");
COLOR_MAP.put("&k", "<obfuscated>");
COLOR_MAP.put("&l", "<bold>");
COLOR_MAP.put("&m", "<strikethrough>");
COLOR_MAP.put("&n", "<underlined>");
COLOR_MAP.put("&o", "<italic>");
COLOR_MAP.put("&r", "<reset>");
COLOR_MAP.put("\\n", "<newline>");
}
private ComponentUtils() {
throw new AssertionError("Instances of this class should not be created.");
}
/**
* Serialize a component to a string.
*
* @param component the component to serialize
* @return the serialized component
*/
public static @NotNull String serializeComponent(final Component component) {
return MINI.serialize(component);
}
/**
* Parses a string to a component.
*
* @param input the string to parse
* @return the parsed component
*/
public static @NotNull Component parseComponent(final String input) {
return MINI.deserialize(colorifyLegacy(input));
}
/**
* Colorify component parsing hex patterns.
*
* @param input the string to colorify into a component
* @return the colorized component
*/
public static @NotNull Component colorify(final String input) {
if (input == null) {
return Component.empty();
}
String parsedStr = input;
// Parse the hex patterns
for (final Pattern pattern : ODD_HEX_PATTERNS) {
parsedStr = colorMatcher(parsedStr, pattern, UNBOXED_PATTERNS.contains(pattern));
}
return parseComponent(parsedStr.replace("D#DONE", "#"));
}
/**
* Colorify legacy parsing legacy color codes.
*
* @param input the string to colorify into a component
* @return the colorized component
*/
public static String colorifyLegacy(final String input) {
String parsedStr = input;
for (Map.Entry<String, String> entry : COLOR_MAP.entrySet()) {
parsedStr = parsedStr.replace(entry.getKey(), entry.getValue());
}
return parsedStr;
}
/**
* Strips matching hex patterns from a string.
*
* @param input the input
* @return the string
*/
public static String stripHex(String input) {
for (Pattern pattern : ODD_HEX_PATTERNS) {
input = pattern.matcher(input).replaceAll("");
}
return input;
}
private static @NotNull String colorMatcher(@NotNull String literal, @NotNull final Pattern pattern, final boolean unboxed) {
final Matcher matcher = pattern.matcher(literal);
while (matcher.find()) {
final String matched = matcher.group();
boolean requiresBoxing = false;
if (unboxed) {
final int literalIndex = literal.indexOf(matched);
final int afterLiteralIndex = literalIndex + matched.length();
if (literal.length() >= afterLiteralIndex) {
final char charAt = literal.charAt(afterLiteralIndex);
if (charAt != ':' && charAt != '>') {
requiresBoxing = true;
}
}
}
final int index = matched.indexOf("#");
final String hexCode = matched.substring(index + 1, index + 7);
if (!requiresBoxing) {
final String start;
final String end = matched.substring(index + 7);
if (MOJANG_PATTERNS.contains(pattern)) {
start = matched.substring(0, index).replace("&", "");
} else {
start = matched.substring(0, index);
}
literal = literal.replace(matched, start + "D#DONE" + hexCode + end);
} else {
literal = literal.replace(matched, "<D#DONE" + hexCode + ">");
}
}
return literal;
}
/**
* Normalize any hex pattern to a standard hex pattern.
*
* @param hex the hex pattern to normalize
* @return the normalized hex pattern
*/
private static @NotNull String normalizeHex(@NotNull final String hex) {
if (hex.startsWith("<") || hex.startsWith("{")) {
return hex.substring(1, hex.length() - 1);
} else if (hex.startsWith("&")) {
return hex.substring(1);
} else {
return hex;
}
}
}
| 412 | 0.798903 | 1 | 0.798903 | game-dev | MEDIA | 0.504588 | game-dev,graphics-rendering | 0.922804 | 1 | 0.922804 |
cryfs/cryfs | 6,560 | test/cpp-utils/pointer/cast_test.cpp | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "cpp-utils/pointer/cast.h"
#include "cpp-utils/pointer/unique_ref.h"
#include "cpp-utils/pointer/unique_ref_boost_optional_gtest_workaround.h"
//TODO There is a lot of duplication here, because each test case is there twice - once for unique_ptr, once for unique_ref. Remove redundancy by using generic test cases.
//TODO Then also move the unique_ref related test cases there - cast_test.cpp should only contain the unique_ptr related ones.
using namespace cpputils;
using std::unique_ptr;
using std::make_unique;
using boost::optional;
using boost::none;
class DestructorCallback {
public:
MOCK_METHOD(void, call, (), (const));
};
class Parent {
public:
virtual ~Parent() { }
};
class Child : public Parent {
public:
Child(const DestructorCallback *childDestructorCallback) : _destructorCallback(childDestructorCallback) { }
Child(): Child(nullptr) {}
~Child() override {
if (_destructorCallback != nullptr) {
_destructorCallback->call();
}
}
private:
const DestructorCallback *_destructorCallback;
DISALLOW_COPY_AND_ASSIGN(Child);
};
class Child2 : public Parent {};
TEST(UniquePtr_DynamicPointerMoveTest, NullPtrParentToChildCast) {
unique_ptr<Parent> source(nullptr);
const unique_ptr<Child> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(nullptr, source.get());
EXPECT_EQ(nullptr, casted.get());
}
TEST(UniquePtr_DynamicPointerMoveTest, NullPtrChildToParentCast) {
unique_ptr<Child> source(nullptr);
const unique_ptr<Parent> casted = dynamic_pointer_move<Parent>(source);
EXPECT_EQ(nullptr, source.get());
EXPECT_EQ(nullptr, casted.get());
}
TEST(UniquePtr_DynamicPointerMoveTest, NullPtrSelfCast) {
unique_ptr<Parent> source(nullptr);
const unique_ptr<Parent> casted = dynamic_pointer_move<Parent>(source);
EXPECT_EQ(nullptr, source.get());
EXPECT_EQ(nullptr, casted.get());
}
TEST(UniqueRef_DynamicPointerMoveTest, ValidParentToChildCast) {
Child *obj = new Child();
unique_ref<Parent> source(nullcheck(unique_ptr<Parent>(obj)).value());
const unique_ref<Child> casted = dynamic_pointer_move<Child>(source).value();
EXPECT_FALSE(source.is_valid()); // source lost ownership
EXPECT_EQ(obj, casted.get());
}
TEST(UniquePtr_DynamicPointerMoveTest, ValidParentToChildCast) {
Child *obj = new Child();
unique_ptr<Parent> source(obj);
const unique_ptr<Child> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(nullptr, source.get()); // source lost ownership
EXPECT_EQ(obj, casted.get());
}
TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast1) {
Parent *obj = new Parent();
unique_ref<Parent> source(nullcheck(unique_ptr<Parent>(obj)).value());
const optional<unique_ref<Child>> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(obj, source.get()); // source still has ownership
EXPECT_EQ(none, casted);
}
TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast1) {
Parent *obj = new Parent();
unique_ptr<Parent> source(obj);
const unique_ptr<Child> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(obj, source.get()); // source still has ownership
EXPECT_EQ(nullptr, casted.get());
}
TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast2) {
Child2 *obj = new Child2();
unique_ref<Parent> source(nullcheck(unique_ptr<Parent>(obj)).value());
const optional<unique_ref<Child>> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(obj, source.get()); // source still has ownership
EXPECT_EQ(none, casted);
}
TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast2) {
Child2 *obj = new Child2();
unique_ptr<Parent> source(obj);
const unique_ptr<Child> casted = dynamic_pointer_move<Child>(source);
EXPECT_EQ(obj, source.get()); // source still has ownership
EXPECT_EQ(nullptr, casted.get());
}
TEST(UniqueRef_DynamicPointerMoveTest, ChildToParentCast) {
Child *obj = new Child();
unique_ref<Child> source(nullcheck(unique_ptr<Child>(obj)).value());
const unique_ref<Parent> casted = dynamic_pointer_move<Parent>(source).value();
EXPECT_FALSE(source.is_valid()); // source lost ownership
EXPECT_EQ(obj, casted.get());
}
TEST(UniquePtr_DynamicPointerMoveTest, ChildToParentCast) {
Child *obj = new Child();
unique_ptr<Child> source(obj);
const unique_ptr<Parent> casted = dynamic_pointer_move<Parent>(source);
EXPECT_EQ(nullptr, source.get()); // source lost ownership
EXPECT_EQ(obj, casted.get());
}
class UniqueRef_DynamicPointerMoveDestructorTest: public ::testing::Test {
public:
UniqueRef_DynamicPointerMoveDestructorTest(): childDestructorCallback() {}
DestructorCallback childDestructorCallback;
unique_ref<Child> createChild() {
return make_unique_ref<Child>(&childDestructorCallback);
}
void EXPECT_CHILD_DESTRUCTOR_CALLED() {
EXPECT_CALL(childDestructorCallback, call()).Times(1);
}
};
class UniquePtr_DynamicPointerMoveDestructorTest: public ::testing::Test {
public:
UniquePtr_DynamicPointerMoveDestructorTest(): childDestructorCallback() {}
DestructorCallback childDestructorCallback;
unique_ptr<Child> createChild() {
return make_unique<Child>(&childDestructorCallback);
}
void EXPECT_CHILD_DESTRUCTOR_CALLED() {
EXPECT_CALL(childDestructorCallback, call()).Times(1);
}
};
TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ChildInParentPtr) {
const unique_ref<Parent> parent = createChild();
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ChildInParentPtr) {
const unique_ptr<Parent> parent = createChild();
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ChildToParentCast) {
unique_ref<Child> child = createChild();
const unique_ref<Parent> parent = dynamic_pointer_move<Parent>(child).value();
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ChildToParentCast) {
unique_ptr<Child> child = createChild();
const unique_ptr<Parent> parent = dynamic_pointer_move<Parent>(child);
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ParentToChildCast) {
unique_ref<Parent> parent = createChild();
const unique_ref<Child> child = dynamic_pointer_move<Child>(parent).value();
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ParentToChildCast) {
unique_ptr<Parent> parent = createChild();
const unique_ptr<Child> child = dynamic_pointer_move<Child>(parent);
EXPECT_CHILD_DESTRUCTOR_CALLED();
}
| 412 | 0.937158 | 1 | 0.937158 | game-dev | MEDIA | 0.723011 | game-dev,testing-qa | 0.834304 | 1 | 0.834304 |
harfang3d/harfang3d | 21,939 | extern/bullet3/BulletDynamics/Dynamics/btRigidBody.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_RIGIDBODY_H
#define BT_RIGIDBODY_H
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btTransform.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
class btCollisionShape;
class btMotionState;
class btTypedConstraint;
extern btScalar gDeactivationTime;
extern bool gDisableDeactivation;
#ifdef BT_USE_DOUBLE_PRECISION
#define btRigidBodyData btRigidBodyDoubleData
#define btRigidBodyDataName "btRigidBodyDoubleData"
#else
#define btRigidBodyData btRigidBodyFloatData
#define btRigidBodyDataName "btRigidBodyFloatData"
#endif //BT_USE_DOUBLE_PRECISION
enum btRigidBodyFlags
{
BT_DISABLE_WORLD_GRAVITY = 1,
///BT_ENABLE_GYROPSCOPIC_FORCE flags is enabled by default in Bullet 2.83 and onwards.
///and it BT_ENABLE_GYROPSCOPIC_FORCE becomes equivalent to BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY
///See Demos/GyroscopicDemo and computeGyroscopicImpulseImplicit
BT_ENABLE_GYROSCOPIC_FORCE_EXPLICIT = 2,
BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_WORLD = 4,
BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY = 8,
BT_ENABLE_GYROPSCOPIC_FORCE = BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY,
};
///The btRigidBody is the main class for rigid body objects. It is derived from btCollisionObject, so it keeps a pointer to a btCollisionShape.
///It is recommended for performance and memory use to share btCollisionShape objects whenever possible.
///There are 3 types of rigid bodies:
///- A) Dynamic rigid bodies, with positive mass. Motion is controlled by rigid body dynamics.
///- B) Fixed objects with zero mass. They are not moving (basically collision objects)
///- C) Kinematic objects, which are objects without mass, but the user can move them. There is one-way interaction, and Bullet calculates a velocity based on the timestep and previous and current world transform.
///Bullet automatically deactivates dynamic rigid bodies, when the velocity is below a threshold for a given time.
///Deactivated (sleeping) rigid bodies don't take any processing time, except a minor broadphase collision detection impact (to allow active objects to activate/wake up sleeping objects)
class btRigidBody : public btCollisionObject
{
btMatrix3x3 m_invInertiaTensorWorld;
btVector3 m_linearVelocity;
btVector3 m_angularVelocity;
btScalar m_inverseMass;
btVector3 m_linearFactor;
btVector3 m_gravity;
btVector3 m_gravity_acceleration;
btVector3 m_invInertiaLocal;
btVector3 m_totalForce;
btVector3 m_totalTorque;
btScalar m_linearDamping;
btScalar m_angularDamping;
bool m_additionalDamping;
btScalar m_additionalDampingFactor;
btScalar m_additionalLinearDampingThresholdSqr;
btScalar m_additionalAngularDampingThresholdSqr;
btScalar m_additionalAngularDampingFactor;
btScalar m_linearSleepingThreshold;
btScalar m_angularSleepingThreshold;
//m_optionalMotionState allows to automatic synchronize the world transform for active objects
btMotionState* m_optionalMotionState;
//keep track of typed constraints referencing this rigid body, to disable collision between linked bodies
btAlignedObjectArray<btTypedConstraint*> m_constraintRefs;
int m_rigidbodyFlags;
int m_debugBodyId;
protected:
ATTRIBUTE_ALIGNED16(btVector3 m_deltaLinearVelocity);
btVector3 m_deltaAngularVelocity;
btVector3 m_angularFactor;
btVector3 m_invMass;
btVector3 m_pushVelocity;
btVector3 m_turnVelocity;
public:
///The btRigidBodyConstructionInfo structure provides information to create a rigid body. Setting mass to zero creates a fixed (non-dynamic) rigid body.
///For dynamic objects, you can use the collision shape to approximate the local inertia tensor, otherwise use the zero vector (default argument)
///You can use the motion state to synchronize the world transform between physics and graphics objects.
///And if the motion state is provided, the rigid body will initialize its initial world transform from the motion state,
///m_startWorldTransform is only used when you don't provide a motion state.
struct btRigidBodyConstructionInfo
{
btScalar m_mass;
///When a motionState is provided, the rigid body will initialize its world transform from the motion state
///In this case, m_startWorldTransform is ignored.
btMotionState* m_motionState;
btTransform m_startWorldTransform;
btCollisionShape* m_collisionShape;
btVector3 m_localInertia;
btScalar m_linearDamping;
btScalar m_angularDamping;
///best simulation results when friction is non-zero
btScalar m_friction;
///the m_rollingFriction prevents rounded shapes, such as spheres, cylinders and capsules from rolling forever.
///See Bullet/Demos/RollingFrictionDemo for usage
btScalar m_rollingFriction;
btScalar m_spinningFriction; //torsional friction around contact normal
///best simulation results using zero restitution.
btScalar m_restitution;
btScalar m_linearSleepingThreshold;
btScalar m_angularSleepingThreshold;
//Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
//Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
bool m_additionalDamping;
btScalar m_additionalDampingFactor;
btScalar m_additionalLinearDampingThresholdSqr;
btScalar m_additionalAngularDampingThresholdSqr;
btScalar m_additionalAngularDampingFactor;
btRigidBodyConstructionInfo(btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia = btVector3(0, 0, 0)) : m_mass(mass),
m_motionState(motionState),
m_collisionShape(collisionShape),
m_localInertia(localInertia),
m_linearDamping(btScalar(0.)),
m_angularDamping(btScalar(0.)),
m_friction(btScalar(0.5)),
m_rollingFriction(btScalar(0)),
m_spinningFriction(btScalar(0)),
m_restitution(btScalar(0.)),
m_linearSleepingThreshold(btScalar(0.8)),
m_angularSleepingThreshold(btScalar(1.f)),
m_additionalDamping(false),
m_additionalDampingFactor(btScalar(0.005)),
m_additionalLinearDampingThresholdSqr(btScalar(0.01)),
m_additionalAngularDampingThresholdSqr(btScalar(0.01)),
m_additionalAngularDampingFactor(btScalar(0.01))
{
m_startWorldTransform.setIdentity();
}
};
///btRigidBody constructor using construction info
btRigidBody(const btRigidBodyConstructionInfo& constructionInfo);
///btRigidBody constructor for backwards compatibility.
///To specify friction (etc) during rigid body construction, please use the other constructor (using btRigidBodyConstructionInfo)
btRigidBody(btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia = btVector3(0, 0, 0));
virtual ~btRigidBody()
{
//No constraints should point to this rigidbody
//Remove constraints from the dynamics world before you delete the related rigidbodies.
btAssert(m_constraintRefs.size() == 0);
}
protected:
///setupRigidBody is only used internally by the constructor
void setupRigidBody(const btRigidBodyConstructionInfo& constructionInfo);
public:
void proceedToTransform(const btTransform& newTrans);
///to keep collision detection and dynamics separate we don't store a rigidbody pointer
///but a rigidbody is derived from btCollisionObject, so we can safely perform an upcast
static const btRigidBody* upcast(const btCollisionObject* colObj)
{
if (colObj->getInternalType() & btCollisionObject::CO_RIGID_BODY)
return (const btRigidBody*)colObj;
return 0;
}
static btRigidBody* upcast(btCollisionObject* colObj)
{
if (colObj->getInternalType() & btCollisionObject::CO_RIGID_BODY)
return (btRigidBody*)colObj;
return 0;
}
/// continuous collision detection needs prediction
void predictIntegratedTransform(btScalar step, btTransform& predictedTransform);
void saveKinematicState(btScalar step);
void applyGravity();
void clearGravity();
void setGravity(const btVector3& acceleration);
const btVector3& getGravity() const
{
return m_gravity_acceleration;
}
void setDamping(btScalar lin_damping, btScalar ang_damping);
btScalar getLinearDamping() const
{
return m_linearDamping;
}
btScalar getAngularDamping() const
{
return m_angularDamping;
}
btScalar getLinearSleepingThreshold() const
{
return m_linearSleepingThreshold;
}
btScalar getAngularSleepingThreshold() const
{
return m_angularSleepingThreshold;
}
void applyDamping(btScalar timeStep);
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const
{
return m_collisionShape;
}
SIMD_FORCE_INLINE btCollisionShape* getCollisionShape()
{
return m_collisionShape;
}
void setMassProps(btScalar mass, const btVector3& inertia);
const btVector3& getLinearFactor() const
{
return m_linearFactor;
}
void setLinearFactor(const btVector3& linearFactor)
{
m_linearFactor = linearFactor;
m_invMass = m_linearFactor * m_inverseMass;
}
btScalar getInvMass() const { return m_inverseMass; }
btScalar getMass() const { return m_inverseMass == btScalar(0.) ? btScalar(0.) : btScalar(1.0) / m_inverseMass; }
const btMatrix3x3& getInvInertiaTensorWorld() const
{
return m_invInertiaTensorWorld;
}
void integrateVelocities(btScalar step);
void setCenterOfMassTransform(const btTransform& xform);
void applyCentralForce(const btVector3& force)
{
m_totalForce += force * m_linearFactor;
}
const btVector3& getTotalForce() const
{
return m_totalForce;
};
const btVector3& getTotalTorque() const
{
return m_totalTorque;
};
const btVector3& getInvInertiaDiagLocal() const
{
return m_invInertiaLocal;
};
void setInvInertiaDiagLocal(const btVector3& diagInvInertia)
{
m_invInertiaLocal = diagInvInertia;
}
void setSleepingThresholds(btScalar linear, btScalar angular)
{
m_linearSleepingThreshold = linear;
m_angularSleepingThreshold = angular;
}
void applyTorque(const btVector3& torque)
{
m_totalTorque += torque * m_angularFactor;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_totalTorque);
#endif
}
void applyForce(const btVector3& force, const btVector3& rel_pos)
{
applyCentralForce(force);
applyTorque(rel_pos.cross(force * m_linearFactor));
}
void applyCentralImpulse(const btVector3& impulse)
{
m_linearVelocity += impulse * m_linearFactor * m_inverseMass;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_linearVelocity);
#endif
}
void applyTorqueImpulse(const btVector3& torque)
{
m_angularVelocity += m_invInertiaTensorWorld * torque * m_angularFactor;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_angularVelocity);
#endif
}
void applyImpulse(const btVector3& impulse, const btVector3& rel_pos)
{
if (m_inverseMass != btScalar(0.))
{
applyCentralImpulse(impulse);
if (m_angularFactor)
{
applyTorqueImpulse(rel_pos.cross(impulse * m_linearFactor));
}
}
}
void applyPushImpulse(const btVector3& impulse, const btVector3& rel_pos)
{
if (m_inverseMass != btScalar(0.))
{
applyCentralPushImpulse(impulse);
if (m_angularFactor)
{
applyTorqueTurnImpulse(rel_pos.cross(impulse * m_linearFactor));
}
}
}
btVector3 getPushVelocity() const
{
return m_pushVelocity;
}
btVector3 getTurnVelocity() const
{
return m_turnVelocity;
}
void setPushVelocity(const btVector3& v)
{
m_pushVelocity = v;
}
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
void clampVelocity(btVector3& v) const {
v.setX(
fmax(-BT_CLAMP_VELOCITY_TO,
fmin(BT_CLAMP_VELOCITY_TO, v.getX()))
);
v.setY(
fmax(-BT_CLAMP_VELOCITY_TO,
fmin(BT_CLAMP_VELOCITY_TO, v.getY()))
);
v.setZ(
fmax(-BT_CLAMP_VELOCITY_TO,
fmin(BT_CLAMP_VELOCITY_TO, v.getZ()))
);
}
#endif
void setTurnVelocity(const btVector3& v)
{
m_turnVelocity = v;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_turnVelocity);
#endif
}
void applyCentralPushImpulse(const btVector3& impulse)
{
m_pushVelocity += impulse * m_linearFactor * m_inverseMass;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_pushVelocity);
#endif
}
void applyTorqueTurnImpulse(const btVector3& torque)
{
m_turnVelocity += m_invInertiaTensorWorld * torque * m_angularFactor;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_turnVelocity);
#endif
}
void clearForces()
{
m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
}
void updateInertiaTensor();
const btVector3& getCenterOfMassPosition() const
{
return m_worldTransform.getOrigin();
}
btQuaternion getOrientation() const;
const btTransform& getCenterOfMassTransform() const
{
return m_worldTransform;
}
const btVector3& getLinearVelocity() const
{
return m_linearVelocity;
}
const btVector3& getAngularVelocity() const
{
return m_angularVelocity;
}
inline void setLinearVelocity(const btVector3& lin_vel)
{
m_updateRevision++;
m_linearVelocity = lin_vel;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_linearVelocity);
#endif
}
inline void setAngularVelocity(const btVector3& ang_vel)
{
m_updateRevision++;
m_angularVelocity = ang_vel;
#if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
clampVelocity(m_angularVelocity);
#endif
}
btVector3 getVelocityInLocalPoint(const btVector3& rel_pos) const
{
//we also calculate lin/ang velocity for kinematic objects
return m_linearVelocity + m_angularVelocity.cross(rel_pos);
//for kinematic objects, we could also use use:
// return (m_worldTransform(rel_pos) - m_interpolationWorldTransform(rel_pos)) / m_kinematicTimeStep;
}
btVector3 getPushVelocityInLocalPoint(const btVector3& rel_pos) const
{
//we also calculate lin/ang velocity for kinematic objects
return m_pushVelocity + m_turnVelocity.cross(rel_pos);
}
void translate(const btVector3& v)
{
m_worldTransform.getOrigin() += v;
}
void getAabb(btVector3& aabbMin, btVector3& aabbMax) const;
SIMD_FORCE_INLINE btScalar computeImpulseDenominator(const btVector3& pos, const btVector3& normal) const
{
btVector3 r0 = pos - getCenterOfMassPosition();
btVector3 c0 = (r0).cross(normal);
btVector3 vec = (c0 * getInvInertiaTensorWorld()).cross(r0);
return m_inverseMass + normal.dot(vec);
}
SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis) const
{
btVector3 vec = axis * getInvInertiaTensorWorld();
return axis.dot(vec);
}
SIMD_FORCE_INLINE void updateDeactivation(btScalar timeStep)
{
if ((getActivationState() == ISLAND_SLEEPING) || (getActivationState() == DISABLE_DEACTIVATION))
return;
if ((getLinearVelocity().length2() < m_linearSleepingThreshold * m_linearSleepingThreshold) &&
(getAngularVelocity().length2() < m_angularSleepingThreshold * m_angularSleepingThreshold))
{
m_deactivationTime += timeStep;
}
else
{
m_deactivationTime = btScalar(0.);
setActivationState(0);
}
}
SIMD_FORCE_INLINE bool wantsSleeping()
{
if (getActivationState() == DISABLE_DEACTIVATION)
return false;
//disable deactivation
if (gDisableDeactivation || (gDeactivationTime == btScalar(0.)))
return false;
if ((getActivationState() == ISLAND_SLEEPING) || (getActivationState() == WANTS_DEACTIVATION))
return true;
if (m_deactivationTime > gDeactivationTime)
{
return true;
}
return false;
}
const btBroadphaseProxy* getBroadphaseProxy() const
{
return m_broadphaseHandle;
}
btBroadphaseProxy* getBroadphaseProxy()
{
return m_broadphaseHandle;
}
void setNewBroadphaseProxy(btBroadphaseProxy* broadphaseProxy)
{
m_broadphaseHandle = broadphaseProxy;
}
//btMotionState allows to automatic synchronize the world transform for active objects
btMotionState* getMotionState()
{
return m_optionalMotionState;
}
const btMotionState* getMotionState() const
{
return m_optionalMotionState;
}
void setMotionState(btMotionState* motionState)
{
m_optionalMotionState = motionState;
if (m_optionalMotionState)
motionState->getWorldTransform(m_worldTransform);
}
//for experimental overriding of friction/contact solver func
int m_contactSolverType;
int m_frictionSolverType;
void setAngularFactor(const btVector3& angFac)
{
m_updateRevision++;
m_angularFactor = angFac;
}
void setAngularFactor(btScalar angFac)
{
m_updateRevision++;
m_angularFactor.setValue(angFac, angFac, angFac);
}
const btVector3& getAngularFactor() const
{
return m_angularFactor;
}
//is this rigidbody added to a btCollisionWorld/btDynamicsWorld/btBroadphase?
bool isInWorld() const
{
return (getBroadphaseProxy() != 0);
}
void addConstraintRef(btTypedConstraint* c);
void removeConstraintRef(btTypedConstraint* c);
btTypedConstraint* getConstraintRef(int index)
{
return m_constraintRefs[index];
}
int getNumConstraintRefs() const
{
return m_constraintRefs.size();
}
void setFlags(int flags)
{
m_rigidbodyFlags = flags;
}
int getFlags() const
{
return m_rigidbodyFlags;
}
///perform implicit force computation in world space
btVector3 computeGyroscopicImpulseImplicit_World(btScalar dt) const;
///perform implicit force computation in body space (inertial frame)
btVector3 computeGyroscopicImpulseImplicit_Body(btScalar step) const;
///explicit version is best avoided, it gains energy
btVector3 computeGyroscopicForceExplicit(btScalar maxGyroscopicForce) const;
btVector3 getLocalInertia() const;
///////////////////////////////////////////////
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
virtual void serializeSingleObject(class btSerializer* serializer) const;
};
//@todo add m_optionalMotionState and m_constraintRefs to btRigidBodyData
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btRigidBodyFloatData
{
btCollisionObjectFloatData m_collisionObjectData;
btMatrix3x3FloatData m_invInertiaTensorWorld;
btVector3FloatData m_linearVelocity;
btVector3FloatData m_angularVelocity;
btVector3FloatData m_angularFactor;
btVector3FloatData m_linearFactor;
btVector3FloatData m_gravity;
btVector3FloatData m_gravity_acceleration;
btVector3FloatData m_invInertiaLocal;
btVector3FloatData m_totalForce;
btVector3FloatData m_totalTorque;
float m_inverseMass;
float m_linearDamping;
float m_angularDamping;
float m_additionalDampingFactor;
float m_additionalLinearDampingThresholdSqr;
float m_additionalAngularDampingThresholdSqr;
float m_additionalAngularDampingFactor;
float m_linearSleepingThreshold;
float m_angularSleepingThreshold;
int m_additionalDamping;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btRigidBodyDoubleData
{
btCollisionObjectDoubleData m_collisionObjectData;
btMatrix3x3DoubleData m_invInertiaTensorWorld;
btVector3DoubleData m_linearVelocity;
btVector3DoubleData m_angularVelocity;
btVector3DoubleData m_angularFactor;
btVector3DoubleData m_linearFactor;
btVector3DoubleData m_gravity;
btVector3DoubleData m_gravity_acceleration;
btVector3DoubleData m_invInertiaLocal;
btVector3DoubleData m_totalForce;
btVector3DoubleData m_totalTorque;
double m_inverseMass;
double m_linearDamping;
double m_angularDamping;
double m_additionalDampingFactor;
double m_additionalLinearDampingThresholdSqr;
double m_additionalAngularDampingThresholdSqr;
double m_additionalAngularDampingFactor;
double m_linearSleepingThreshold;
double m_angularSleepingThreshold;
int m_additionalDamping;
char m_padding[4];
};
#endif //BT_RIGIDBODY_H
| 412 | 0.925744 | 1 | 0.925744 | game-dev | MEDIA | 0.999078 | game-dev | 0.907896 | 1 | 0.907896 |
Durss/Twitchat | 7,440 | src_front/components/params/contents/triggers/entries/TriggerActionGoXLREntry.vue | <template>
<div class="triggeractiongoxlrentry triggerActionForm">
<ParamItem :paramData="param_action" v-model="action.action" />
<ParamItem :paramData="param_fxPreset" v-model="action.fxPresetIndex" v-if="param_action.value == 'fx_on'" />
<ParamItem :paramData="param_faderId" v-model="action.faderId" v-if="param_action.value == 'set_fader'" />
<ParamItem :paramData="param_faderValue" v-model="action.faderValue" v-if="param_action.value == 'set_fader'" />
<ParamItem :paramData="param_profile" v-model="action.profile" v-if="param_action.value == 'profile'" />
<div class="card-item" v-if="param_action.value == 'sample_play'">
<p class="head">{{ $t("triggers.actions.goxlr.select_sampler") }}</p>
<GoXLRUI v-model="sampleTarget" @change="samplerTargetChange()" samplerMode childMode />
</div>
</div>
</template>
<script lang="ts">
import ToggleBlock from '@/components/ToggleBlock.vue';
import { TriggerActionGoXLRDataActionList, type TriggerActionGoXLRData, type TriggerActionGoXLRDataAction, type ITriggerPlaceholder } from '@/types/TriggerActionDataTypes';
import type { TwitchatDataTypes } from '@/types/TwitchatDataTypes';
import GoXLRSocket from '@/utils/goxlr/GoXLRSocket';
import {toNative, Component, Prop } from 'vue-facing-decorator';
import ParamItem from '../../../ParamItem.vue';
import AbstractTriggerActionEntry from './AbstractTriggerActionEntry';
import GoXLRUI from '@/components/goxlr/GoXLRUI.vue';
import { GoXLRTypes } from '@/types/GoXLRTypes';
import GoXLRSocketEvent from '@/events/GoXLRSocketEvent';
@Component({
components:{
GoXLRUI,
ParamItem,
ToggleBlock,
},
emits:[],
})
class TriggerActionGoXLREntry extends AbstractTriggerActionEntry {
@Prop
declare action:TriggerActionGoXLRData;
public sampleTarget:Extract<GoXLRTypes.ButtonTypesData, "SamplerSelectA"|"SamplerSelectB"|"SamplerSelectC"|"SamplerBottomLeft"|"SamplerBottomRight"|"SamplerTopLeft"|"SamplerTopRight">[] = [];
public param_action:TwitchatDataTypes.ParameterData<TriggerActionGoXLRDataAction, string> = {type:"list", value:"fx_on", labelKey:"triggers.actions.goxlr.param_action"};
public param_fxPreset:TwitchatDataTypes.ParameterData<number> = {type:"list", value:0, labelKey:"triggers.actions.goxlr.param_fxPreset"};
public param_faderId:TwitchatDataTypes.ParameterData<GoXLRTypes.InputTypesData> = {type:"list", value:"Mic", labelKey:"triggers.actions.goxlr.param_faderIndex"};
public param_profile:TwitchatDataTypes.ParameterData<string> = {type:"list", value:"Mc", labelKey:"triggers.actions.goxlr.param_profile"};
public param_faderValue:TwitchatDataTypes.ParameterData<string> = {type:"string", value:"128", labelKey:"triggers.actions.goxlr.param_faderValue"};
private goxlrFaderHandler!:(e:GoXLRSocketEvent) =>void;
private goxlrButtonHandler!:(e:GoXLRSocketEvent) =>void;
public beforeMount():void {
this.param_action.listValues = TriggerActionGoXLRDataActionList
//Remove "large" GoXLR features if connected one is a mini model
.filter(v=>v.mini === true || !GoXLRSocket.instance.isGoXLRMini )
.map(v=>{ return {value:v.code, labelKey:"triggers.actions.goxlr.action_"+v.code}});
this.param_fxPreset.listValues = [0,1,2,3,4,5].map(v=>{ return {value:v, labelKey:"triggers.actions.goxlr.param_fxPreset"+(v+1)}});
this.param_fxPreset.listValues.unshift({value:-1, labelKey:"triggers.actions.goxlr.param_fxPreset_keep"})
this.param_action.value = this.action.action || this.param_action.listValues[0].value;
this.action.action = this.param_action.value;
this.param_profile.listValues = GoXLRSocket.instance.profileList.map(v=> {
return {value:v, label:v};
});
this.param_profile.value = GoXLRSocket.instance.currentProfile;
if(this.action.sampleIndex) {
const bt1 = "SamplerSelect" + this.action.sampleIndex[0] as "SamplerSelectA" | "SamplerSelectB" | "SamplerSelectC";
const bt2 = "Sampler" + this.action.sampleIndex[1] as "SamplerBottomLeft" | "SamplerBottomRight" | "SamplerTopLeft" | "SamplerTopRight";
this.sampleTarget = [bt1, bt2];
}
const list:TwitchatDataTypes.ParameterDataListValue<GoXLRTypes.InputTypesData>[] = [];
for (let i = 0; i < GoXLRTypes.InputTypes.length; i++) {
const el = GoXLRTypes.InputTypes[i];
list.push({
value:el,
labelKey:"triggers.actions.goxlr.param_fader_"+el.toLowerCase()
})
}
this.param_faderId.listValues = list;
this.goxlrFaderHandler = (e:GoXLRSocketEvent) => this.onFaderHandler(e)
this.goxlrButtonHandler = (e:GoXLRSocketEvent) => this.onGoxlrButton(e)
GoXLRSocket.instance.addEventListener(GoXLRSocketEvent.FADER_VOLUME, this.goxlrFaderHandler);
GoXLRSocket.instance.addEventListener(GoXLRSocketEvent.BUTTON_PRESSED, this.goxlrButtonHandler);
}
public beforeUnmount():void {
GoXLRSocket.instance.removeEventListener(GoXLRSocketEvent.FADER_VOLUME, this.goxlrFaderHandler);
GoXLRSocket.instance.removeEventListener(GoXLRSocketEvent.BUTTON_PRESSED, this.goxlrButtonHandler);
}
public samplerTargetChange():void {
if(this.sampleTarget.length > 2) {
this.sampleTarget.splice(1, 1);
}
if(this.sampleTarget.length == 2) {
const bt1 = this.sampleTarget[0].replace("SamplerSelect", "") as "A" | "B" | "C";
const bt2 = this.sampleTarget[1].replace("Sampler", "") as "BottomLeft" | "BottomRight" | "TopLeft" | "TopRight";
this.action.sampleIndex = [bt1, bt2];
}
}
/**
* Called when the available placeholder list is updated
*/
public onPlaceholderUpdate(list:ITriggerPlaceholder<any>[]):void {
this.param_faderValue.placeholderList = list.filter(v=>v.numberParsable == true);
}
/**
* Called when a button is pressed
* @param e
*/
private onGoxlrButton(e:GoXLRSocketEvent):void {
switch(this.action.action) {
case "sample_play": {
if(!this.action.sampleIndex) this.action.sampleIndex = ["A", "TopLeft"];
if(e.buttonId == "SamplerSelectA") this.action.sampleIndex![0] = "A";
if(e.buttonId == "SamplerSelectB") this.action.sampleIndex![0] = "B";
if(e.buttonId == "SamplerSelectC") this.action.sampleIndex![0] = "C";
if(e.buttonId == "SamplerTopLeft"
|| e.buttonId == "SamplerTopRight"
|| e.buttonId == "SamplerBottomLeft"
|| e.buttonId == "SamplerBottomRight") {
if(GoXLRSocket.instance.getButtonState("SamplerSelectA")) this.action.sampleIndex![0] = "A";
if(GoXLRSocket.instance.getButtonState("SamplerSelectB")) this.action.sampleIndex![0] = "B";
if(GoXLRSocket.instance.getButtonState("SamplerSelectC")) this.action.sampleIndex![0] = "C";
if(e.buttonId == "SamplerTopLeft") this.action.sampleIndex![1] = "TopLeft";
if(e.buttonId == "SamplerTopRight") this.action.sampleIndex![1] = "TopRight";
if(e.buttonId == "SamplerBottomLeft") this.action.sampleIndex![1] = "BottomLeft";
if(e.buttonId == "SamplerBottomRight") this.action.sampleIndex![1] = "BottomRight";
}
break;
}
}
}
/**
* Called when a fader is used
* @param e
*/
private onFaderHandler(e:GoXLRSocketEvent):void {
switch(this.action.action) {
case "set_fader": {
//Don't do this or the value would get erased after testing the trigger
// this.action.faderId = e.faderChannel!
// this.action.faderValue = e.faderVolume!.toString();
break;
}
}
}
}
export default toNative(TriggerActionGoXLREntry);
</script>
<style scoped lang="less">
.triggeractiongoxlrentry{
.head {
margin-bottom: .5em;
text-align: center;
}
}
</style> | 412 | 0.859964 | 1 | 0.859964 | game-dev | MEDIA | 0.623006 | game-dev | 0.907164 | 1 | 0.907164 |
qnpiiz/rich-2.0 | 1,116 | src/main/java/net/minecraft/block/NetherRootsBlock.java | package net.minecraft.block;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
public class NetherRootsBlock extends BushBlock
{
protected static final VoxelShape SHAPE = Block.makeCuboidShape(2.0D, 0.0D, 2.0D, 14.0D, 13.0D, 14.0D);
protected NetherRootsBlock(AbstractBlock.Properties properties)
{
super(properties);
}
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{
return SHAPE;
}
protected boolean isValidGround(BlockState state, IBlockReader worldIn, BlockPos pos)
{
return state.isIn(BlockTags.NYLIUM) || state.isIn(Blocks.SOUL_SOIL) || super.isValidGround(state, worldIn, pos);
}
/**
* Get the OffsetType for this Block. Determines if the model is rendered slightly offset.
*/
public AbstractBlock.OffsetType getOffsetType()
{
return AbstractBlock.OffsetType.XZ;
}
}
| 412 | 0.740571 | 1 | 0.740571 | game-dev | MEDIA | 0.996238 | game-dev | 0.926248 | 1 | 0.926248 |
Fluorohydride/ygopro-scripts | 3,778 | c65853758.lua | --ヤミー★リデンプション
local s,id,o=GetID()
function s.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
c:RegisterEffect(e1)
--atk down
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetValue(s.val)
c:RegisterEffect(e2)
--draw
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,0))
e3:SetCategory(CATEGORY_DRAW+CATEGORY_TODECK)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetRange(LOCATION_SZONE)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCountLimit(1,EFFECT_COUNT_CODE_CHAIN)
e3:SetCondition(s.drcon)
e3:SetTarget(s.drtg)
e3:SetOperation(s.drop)
c:RegisterEffect(e3)
--control
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(id,1))
e4:SetCategory(CATEGORY_CONTROL)
e4:SetType(EFFECT_TYPE_QUICK_O)
e4:SetCode(EVENT_FREE_CHAIN)
e4:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
e4:SetRange(LOCATION_GRAVE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCountLimit(1,id+o)
e4:SetCost(aux.bfgcost)
e4:SetTarget(s.cttg)
e4:SetOperation(s.ctop)
c:RegisterEffect(e4)
end
function s.atkfilter(c)
return c:IsRace(RACE_BEAST) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsType(TYPE_MONSTER) and c:IsFaceupEx()
end
function s.val(e,c)
local tp=e:GetHandlerPlayer()
local g=Duel.GetMatchingGroup(s.atkfilter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,nil)
return g:GetCount()*(-200)
end
function s.cfilter(c,tp)
return c:IsFaceup() and c:IsRace(RACE_BEAST) and c:IsAttribute(ATTRIBUTE_LIGHT)
and c:IsType(TYPE_SYNCHRO) and c:IsSummonType(SUMMON_TYPE_SYNCHRO)
and c:IsSummonPlayer(tp)
end
function s.drcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(s.cfilter,1,nil,tp)
end
function s.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_HAND)
end
function s.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
if Duel.Draw(p,d,REASON_EFFECT)~=0 and Duel.IsExistingMatchingCard(Card.IsAbleToDeck,p,LOCATION_HAND,0,1,nil) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(p,Card.IsAbleToDeck,p,LOCATION_HAND,0,1,1,nil)
Duel.ShuffleHand(p)
Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
end
end
function s.ctfilter1(c)
local tp=c:GetControler()
return c:IsAbleToChangeControler() and Duel.GetMZoneCount(tp,c,tp,LOCATION_REASON_CONTROL)>0
end
function s.ctfilter2(c)
local tp=c:GetControler()
return c:IsFaceup() and c:IsSetCard(0x1ca) and c:IsAbleToChangeControler()
and Duel.GetMZoneCount(tp,c,tp,LOCATION_REASON_CONTROL)>0
end
function s.cttg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(s.ctfilter1,tp,0,LOCATION_MZONE,1,nil)
and Duel.IsExistingTarget(s.ctfilter2,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL)
local g1=Duel.SelectTarget(tp,s.ctfilter1,tp,0,LOCATION_MZONE,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL)
local g2=Duel.SelectTarget(tp,s.ctfilter2,tp,LOCATION_MZONE,0,1,1,nil)
g1:Merge(g2)
Duel.SetOperationInfo(0,CATEGORY_CONTROL,g1,2,0,0)
end
function s.ctop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local a=g:GetFirst()
local b=g:GetNext()
if a:IsRelateToEffect(e) and b:IsRelateToEffect(e) then
Duel.SwapControl(a,b)
end
end
| 412 | 0.88898 | 1 | 0.88898 | game-dev | MEDIA | 0.98802 | game-dev | 0.964554 | 1 | 0.964554 |
JetBrains/resharper-unity | 14,887 | resharper/resharper-unity/src/Unity.Rider/Integration/Protocol/PassthroughHost.cs | #nullable enable
using System;
using System.Linq;
using JetBrains.Application.Parts;
using JetBrains.Application.Threading;
using JetBrains.Collections.Viewable;
using JetBrains.Core;
using JetBrains.Diagnostics;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.Rd.Base;
using JetBrains.Rd.Tasks;
using JetBrains.ReSharper.Plugins.Unity.Core.Application.Components;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Rider.Model.Unity;
using JetBrains.Rider.Model.Unity.BackendUnity;
using JetBrains.Rider.Model.Unity.FrontendBackend;
using JetBrains.Util;
using FrontendOpenArgs = JetBrains.Rider.Model.Unity.FrontendBackend.RdOpenFileArgs;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.Protocol
{
[SolutionComponent(Instantiation.DemandAnyThreadSafe)]
public class PassthroughHost : IUnityProjectLazyComponent
{
private readonly BackendUnityHost myBackendUnityHost;
private readonly FrontendBackendHost myFrontendBackendHost;
private readonly ILogger myLogger;
public PassthroughHost(Lifetime lifetime,
BackendUnityHost backendUnityHost,
FrontendBackendHost frontendBackendHost,
ILogger logger,
IThreading threading)
{
myBackendUnityHost = backendUnityHost;
myFrontendBackendHost = frontendBackendHost;
myLogger = logger;
if (!frontendBackendHost.IsAvailable) return;
var model = frontendBackendHost.Model;
if (model == null) return; // only tests
threading.ExecuteOrQueueEx(lifetime, "PassthroughHost.ctor", () =>
{
AdviseFrontendToUnityModel(lifetime, model);
// Advise the backend/Unity model as high priority so we get called back before other subscribers.
// This allows us to populate the protocol on reconnection before other subscribes start to advise
using (Signal.PriorityAdviseCookie.Create())
{
// TODO: ReactiveEx.ViewNotNull isn't NRT ready
backendUnityHost.BackendUnityModel!.ViewNotNull<BackendUnityModel>(lifetime,
(l, backendUnityModel) =>
{
Assertion.AssertNotNull(backendUnityModel);
AdviseUnityToFrontendModel(l, backendUnityModel);
});
}
backendUnityHost.BackendUnityModel.Advise(lifetime, backendUnityModel =>
{
// https://github.com/JetBrains/resharper-unity/pull/2023
if (backendUnityModel == null) frontendBackendHost.Model?.PlayControlsInitialized.SetValue(false);
});
});
}
private void AdviseFrontendToUnityModel(Lifetime lifetime, FrontendBackendModel frontendBackendModel)
{
// BackendUnityModel is recreated frequently (e.g. on each AppDomain reload when changing play/edit mode).
// So subscribe to the frontendBackendModel once and flow in changes only if backendUnityModel is available.
// Note that we only flow changes, not the current value. Even though these properties are stateful,
// frontendBackendModel is not the source of truth - values need to flow from backendUnityModel. Also, due
// to model reload, we go through a few values before we stabilise. E.g.:
// * User clicks play, fb.Play is true, flows into bu.Play which switches to play mode and causes an
// AppDomain reload.
// * bu.Play becomes false due to AppDomain teardown, flows into fb.Play
// * BackendUnityModel is torn down and recreated (<- WARNING!)
// * bu.Play becomes true as Unity enters play mode, flows into fb.Play
// If we flowed the current value of fb.Play into backendUnityModel when it is recreated, we'd set it to
// false, triggering play mode to end.
// Step is simply since it's a non-stateful ISource<T>
var backendUnityModelProperty = myBackendUnityHost.BackendUnityModel;
frontendBackendModel.PlayControls.Play.FlowChangesIntoRdDeferred(lifetime,
() => backendUnityModelProperty.Maybe.ValueOrDefault?.PlayControls.Play);
frontendBackendModel.PlayControls.Pause.FlowChangesIntoRdDeferred(lifetime,
() => backendUnityModelProperty.Maybe.ValueOrDefault?.PlayControls.Pause);
frontendBackendModel.PlayControls.Step.Advise(lifetime, () => backendUnityModelProperty.Maybe.ValueOrDefault?.PlayControls.Step.Fire());
frontendBackendModel.UnityApplicationSettings.ProfilerSnapshotFetchingSettings.Advise(lifetime,
settingValue =>
{
backendUnityModelProperty.Maybe.ValueOrDefault?.UnityApplicationSettings
.ProfilerSnapshotFetchingSettings.Fire(settingValue);
});
// Called from frontend to generate the UIElements schema files
frontendBackendModel.GenerateUIElementsSchema.SetAsync((l, u) =>
{
var model = backendUnityModelProperty.Maybe.ValueOrDefault;
return model != null
? model.GenerateUIElementsSchema.Start(l, u).ToRdTask(l)
: RdTask.Successful(false);
});
frontendBackendModel.GetAndroidSdkRoot.SetAsync(async (l, u) =>
{
var model = backendUnityModelProperty.Maybe.ValueOrDefault;
return model == null ? null : await model.GetAndroidSdkRoot.Start(l, u).AsTask();
});
// Signalled from frontend to select and ping the object in the Project view
frontendBackendModel.ShowFileInUnity.Advise(lifetime, file =>
backendUnityModelProperty.Maybe.ValueOrDefault?.ShowFileInUnity.Fire(file));
// Signalled from fronted to open the preferences window
frontendBackendModel.ShowPreferences.Advise(lifetime, _ =>
backendUnityModelProperty.Maybe.ValueOrDefault?.ShowPreferences.Fire());
// Called from frontend to run a method in unity
frontendBackendModel.RunMethodInUnity.SetAsync((l, data) =>
{
var backendUnityModel = backendUnityModelProperty.Maybe.ValueOrDefault;
return backendUnityModel == null
? RdTask.Cancelled<RunMethodResult>()
: backendUnityModel.RunMethodInUnity.Start(l, data).ToRdTask(l);
});
frontendBackendModel.HasUnsavedState.SetAsync((l, u) =>
{
var backendUnityModel = backendUnityModelProperty.Maybe.ValueOrDefault;
return backendUnityModel == null
? RdTask.Cancelled<bool>()
: backendUnityModel.HasUnsavedState.Start(l, u).ToRdTask(l);
});
frontendBackendModel.StartProfiling.SetAsync((l, play) =>
{
var backendUnityModel = backendUnityModelProperty.Maybe.ValueOrDefault;
var profilerApiPath = GetProfilerApiPath();
return backendUnityModel == null || profilerApiPath == null
? RdTask.Cancelled<Unit>()
: backendUnityModel.StartProfiling.Start(l, new ProfilingData(play, profilerApiPath, false)).ToRdTask(l);
});
}
private string? GetProfilerApiPath()
{
var etwAssemblyShorName = "JetBrains.Etw";
var etwAssemblyLocation = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.Equals(etwAssemblyShorName))?.Location;
if (etwAssemblyLocation == null)
{
myLogger.Error($"{etwAssemblyShorName} was not found.");
return null;
}
var unityProfilerApiPath = FileSystemPath.Parse(etwAssemblyLocation).Parent
.Combine("JetBrains.Etw.UnityProfilerApi.dll");
if (!unityProfilerApiPath.ExistsFile)
{
myLogger.Error($"{unityProfilerApiPath} doesn't exist.");
return null;
}
return unityProfilerApiPath.FullPath;
}
private void AdviseUnityToFrontendModel(Lifetime lifetime, BackendUnityModel backendUnityModel)
{
// *********************************************************************************************************
//
// WARNING
//
// Be very careful with stateful properties!
//
// When the backend/Unity protocol is closed, the existing properties maintain their current values. This
// doesn't affect BackendUnityModel because we clear the model when the connection is lost. However, it does
// affect any properties that have had values flowed in from BackedUnityModel - these values are not reset.
//
// When the backend/Unity protocol is (re)created and advertised, we *should* have initial values from the
// Unity end (the model is advertised asynchronously to being created, and the dispatcher *should* have
// processed messages). However, we cannot guarantee this - during testing, it usually works as expected,
// but occasionally wouldn't be fully initialised. These means we need to be careful when assuming that
// initial values are available in the properties. Advise and RdExtensions.FlowIntoRdSafe will correctly set
// the target value if the source value exists. Avoid BeUtilExtensions.FlowIntoRd, as that will throw an
// exception if the source value does not yet exist.
// Note that creating and advertising the model, as well as all callbacks, happen on the main thread.
//
// We must ensure that the Unity end (re)initialises properties when the protocol is created, or we could
// have stale or empty properties here and in the frontend.
//
// *********************************************************************************************************
var frontendBackendModel = myFrontendBackendHost.Model.NotNull("frontendBackendModel != null");
AdviseApplicationData(lifetime, backendUnityModel, frontendBackendModel);
AdviseApplicationSettings(lifetime, backendUnityModel, frontendBackendModel);
AdviseProjectSettings(lifetime, backendUnityModel, frontendBackendModel);
AdvisePlayControls(lifetime, backendUnityModel, frontendBackendModel);
AdviseConsoleEvents(lifetime, backendUnityModel, frontendBackendModel);
AdviseOpenFile(backendUnityModel, frontendBackendModel);
}
private static void AdviseApplicationData(in Lifetime lifetime, BackendUnityModel backendUnityModel,
FrontendBackendModel frontendBackendModel)
{
backendUnityModel.UnityApplicationData.FlowIntoRdSafe(lifetime, frontendBackendModel.UnityApplicationData);
backendUnityModel.UnityApplicationData.FlowIntoRdSafe(lifetime, data =>
{
var version = UnityVersion.Parse(data.ApplicationVersion);
return UnityVersion.RequiresRiderPackage(version);
}, frontendBackendModel.RequiresRiderPackage);
backendUnityModel.UnityApplicationData.FlowIntoRdSafe(lifetime, data =>
{
var version = UnityVersion.Parse(data.ApplicationVersion);
return UnityVersion.IsCoreCLR(version);
}, frontendBackendModel.IsCoreCLR);
}
private static void AdviseApplicationSettings(in Lifetime lifetime, BackendUnityModel backendUnityModel,
FrontendBackendModel frontendBackendModel)
{
backendUnityModel.UnityApplicationSettings.ScriptCompilationDuringPlay.FlowIntoRdSafe(lifetime,
frontendBackendModel.UnityApplicationSettings.ScriptCompilationDuringPlay);
}
private static void AdviseProjectSettings(in Lifetime lifetime, BackendUnityModel backendUnityModel,
FrontendBackendModel frontendBackendModel)
{
backendUnityModel.UnityProjectSettings.BuildLocation.FlowIntoRdSafe(lifetime,
frontendBackendModel.UnityProjectSettings.BuildLocation);
}
private static void AdvisePlayControls(in Lifetime lifetime, BackendUnityModel backendUnityModel,
FrontendBackendModel frontendBackendModel)
{
backendUnityModel.PlayControls.Play.FlowIntoRdSafe(lifetime, frontendBackendModel.PlayControls.Play);
backendUnityModel.PlayControls.Pause.FlowIntoRdSafe(lifetime, frontendBackendModel.PlayControls.Pause);
// https://github.com/JetBrains/resharper-unity/pull/2023
backendUnityModel.PlayControls.Play.Advise(lifetime, _ => frontendBackendModel.PlayControlsInitialized.SetValue(true));
}
private static void AdviseConsoleEvents(in Lifetime lifetime, BackendUnityModel backendUnityModel,
FrontendBackendModel frontendBackendModel)
{
backendUnityModel.ConsoleLogging.OnConsoleLogEvent.Advise(lifetime, frontendBackendModel.ConsoleLogging.OnConsoleLogEvent.Fire);
backendUnityModel.ConsoleLogging.LastInitTime.FlowIntoRdSafe(lifetime, frontendBackendModel.ConsoleLogging.LastInitTime);
backendUnityModel.ConsoleLogging.LastPlayTime.FlowIntoRdSafe(lifetime, frontendBackendModel.ConsoleLogging.LastPlayTime);
}
private void AdviseOpenFile(BackendUnityModel backendUnityModel, FrontendBackendModel frontendBackendModel)
{
backendUnityModel.OpenFileLineCol.SetAsync((lf, args) =>
{
RdTask<bool> result = new RdTask<bool>();
using (ReadLockCookie.Create())
{
try
{
return frontendBackendModel.OpenFileLineCol.Start(lf, new FrontendOpenArgs(args.Path, args.Line, args.Col)).ToRdTask(lf);
}
catch (Exception e)
{
myLogger.Error(e);
result.Set(false);
}
}
return result;
});
}
}
}
| 412 | 0.811366 | 1 | 0.811366 | game-dev | MEDIA | 0.925343 | game-dev | 0.930785 | 1 | 0.930785 |
sonicretro/skdisasm | 4,528 | SonLVL INI Files/SSZ/EggRobo.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using SonicRetro.SonLVL.API;
namespace S3KObjectDefinitions.SSZ
{
class EggRobo : ObjectDefinition
{
private PropertySpec[] properties;
private ReadOnlyCollection<byte> subtypes;
private Sprite[][] sprites;
public override string Name
{
get { return "Egg Robo"; }
}
public override Sprite Image
{
get { return sprites[0][0]; }
}
public override PropertySpec[] CustomProperties
{
get { return properties; }
}
public override ReadOnlyCollection<byte> Subtypes
{
get { return subtypes; }
}
public override string SubtypeName(byte subtype)
{
return null;
}
public override Sprite SubtypeImage(byte subtype)
{
return sprites[0][0];
}
public override Sprite GetSprite(ObjectEntry obj)
{
var index = (obj.SubType & 0x09) == 0 ? (obj.SubType >> 1) & 3 : 3;
return sprites[index][(obj.XFlip ? 1 : 0) | (obj.YFlip ? 2 : 0)];
}
public override Rectangle GetBounds(ObjectEntry obj)
{
if ((obj.SubType & 6) != 4) return base.GetBounds(obj);
var bounds = sprites[1][(obj.XFlip ? 1 : 0) | (obj.YFlip ? 2 : 0)].Bounds;
bounds.Offset(obj.X, obj.Y);
return bounds;
}
public override int GetDepth(ObjectEntry obj)
{
return 5;
}
public override void Init(ObjectData data)
{
var art = LevelData.ReadFile(
"../General/Sprites/Egg Robo/Egg Robo Badnik.bin", CompressionType.KosinskiM);
var map = LevelData.ASMToBin(
"../General/Sprites/Egg Robo/Map - Egg Robo Badnik.asm", LevelData.Game.MappingsVersion);
properties = new PropertySpec[2];
subtypes = new ReadOnlyCollection<byte>(new byte[0]);
sprites = new Sprite[4][];
sprites[0] = BuildFlippedSprites(
ReadScaledArt("../General/Sprites/Egg Robo/Egg Robo Fly Scaled.bin", 0, 1, true));
var arm = ObjectHelper.MapToBmp(art, map, 2, 0);
var body = ObjectHelper.MapToBmp(art, map, 3, 0, true);
var legs = ObjectHelper.MapToBmp(art, map, 6, 0);
arm.Offset(-28, -4);
legs.Offset(-12, 28);
sprites[1] = BuildFlippedSprites(new Sprite(arm, legs, body));
body.InvertPriority();
sprites[2] = BuildFlippedSprites(new Sprite(arm, legs, body));
var cucky = ObjectHelper.MapASMToBmp(LevelData.ReadFile(
"../General/Sprites/Animals/Chicken.bin", CompressionType.Nemesis),
"../General/Sprites/Animals/Map - Animals 4.asm", 0, 0);
var pocky = ObjectHelper.MapASMToBmp(LevelData.ReadFile(
"../General/Sprites/Animals/Rabbit.bin", CompressionType.Nemesis),
"../General/Sprites/Animals/Map - Animals 5.asm", 0, 0);
pocky.Offset(32, 20);
var right = new Sprite(cucky, pocky);
right.Flip(true, false);
right.Offset(80, 0);
pocky.Offset(-64, 0);
var left = new Sprite(cucky, pocky);
left.Flip(true, false);
left.Offset(-80, 0);
sprites[2][0] = new Sprite(sprites[2][0], left);
sprites[2][1] = new Sprite(sprites[2][1], right);
sprites[2][2] = new Sprite(sprites[2][2], left);
sprites[2][3] = new Sprite(sprites[2][3], right);
sprites[3] = BuildFlippedSprites(ObjectHelper.UnknownObject);
properties[0] = new PropertySpec("Egg Robo ID", typeof(int), "Extended",
"The object status array flag set by this object.", null,
(obj) => obj.SubType >> 4,
(obj, value) => obj.SubType = (byte)((obj.SubType & 0x0F) | ((int)value << 4)));
properties[1] = new PropertySpec("Reveal From", typeof(int), "Extended",
"If set, the enemy will be hidden when it first spawns.", null, new Dictionary<string, int>
{
{ "Start", 2 },
{ "Side (animals)", 4 },
{ "Background", 0 }
},
(obj) => obj.SubType & 0x0F,
(obj, value) => obj.SubType = (byte)((obj.SubType & 0xF0) | ((int)value & 0x0F)));
}
private Sprite[] BuildFlippedSprites(Sprite sprite)
{
var flipX = new Sprite(sprite, true, false);
var flipY = new Sprite(sprite, false, true);
var flipXY = new Sprite(sprite, true, true);
return new[] { sprite, flipX, flipY, flipXY };
}
private Sprite ReadScaledArt(string artfile, int frame, int pal, bool priority = false)
{
var bitmap = new BitmapBits(64, 64);
var src = LevelData.ReadFile(artfile, CompressionType.Uncompressed);
var dest = bitmap.Bits;
frame <<= 12;
pal <<= 4;
for (var index = 0; index < dest.Length; index++)
{
var color = src[frame++] & 0x0F;
dest[index] = (byte)(color == 0 ? 0 : (pal | color));
}
return new Sprite(bitmap, priority, -32, -32);
}
}
}
| 412 | 0.676547 | 1 | 0.676547 | game-dev | MEDIA | 0.89084 | game-dev | 0.749573 | 1 | 0.749573 |
sporchia/alttp_vt_randomizer | 1,969 | tests/NoGlitches/DarkWorld/MireTest.php | <?php
namespace NoGlitches\DarkWorld;
use ALttP\Item;
use ALttP\World;
use TestCase;
/**
* @group NoGlitches
*/
class MireTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$this->world = World::factory('standard', ['difficulty' => 'test_rules', 'logic' => 'NoGlitches']);
$this->addCollected(['RescueZelda']);
$this->collected->setChecksForWorld($this->world->id);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->world);
}
/**
* @param string $location
* @param bool $access
* @param array $items
* @param array $except
*
* @dataProvider accessPool
*/
public function testLocation(string $location, bool $access, array $items, array $except = [])
{
if (count($except)) {
$this->collected = $this->allItemsExcept($except);
}
$this->addCollected($items);
$this->assertEquals($access, $this->world->getLocation($location)
->canAccess($this->collected));
}
public function accessPool()
{
return [
["Mire Shed - Left", false, []],
["Mire Shed - Left", false, [], ['Gloves']],
["Mire Shed - Left", false, [], ['MoonPearl']],
["Mire Shed - Left", false, [], ['Flute']],
["Mire Shed - Left", true, ['MoonPearl', 'Flute', 'ProgressiveGlove', 'ProgressiveGlove']],
["Mire Shed - Left", true, ['MoonPearl', 'Flute', 'TitansMitt']],
["Mire Shed - Right", false, []],
["Mire Shed - Right", false, [], ['Gloves']],
["Mire Shed - Right", false, [], ['MoonPearl']],
["Mire Shed - Right", false, [], ['Flute']],
["Mire Shed - Right", true, ['MoonPearl', 'Flute', 'ProgressiveGlove', 'ProgressiveGlove']],
["Mire Shed - Right", true, ['MoonPearl', 'Flute', 'TitansMitt']],
];
}
}
| 412 | 0.946808 | 1 | 0.946808 | game-dev | MEDIA | 0.48484 | game-dev | 0.759471 | 1 | 0.759471 |
plan-player-analytics/Plan | 4,267 | Plan/nukkit/src/main/java/com/djrapitops/plan/addons/placeholderapi/NukkitPlaceholderRegistrar.java | /*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.addons.placeholderapi;
import cn.nukkit.Player;
import com.creeperface.nukkit.placeholderapi.api.PlaceholderAPI;
import com.creeperface.nukkit.placeholderapi.api.PlaceholderParameters;
import com.creeperface.nukkit.placeholderapi.api.PlaceholderParameters.Parameter;
import com.djrapitops.plan.PlanSystem;
import com.djrapitops.plan.commands.use.Arguments;
import com.djrapitops.plan.delivery.domain.container.PlayerContainer;
import com.djrapitops.plan.delivery.domain.keys.PlayerKeys;
import com.djrapitops.plan.gathering.cache.SessionCache;
import com.djrapitops.plan.placeholder.PlanPlaceholders;
import com.djrapitops.plan.storage.database.queries.containers.ContainerFetchQueries;
import com.djrapitops.plan.utilities.logging.ErrorContext;
import com.djrapitops.plan.utilities.logging.ErrorLogger;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Placeholder expansion used to provide data from Plan on Nukkit.
*
* @author developStorm
*/
@Singleton
public class NukkitPlaceholderRegistrar {
private final PlanPlaceholders placeholders;
private final PlanSystem system;
private final ErrorLogger errorLogger;
@Inject
public NukkitPlaceholderRegistrar(
PlanPlaceholders placeholders,
PlanSystem system,
ErrorLogger errorLogger
) {
this.placeholders = placeholders;
this.system = system;
this.errorLogger = errorLogger;
}
public void register() {
PlaceholderAPI api = PlaceholderAPI.getInstance();
placeholders.getPlaceholders().forEach((name, loader) -> api.builder(name, Serializable.class)
.visitorLoader(options -> {
try {
return loader.apply(
getPlayer(options.getPlayer()),
getPlaceholderParameterValues(options.getParameters())
);
} catch (Exception e) {
errorLogger.warn(e, ErrorContext.builder().related("Registering PlaceholderAPI").build());
return null;
}
}).build()
);
placeholders.getStaticPlaceholders().forEach((name, loader) -> api.builder(name, Serializable.class)
.loader(options -> {
try {
return loader.apply(
new Arguments(getPlaceholderParameterValues(options.getParameters()))
);
} catch (Exception e) {
errorLogger.warn(e, ErrorContext.builder().related("Registering PlaceholderAPI").build());
return null;
}
}).build()
);
}
private List<String> getPlaceholderParameterValues(PlaceholderParameters parameters) {
return parameters.getAll().stream()
.map(Parameter::getValue)
.collect(Collectors.toList());
}
private PlayerContainer getPlayer(Player player) {
UUID uuid = player.getUniqueId();
PlayerContainer container = system.getDatabaseSystem().getDatabase().query(ContainerFetchQueries.fetchPlayerContainer(uuid));
SessionCache.getCachedSession(uuid).ifPresent(session -> container.putRawData(PlayerKeys.ACTIVE_SESSION, session));
return container;
}
}
| 412 | 0.91914 | 1 | 0.91914 | game-dev | MEDIA | 0.698006 | game-dev | 0.919592 | 1 | 0.919592 |
rspamd/rspamd | 2,402 | src/rspamadm/rspamadm.h | /*-
* Copyright 2016 Vsevolod Stakhov
*
* 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.
*/
#ifndef RSPAMD_RSPAMDADM_H
#define RSPAMD_RSPAMDADM_H
#include "config.h"
#include "ucl.h"
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef __cplusplus
extern "C" {
#endif
extern GHashTable *ucl_vars;
extern char **lua_env;
extern struct rspamd_main *rspamd_main;
GQuark rspamadm_error(void);
struct rspamadm_command;
typedef const char *(*rspamadm_help_func)(gboolean full_help,
const struct rspamadm_command *cmd);
typedef void (*rspamadm_run_func)(int argc, char **argv,
const struct rspamadm_command *cmd);
typedef void (*rspamadm_lua_exports_func)(gpointer lua_state);
#define RSPAMADM_FLAG_NOHELP (1u << 0u)
#define RSPAMADM_FLAG_LUA (1u << 1u)
#define RSPAMADM_FLAG_DYNAMIC (1u << 2u)
struct rspamadm_command {
const char *name;
unsigned int flags;
rspamadm_help_func help;
rspamadm_run_func run;
rspamadm_lua_exports_func lua_subrs;
GPtrArray *aliases;
gpointer command_data; /* Opaque data */
};
extern const struct rspamadm_command *commands[];
extern struct rspamadm_command help_command;
const struct rspamadm_command *rspamadm_search_command(const char *name,
GPtrArray *all_commands);
void rspamadm_fill_internal_commands(GPtrArray *dest);
void rspamadm_fill_lua_commands(lua_State *L, GPtrArray *dest);
gboolean rspamadm_execute_lua_ucl_subr(int argc, char **argv,
const ucl_object_t *res,
const char *script_name,
gboolean rspamadm_subcommand);
struct thread_entry;
typedef void (*lua_thread_error_t)(struct thread_entry *thread, int ret, const char *msg);
struct lua_call_data {
int top;
int ret;
gpointer ud;
};
int lua_repl_thread_call(struct thread_entry *thread, int narg,
gpointer ud, lua_thread_error_t error_func);
#ifdef __cplusplus
}
#endif
#endif
| 412 | 0.826466 | 1 | 0.826466 | game-dev | MEDIA | 0.178684 | game-dev | 0.531108 | 1 | 0.531108 |
llapuras/UnityXbrShader | 34,771 | XbrForPixelArt/Library/PackageCache/com.unity.timeline@1.2.12/Editor/Recording/TimelineRecording_Monobehaviour.cs | using System.Collections.Generic;
using System.Linq;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Timeline;
using System.Globalization;
namespace UnityEditor.Timeline
{
// Methods and data for handling recording to monobehaviours
static partial class TimelineRecording
{
internal class RecordingState : IAnimationRecordingState
{
public GameObject activeGameObject { get; set; }
public GameObject activeRootGameObject { get; set; }
public AnimationClip activeAnimationClip { get; set; }
public void SaveCurve(AnimationWindowCurve curve)
{
Undo.RegisterCompleteObjectUndo(activeAnimationClip, "Edit Curve");
AnimationWindowUtility.SaveCurve(activeAnimationClip, curve);
}
public void AddPropertyModification(EditorCurveBinding binding, PropertyModification propertyModification, bool keepPrefabOverride)
{
AnimationMode.AddPropertyModification(binding, propertyModification, keepPrefabOverride);
}
public bool addZeroFrame
{
get { return false; }
}
public int currentFrame { get; set; }
public bool DiscardModification(PropertyModification modification)
{
return false;
}
}
static readonly RecordingState s_RecordState = new RecordingState();
static readonly AnimationTrackRecorder s_TrackRecorder = new AnimationTrackRecorder();
static readonly List<UndoPropertyModification> s_UnprocessedMods = new List<UndoPropertyModification>();
static readonly List<UndoPropertyModification> s_ModsToProcess = new List<UndoPropertyModification>();
static AnimationTrack s_LastTrackWarning;
public const string kLocalPosition = "m_LocalPosition";
public const string kLocalRotation = "m_LocalRotation";
public const string kLocalEulerHint = "m_LocalEulerAnglesHint";
const string kRotationWarning = "You are recording with an initial rotation offset. This may result in a misrepresentation of euler angles. When recording transform properties, it is recommended to reset rotation prior to recording";
public static bool IsRecordingAnimationTrack { get; private set; }
internal static UndoPropertyModification[] ProcessMonoBehaviourModification(UndoPropertyModification[] modifications, WindowState state)
{
if (state == null || state.editSequence.director == null)
return modifications;
s_UnprocessedMods.Clear();
s_TrackRecorder.PrepareForRecord(state);
s_ModsToProcess.Clear();
s_ModsToProcess.AddRange(modifications.Reverse());
while (s_ModsToProcess.Count > 0)
{
var modification = s_ModsToProcess[s_ModsToProcess.Count - 1];
s_ModsToProcess.RemoveAt(s_ModsToProcess.Count - 1);
// grab the clip we need to apply to
var modifiedGO = GetGameObjectFromModification(modification);
var track = GetTrackForGameObject(modifiedGO, state);
if (track != null)
{
IsRecordingAnimationTrack = true;
double startTime = 0;
var clip = s_TrackRecorder.PrepareTrack(track, state, modifiedGO, out startTime);
if (clip == null)
{
s_ModsToProcess.Reverse();
return s_ModsToProcess.ToArray();
}
s_RecordState.activeAnimationClip = clip;
s_RecordState.activeRootGameObject = state.GetSceneReference(track);
s_RecordState.activeGameObject = modifiedGO;
s_RecordState.currentFrame = Mathf.RoundToInt((float)startTime);
EditorUtility.SetDirty(clip);
var toProcess = GatherRelatedModifications(modification, s_ModsToProcess);
var animator = s_RecordState.activeRootGameObject.GetComponent<Animator>();
var animTrack = track as AnimationTrack;
// update preview mode before recording so the correct values get placed (in case we modify offsets)
// Case 900624
UpdatePreviewMode(toProcess, modifiedGO);
// if this is the first position/rotation recording, copy the current position / rotation to the track offset
AddTrackOffset(animTrack, toProcess, clip, animator);
// same for clip mod clips being created
AddClipOffset(animTrack, toProcess, s_TrackRecorder.recordClip, animator);
// Check if we need to handle position/rotation offsets
var handleOffsets = animator != null && modification.currentValue != null &&
modification.currentValue.target == s_RecordState.activeRootGameObject.transform &&
HasOffsets(animTrack, s_TrackRecorder.recordClip);
if (handleOffsets)
{
toProcess = HandleEulerModifications(animTrack, s_TrackRecorder.recordClip, clip, s_RecordState.currentFrame * clip.frameRate, toProcess);
RemoveOffsets(modification, animTrack, s_TrackRecorder.recordClip, toProcess);
}
var remaining = AnimationRecording.Process(s_RecordState, toProcess);
if (remaining != null && remaining.Length != 0)
{
s_UnprocessedMods.AddRange(remaining);
}
if (handleOffsets)
{
ReapplyOffsets(modification, animTrack, s_TrackRecorder.recordClip, toProcess);
}
s_TrackRecorder.FinializeTrack(track, state);
IsRecordingAnimationTrack = false;
}
else
{
s_UnprocessedMods.Add(modification);
}
}
s_TrackRecorder.FinalizeRecording(state);
return s_UnprocessedMods.ToArray();
}
internal static bool IsPosition(UndoPropertyModification modification)
{
if (modification.currentValue != null)
return modification.currentValue.propertyPath.StartsWith(kLocalPosition);
else if (modification.previousValue != null)
return modification.previousValue.propertyPath.StartsWith(kLocalPosition);
return false;
}
internal static bool IsRotation(UndoPropertyModification modification)
{
if (modification.currentValue != null)
return modification.currentValue.propertyPath.StartsWith(kLocalRotation) ||
modification.currentValue.propertyPath.StartsWith(kLocalEulerHint);
if (modification.previousValue != null)
return modification.previousValue.propertyPath.StartsWith(kLocalRotation) ||
modification.previousValue.propertyPath.StartsWith(kLocalEulerHint);
return false;
}
// Test if this modification position or rotation
internal static bool IsPositionOrRotation(UndoPropertyModification modification)
{
return IsPosition(modification) || IsRotation(modification);
}
internal static void UpdatePreviewMode(UndoPropertyModification[] mods, GameObject go)
{
if (mods.Any(x => IsPositionOrRotation(x) && IsRootModification(x)))
{
bool hasPosition = false;
bool hasRotation = false;
foreach (var mod in mods)
{
EditorCurveBinding binding = new EditorCurveBinding();
if (AnimationUtility.PropertyModificationToEditorCurveBinding(mod.previousValue, go, out binding) != null)
{
hasPosition |= IsPosition(mod);
hasRotation |= IsRotation(mod);
AnimationMode.AddPropertyModification(binding, mod.previousValue, true);
}
}
// case 931859 - if we are only changing one field, all fields must be registered before
// any recording modifications
var driver = WindowState.previewDriver;
if (driver != null && AnimationMode.InAnimationMode(driver))
{
if (hasPosition)
{
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalPosition + ".x");
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalPosition + ".y");
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalPosition + ".z");
}
else if (hasRotation)
{
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalRotation + ".x");
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalRotation + ".y");
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalRotation + ".z");
DrivenPropertyManager.RegisterProperty(driver, go.transform, kLocalRotation + ".w");
}
}
}
}
internal static bool IsRootModification(UndoPropertyModification modification)
{
string path = string.Empty;
if (modification.currentValue != null)
path = modification.currentValue.propertyPath;
else if (modification.previousValue != null)
path = modification.previousValue.propertyPath;
return !path.Contains('/') && !path.Contains('\\');
}
// test if the clip has any position or rotation bindings
internal static bool ClipHasPositionOrRotation(AnimationClip clip)
{
if (clip == null || clip.empty)
return false;
var info = AnimationClipCurveCache.Instance.GetCurveInfo(clip);
for (var i = 0; i < info.bindings.Length; i++)
{
bool isPositionOrRotation =
info.bindings[i].type != null &&
typeof(Transform).IsAssignableFrom(info.bindings[i].type) &&
(
info.bindings[i].propertyName.StartsWith(kLocalPosition) ||
info.bindings[i].propertyName.StartsWith(kLocalRotation) ||
info.bindings[i].propertyName.StartsWith("localEuler")
);
if (isPositionOrRotation)
return true;
}
return false;
}
internal static TimelineAnimationUtilities.RigidTransform ComputeInitialClipOffsets(AnimationTrack track, UndoPropertyModification[] mods, Animator animator)
{
// take into account the track transform
var target = GetInitialTransform(mods, animator);
var trackToClip = TimelineAnimationUtilities.RigidTransform.identity;
if (track.trackOffset == TrackOffset.ApplyTransformOffsets)
trackToClip = TimelineAnimationUtilities.RigidTransform.Compose(track.position, track.rotation);
else if (track.trackOffset == TrackOffset.ApplySceneOffsets)
trackToClip = TimelineAnimationUtilities.RigidTransform.Compose(track.sceneOffsetPosition, Quaternion.Euler(track.sceneOffsetRotation));
target = TimelineAnimationUtilities.RigidTransform.Mul(TimelineAnimationUtilities.RigidTransform.Inverse(trackToClip), target);
// set the previous position in case the animation system adds a default key
SetPreviousPositionAndRotation(mods, animator, trackToClip.position, trackToClip.rotation);
return target;
}
internal static TimelineAnimationUtilities.RigidTransform GetInitialTransform(UndoPropertyModification[] mods, Animator animator)
{
var pos = Vector3.zero;
var rot = Quaternion.identity;
// if we are operating on the root, grab the transform from the undo
if (mods[0].previousValue.target == animator.transform)
{
GetPreviousPositionAndRotation(mods, ref pos, ref rot);
}
// otherwise we need to grab it from the root object, which is the one with the actual animator
else
{
pos = animator.transform.localPosition;
rot = animator.transform.localRotation;
}
// take into account the track transform
return TimelineAnimationUtilities.RigidTransform.Compose(pos, rot);
}
internal static void SetPreviousPositionAndRotation(UndoPropertyModification[] mods, Animator animator, Vector3 pos, Quaternion rot)
{
if (mods[0].previousValue.target == animator.transform)
{
SetPreviousPositionAndRotation(mods, pos, rot);
}
}
// If we are adding to an infinite clip, strip the objects position and rotation and set it as the clip offset
internal static void AddTrackOffset(AnimationTrack track, UndoPropertyModification[] mods, AnimationClip clip, Animator animator)
{
var copyTrackOffset = !track.inClipMode &&
!ClipHasPositionOrRotation(clip) &&
mods.Any(x => IsPositionOrRotation(x) && IsRootModification(x)) &&
animator != null;
if (copyTrackOffset)
{
// in scene offset mode, makes sure we have the correct initial transform set
if (track.trackOffset == TrackOffset.ApplySceneOffsets)
{
var rigidTransform = GetInitialTransform(mods, animator);
track.sceneOffsetPosition = rigidTransform.position;
track.sceneOffsetRotation = rigidTransform.rotation.eulerAngles;
SetPreviousPositionAndRotation(mods, animator, rigidTransform.position, rigidTransform.rotation);
}
else
{
var rigidTransform = ComputeInitialClipOffsets(track, mods, animator);
track.infiniteClipOffsetPosition = rigidTransform.position;
track.infiniteClipOffsetEulerAngles = rigidTransform.rotation.eulerAngles;
}
}
}
internal static void AddClipOffset(AnimationTrack track, UndoPropertyModification[] mods, TimelineClip clip, Animator animator)
{
if (clip == null || clip.asset == null)
return;
var clipAsset = clip.asset as AnimationPlayableAsset;
var copyClipOffset = track.inClipMode &&
clipAsset != null && !ClipHasPositionOrRotation(clipAsset.clip) &&
mods.Any(x => IsPositionOrRotation(x) && IsRootModification(x)) &&
animator != null;
if (copyClipOffset)
{
var rigidTransform = ComputeInitialClipOffsets(track, mods, animator);
clipAsset.position = rigidTransform.position;
clipAsset.rotation = rigidTransform.rotation;
}
}
internal static TimelineAnimationUtilities.RigidTransform GetLocalToTrack(AnimationTrack track, TimelineClip clip)
{
if (track == null)
return TimelineAnimationUtilities.RigidTransform.Compose(Vector3.zero, Quaternion.identity);
var trackPos = track.position;
var trackRot = track.rotation;
if (track.trackOffset == TrackOffset.ApplySceneOffsets)
{
trackPos = track.sceneOffsetPosition;
trackRot = Quaternion.Euler(track.sceneOffsetRotation);
}
var clipWrapper = clip == null ? null : clip.asset as AnimationPlayableAsset;
var clipTransform = TimelineAnimationUtilities.RigidTransform.Compose(Vector3.zero, Quaternion.identity);
if (clipWrapper != null)
{
clipTransform = TimelineAnimationUtilities.RigidTransform.Compose(clipWrapper.position, clipWrapper.rotation);
}
else
{
clipTransform = TimelineAnimationUtilities.RigidTransform.Compose(track.infiniteClipOffsetPosition, track.infiniteClipOffsetRotation);
}
var trackTransform = TimelineAnimationUtilities.RigidTransform.Compose(trackPos, trackRot);
return TimelineAnimationUtilities.RigidTransform.Mul(trackTransform, clipTransform);
}
// Checks whether there are any offsets applied to a clip
internal static bool HasOffsets(AnimationTrack track, TimelineClip clip)
{
if (track == null)
return false;
bool hasClipOffsets = false;
bool hasTrackOffsets = false;
var clipWrapper = clip == null ? null : clip.asset as AnimationPlayableAsset;
if (clipWrapper != null)
hasClipOffsets |= clipWrapper.position != Vector3.zero || clipWrapper.rotation != Quaternion.identity;
if (track.trackOffset == TrackOffset.ApplySceneOffsets)
{
hasTrackOffsets = track.sceneOffsetPosition != Vector3.zero || track.sceneOffsetRotation != Vector3.zero;
}
else
{
hasTrackOffsets = (track.position != Vector3.zero || track.rotation != Quaternion.identity);
if (!track.inClipMode)
hasClipOffsets |= track.infiniteClipOffsetPosition != Vector3.zero || track.infiniteClipOffsetRotation != Quaternion.identity;
}
return hasTrackOffsets || hasClipOffsets;
}
internal static void RemoveOffsets(UndoPropertyModification modification, AnimationTrack track, TimelineClip clip, UndoPropertyModification[] mods)
{
if (IsPositionOrRotation(modification))
{
var modifiedGO = GetGameObjectFromModification(modification);
var target = TimelineAnimationUtilities.RigidTransform.Compose(modifiedGO.transform.localPosition, modifiedGO.transform.localRotation);
var localToTrack = GetLocalToTrack(track, clip);
var trackToLocal = TimelineAnimationUtilities.RigidTransform.Inverse(localToTrack);
var localSpace = TimelineAnimationUtilities.RigidTransform.Mul(trackToLocal, target);
// Update the undo call values
var prevPos = modifiedGO.transform.localPosition;
var prevRot = modifiedGO.transform.localRotation;
GetPreviousPositionAndRotation(mods, ref prevPos, ref prevRot);
var previousRigidTransform = TimelineAnimationUtilities.RigidTransform.Mul(trackToLocal, TimelineAnimationUtilities.RigidTransform.Compose(prevPos, prevRot));
SetPreviousPositionAndRotation(mods, previousRigidTransform.position, previousRigidTransform.rotation);
var currentPos = modifiedGO.transform.localPosition;
var currentRot = modifiedGO.transform.localRotation;
GetCurrentPositionAndRotation(mods, ref currentPos, ref currentRot);
var currentRigidTransform = TimelineAnimationUtilities.RigidTransform.Mul(trackToLocal, TimelineAnimationUtilities.RigidTransform.Compose(currentPos, currentRot));
SetCurrentPositionAndRotation(mods, currentRigidTransform.position, currentRigidTransform.rotation);
modifiedGO.transform.localPosition = localSpace.position;
modifiedGO.transform.localRotation = localSpace.rotation;
}
}
internal static void ReapplyOffsets(UndoPropertyModification modification, AnimationTrack track, TimelineClip clip, UndoPropertyModification[] mods)
{
if (IsPositionOrRotation(modification))
{
var modifiedGO = GetGameObjectFromModification(modification);
var target = TimelineAnimationUtilities.RigidTransform.Compose(modifiedGO.transform.localPosition, modifiedGO.transform.localRotation);
var localToTrack = GetLocalToTrack(track, clip);
var trackSpace = TimelineAnimationUtilities.RigidTransform.Mul(localToTrack, target);
// Update the undo call values
var prevPos = modifiedGO.transform.localPosition;
var prevRot = modifiedGO.transform.localRotation;
GetPreviousPositionAndRotation(mods, ref prevPos, ref prevRot);
var previousRigidTransform = TimelineAnimationUtilities.RigidTransform.Mul(localToTrack, TimelineAnimationUtilities.RigidTransform.Compose(prevPos, prevRot));
SetPreviousPositionAndRotation(mods, previousRigidTransform.position, previousRigidTransform.rotation);
var currentPos = modifiedGO.transform.localPosition;
var currentRot = modifiedGO.transform.localRotation;
GetCurrentPositionAndRotation(mods, ref currentPos, ref currentRot);
var currentRigidTransform = TimelineAnimationUtilities.RigidTransform.Mul(localToTrack, TimelineAnimationUtilities.RigidTransform.Compose(currentPos, currentRot));
SetCurrentPositionAndRotation(mods, currentRigidTransform.position, currentRigidTransform.rotation);
modifiedGO.transform.localPosition = trackSpace.position;
modifiedGO.transform.localRotation = trackSpace.rotation;
}
}
// This will gather the modifications that modify the same property on the same object (rgba of a color, xyzw of a vector)
// Note: This will modify the list, removing any elements that match
static UndoPropertyModification[] GatherRelatedModifications(UndoPropertyModification toMatch, List<UndoPropertyModification> list)
{
var matching = new List<UndoPropertyModification> {toMatch};
for (var i = list.Count - 1; i >= 0; i--)
{
var undo = list[i];
if (undo.previousValue.target == toMatch.previousValue.target &&
DoesPropertyPathMatch(undo.previousValue.propertyPath, toMatch.previousValue.propertyPath))
{
matching.Add(undo);
list.RemoveAt(i);
}
}
return matching.ToArray();
}
// Grab the game object out of the modification object
static GameObject GetGameObjectFromModification(UndoPropertyModification mod)
{
// grab the GO this is modifying
GameObject modifiedGO = null;
if (mod.previousValue.target is GameObject)
modifiedGO = mod.previousValue.target as GameObject;
else if (mod.previousValue.target is Component)
modifiedGO = (mod.previousValue.target as Component).gameObject;
return modifiedGO;
}
// returns the level of the child in the hierarchy relative to the parent,
// or -1 if the child is not the parent or a descendent of it
static int GetChildLevel(GameObject parent, GameObject child)
{
var level = 0;
while (child != null)
{
if (parent == child)
break;
if (child.transform.parent == null)
return -1;
child = child.transform.parent.gameObject;
level++;
}
if (child != null)
return level;
return -1;
}
static bool DoesPropertyPathMatch(string a, string b)
{
return AnimationWindowUtility.GetPropertyGroupName(a).Equals(AnimationWindowUtility.GetPropertyGroupName(a));
}
internal static void GetPreviousPositionAndRotation(UndoPropertyModification[] mods, ref Vector3 position, ref Quaternion rotation)
{
var t = mods[0].previousValue.target as Transform;
if (t == null)
t = (Transform)mods[0].currentValue.target;
position = t.localPosition;
rotation = t.localRotation;
foreach (var mod in mods)
{
switch (mod.previousValue.propertyPath)
{
case kLocalPosition + ".x":
position.x = ParseFloat(mod.previousValue.value, position.x);
break;
case kLocalPosition + ".y":
position.y = ParseFloat(mod.previousValue.value, position.y);
break;
case kLocalPosition + ".z":
position.z = ParseFloat(mod.previousValue.value, position.z);
break;
case kLocalRotation + ".x":
rotation.x = ParseFloat(mod.previousValue.value, rotation.x);
break;
case kLocalRotation + ".y":
rotation.y = ParseFloat(mod.previousValue.value, rotation.y);
break;
case kLocalRotation + ".z":
rotation.z = ParseFloat(mod.previousValue.value, rotation.z);
break;
case kLocalRotation + ".w":
rotation.w = ParseFloat(mod.previousValue.value, rotation.w);
break;
}
}
}
internal static void GetCurrentPositionAndRotation(UndoPropertyModification[] mods, ref Vector3 position, ref Quaternion rotation)
{
var t = (Transform)mods[0].currentValue.target;
position = t.localPosition;
rotation = t.localRotation;
foreach (var mod in mods)
{
switch (mod.currentValue.propertyPath)
{
case kLocalPosition + ".x":
position.x = ParseFloat(mod.currentValue.value, position.x);
break;
case kLocalPosition + ".y":
position.y = ParseFloat(mod.currentValue.value, position.y);
break;
case kLocalPosition + ".z":
position.z = ParseFloat(mod.currentValue.value, position.z);
break;
case kLocalRotation + ".x":
rotation.x = ParseFloat(mod.currentValue.value, rotation.x);
break;
case kLocalRotation + ".y":
rotation.y = ParseFloat(mod.currentValue.value, rotation.y);
break;
case kLocalRotation + ".z":
rotation.z = ParseFloat(mod.currentValue.value, rotation.z);
break;
case kLocalRotation + ".w":
rotation.w = ParseFloat(mod.currentValue.value, rotation.w);
break;
}
}
}
// when making the previous position and rotation
internal static void SetPreviousPositionAndRotation(UndoPropertyModification[] mods, Vector3 pos, Quaternion rot)
{
foreach (var mod in mods)
{
switch (mod.previousValue.propertyPath)
{
case kLocalPosition + ".x":
mod.previousValue.value = pos.x.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalPosition + ".y":
mod.previousValue.value = pos.y.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalPosition + ".z":
mod.previousValue.value = pos.z.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".x":
mod.previousValue.value = rot.x.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".y":
mod.previousValue.value = rot.y.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".z":
mod.previousValue.value = rot.z.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".w":
mod.previousValue.value = rot.w.ToString(EditorGUI.kFloatFieldFormatString);
break;
}
}
}
internal static void SetCurrentPositionAndRotation(UndoPropertyModification[] mods, Vector3 pos, Quaternion rot)
{
foreach (var mod in mods)
{
switch (mod.previousValue.propertyPath)
{
case kLocalPosition + ".x":
mod.currentValue.value = pos.x.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalPosition + ".y":
mod.currentValue.value = pos.y.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalPosition + ".z":
mod.currentValue.value = pos.z.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".x":
mod.currentValue.value = rot.x.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".y":
mod.currentValue.value = rot.y.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".z":
mod.currentValue.value = rot.z.ToString(EditorGUI.kFloatFieldFormatString);
break;
case kLocalRotation + ".w":
mod.currentValue.value = rot.w.ToString(EditorGUI.kFloatFieldFormatString);
break;
}
}
}
internal static float ParseFloat(string str, float defaultVal)
{
float temp = 0.0f;
if (float.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out temp))
return temp;
return defaultVal;
}
internal static UndoPropertyModification[] HandleEulerModifications(AnimationTrack track, TimelineClip clip, AnimationClip animClip, float time, UndoPropertyModification[] mods)
{
if (mods.Any(x => x.currentValue.propertyPath.StartsWith(kLocalEulerHint) || x.currentValue.propertyPath.StartsWith(kLocalRotation)))
{
// if there is a rotational offsets, we need to strip the euler hints, since they are used by the animation recording system
// over the quaternion.
var localToTrack = GetLocalToTrack(track, clip);
if (localToTrack.rotation != Quaternion.identity)
{
if (s_LastTrackWarning != track)
{
s_LastTrackWarning = track;
Debug.LogWarning(kRotationWarning);
}
Transform transform = mods[0].currentValue.target as Transform;
if (transform != null)
{
var trackToLocal = TimelineAnimationUtilities.RigidTransform.Inverse(localToTrack);
// since the euler angles are going to be transformed, we do a best guess at a euler that gives the shortest path
var quatMods = mods.Where(x => !x.currentValue.propertyPath.StartsWith(kLocalEulerHint));
var eulerMods = FindBestEulerHint(trackToLocal.rotation * transform.localRotation, animClip, time, transform);
return quatMods.Union(eulerMods).ToArray();
}
return mods.Where(x => !x.currentValue.propertyPath.StartsWith(kLocalEulerHint)).ToArray();
}
}
return mods;
}
internal static IEnumerable<UndoPropertyModification> FindBestEulerHint(Quaternion rotation, AnimationClip clip, float time, Transform transform)
{
Vector3 euler = rotation.eulerAngles;
var xCurve = AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAnglesRaw.x"));
var yCurve = AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAnglesRaw.y"));
var zCurve = AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAnglesRaw.z"));
if (xCurve != null)
euler.x = xCurve.Evaluate(time);
if (yCurve != null)
euler.y = yCurve.Evaluate(time);
if (zCurve != null)
euler.z = zCurve.Evaluate(time);
euler = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(rotation, euler);
return new[]
{
PropertyModificationToUndoPropertyModification(new PropertyModification {target = transform, propertyPath = kLocalEulerHint + ".x", value = euler.x.ToString() }),
PropertyModificationToUndoPropertyModification(new PropertyModification {target = transform, propertyPath = kLocalEulerHint + ".y", value = euler.y.ToString() }),
PropertyModificationToUndoPropertyModification(new PropertyModification {target = transform, propertyPath = kLocalEulerHint + ".z", value = euler.z.ToString() })
};
}
}
}
| 412 | 0.910013 | 1 | 0.910013 | game-dev | MEDIA | 0.876126 | game-dev | 0.927479 | 1 | 0.927479 |
sigeer/RuaMS | 9,442 | src/Application.Resources/scripts/npc/1012100.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Athena Pierce
Bowman Job Advancement
Victoria Road : Bowman Instructional School (100000201)
*/
status = -1;
actionx = {"1stJob": false, "2ndjob": false, "3thJobI": false, "3thJobC": false};
job = 310;
spawnPnpc = false;
spawnPnpcFee = 7000000;
jobType = 3;
function start() {
if (parseInt(cm.getJobId() / 100) == jobType && cm.canSpawnPlayerNpc(GameConstants.getHallOfFameMapid(cm.getJob()))) {
spawnPnpc = true;
var sendStr = "你已经走了很长的路,才能达到你今天所拥有的权力、智慧和勇气,不是吗? 你觉得现在#r名人堂上哪一个NPC形象适合你#k? 你确定要这么做吗?";
if (spawnPnpcFee > 0) {
sendStr += " 我可以为你做,费用是 #b " + cm.numberWithCommas(spawnPnpcFee) + " 金币。#k";
}
cm.sendYesNo(sendStr);
} else {
if (cm.getJobId() == 0) {
actionx["1stJob"] = true;
cm.sendNext("所以你决定成为一个#rbowman#k?你知道吗,有一些标准要达到……#b你的等级至少应该是10级,至少有" + cm.getFirstJobStatRequirement(jobType) + "#k。让我看看。"); // thanks Vcoc for noticing a need to state and check requirements on first job adv starting message
} else if (cm.getLevel() >= 30 && cm.getJobId() == 300) {
actionx["2ndJob"] = true;
if (cm.haveItem(4031012)) {
cm.sendNext("哈哈...我知道你会轻松通过那个测试的。我承认,你是一个很棒的弓箭手。我会让你比现在强大得多。不过,在那之前...你需要选择给你的两条路中的一条。这对你来说会是一个艰难的决定,但是...如果有任何问题需要问,请尽管问吧。");
} else if (cm.haveItem(4031011)) {
cm.sendOk("去找#b#p1072002##k。");
cm.dispose();
} else {
cm.sendYesNo("嗯...自从上次见到你以来,你长大了许多。我再也看不到以前那个软弱的家伙,而是看起来更像一个弓箭手了。那么,你觉得呢?难道你不想变得更加强大吗?通过一个简单的测试,我就可以帮你实现。你想试试吗?");
}
} else if (actionx["3thJobI"] || (cm.getPlayer().gotPartyQuestItem("JB3") && cm.getLevel() >= 70 && cm.getJobId() % 10 == 0 && parseInt(cm.getJobId() / 100) == 3 && !cm.getPlayer().gotPartyQuestItem("JBP"))) {
actionx["3thJobI"] = true;
cm.sendNext("你来了。几天前,奥西里亚的#b#p2020010##k跟我谈到了你。我看到你对成为弓箭手职业的第三次转职很感兴趣。为了实现这个目标,我需要测试你的实力,看看你是否配得上这个晋升。在金银岛的深林中有一个开口,会带你通往一个秘密通道。一旦进入,你将面对我的分身。你的任务是打败她,并带着#b#t4031059##k回来。");
} else if (cm.getPlayer().gotPartyQuestItem("JBP") && !cm.haveItem(4031059)) {
cm.sendNext("请把#b#t4031059##k带给我。");
cm.dispose();
} else if (cm.haveItem(4031059) && cm.getPlayer().gotPartyQuestItem("JBP")) {
actionx["3thJobC"] = true;
cm.sendNext("干得好。你打败了我的分身,并安全地带回了#b#t4031059##k。你现在已经从物理角度证明了自己配得上进行第三次职业转职。现在你应该把这条项链交给在奥西里亚的#b#p2020011##k,以进行测试的第二部分。祝你好运。你会需要的。");
} else {
cm.sendOk("你选择得很明智。");
cm.dispose();
}
}
}
function action(mode, type, selection) {
status++;
if (mode == -1 && selection == -1) {
cm.dispose();
return;
} else if (mode == 0 && type != 1) {
status -= 2;
}
if (status == -1) {
start();
return;
} else {
if (spawnPnpc) {
if (mode > 0) {
if (cm.getMeso() < spawnPnpcFee) {
cm.sendOk("抱歉,您没有足够的金币购买在名人堂上的位置。");
cm.dispose();
return;
}
if (PlayerNPC.spawnPlayerNPC(GameConstants.getHallOfFameMapid(cm.getJob()), cm.getPlayer())) {
cm.sendOk("给你了!希望你会喜欢它。");
cm.gainMeso(-spawnPnpcFee);
} else {
cm.sendOk("抱歉,名人堂目前已满...");
}
}
cm.dispose();
return;
} else {
if (mode != 1 || status == 7 && type != 1 || (actionx["1stJob"] && status == 4) || (cm.haveItem(4031008) && status == 2) || (actionx["3thJobI"] && status == 1)) {
if (mode == 0 && status == 2 && type == 1) {
cm.sendOk("你知道没有其他选择……");
}
if (!(mode == 0 && type != 1)) {
cm.dispose();
return;
}
}
}
}
if (actionx["1stJob"]) {
if (status == 0) {
if (cm.getLevel() >= 10 && cm.canGetFirstJob(jobType)) {
cm.sendNextPrev("这是一个重要且最终的选择。你将无法回头。");
} else {
cm.sendOk("再多训练一会儿,直到你达到基本要求,我就可以教你成为一名#r弓箭手#k的方法。");
cm.dispose();
}
} else if (status == 1) {
if (cm.canHold(1452051) && cm.canHold(2070000)) {
if (cm.getJobId() == 0) {
cm.changeJobById(300);
cm.gainItem(1452051, 1);
cm.gainItem(2060000, 1000);
cm.resetStats();
}
cm.sendNext("好的,从现在开始,你就是我们的一员了!你将在...过着流浪者的生活,但要耐心等待,很快你就会过上好日子。好了,虽然不多,但我会传授给你一些我的能力... 哈啊啊啊!!");
} else {
cm.sendNext("清理一下你的背包,然后回来找我说话。");
cm.dispose();
}
} else if (status == 2) {
cm.sendNextPrev("你现在变得更强大了。而且你的所有物品栏都增加了槽位。确切地说,是一整行。自己去看看吧。我刚给了你一点 #bSP#k。当你在屏幕左下角打开 #b技能#k 菜单时,可以使用SP学习技能。不过要注意一点:你不能一次性全部提升。在学习了一些技能之后,你还可以获得一些特定的技能。");
} else if (status == 3) {
cm.sendNextPrev("现在提醒一下。一旦你做出选择,就不能改变主意,试图选择另一条道路。现在去吧,做一个骄傲的弓箭手。");
} else {
cm.dispose();
}
} else if (actionx["2ndJob"]) {
if (status == 0) {
if (cm.haveItem(4031012)) {
cm.sendSimple("好的,当你做出决定后,点击底部的[我会选择我的职业]。#b\r\n#L0#请解释一下成为猎人的意义。\r\n#L1#请解释一下成为弩弓手的意义。\r\n#L3#我会选择我的职业!");
} else {
cm.sendNext("做得好。你看起来很强壮,但我需要看看你是否真的足够强大来通过测试,这不是一个困难的测试,所以你会做得很好。拿着我的信先……确保你不要丢了它!");
if (!cm.isQuestStarted(100000)) {
cm.startQuest(100000);
}
}
} else if (status == 1) {
if (!cm.haveItem(4031012)) {
if (cm.canHold(4031010)) {
if (!cm.haveItem(4031010)) {
cm.gainItem(4031010, 1);
}
cm.sendNextPrev("请将这封信交给射手村附近的#b#p1072002##k。她正在代替我担任教练的工作。把信交给她,她会代替我测试你。祝你好运。");
cm.dispose();
} else {
cm.sendNext("请在你的背包中腾出一些空间。");
cm.dispose();
}
} else {
if (selection < 3) {
if (selection == 0) { //hunter
cm.sendNext("精通弓箭的弓箭手。\r\n\r\n在早期级别中,#b猎人#k的每分钟伤害输出更高,攻击速度更快,但略弱于弩弓手。#b猎人#k可以使用#r箭炸弹#k,这是一个略微较弱的攻击,可以使最多6个敌人被眩晕。");
} else if (selection == 1) { //crossbowman 弩弓手
cm.sendNext("精通弓弩的弩弓手。\r\n\r\n与猎人相比,弩弓手的攻击力随等级提高而增加。弩弓手可以使用更强大的攻击技能#r铁箭#k,该技能不会自动追踪敌人,但可以穿墙。");
}
status -= 2;
} else {
cm.sendSimple("现在... 你决定好了吗?请选择你想要在二转时选择的职业。#b\r\n#L0#猎人\r\n#L1#弩手");
}
}
} else if (status == 2) {
job += selection * 10;
cm.sendYesNo("所以你想要选择成为" + (job == 310 ? "#b猎人#k" : "#b弩弓手#k") + "进行第二次转职吗?你知道一旦在这里做出选择,就无法在第二次转职时选择其他职业了,对吧?");
} else if (status == 3) {
if (cm.haveItem(4031012)) {
cm.gainItem(4031012, -1);
}
cm.sendNext("好了,从现在开始你就是#b猎人#k了。#b猎人#k是聪明的一群,拥有惊人的视力,能够轻松地将箭射穿怪物的心脏……请每天都训练自己。我会帮助你变得比你现在更强大。");
if (cm.getJobId() != job) {
cm.changeJobById(job);
}
} else if (status == 4) {
cm.sendNextPrev("我刚刚给了你一本书,上面列出了你作为一个猎人或弩弓手可以获得的技能清单。此外,你的杂项物品栏也扩展了一行。你的最大生命值和魔法值也增加了。去检查一下,看看吧。");
} else if (status == 5) {
cm.sendNextPrev("我也给了你一点 #bSP#k。打开左下角的 #b技能菜单#k。你可以提升新获得的二级技能。不过要注意,你不能一次性提升它们。有些技能只有在学会其他技能后才能使用。记得要记住这一点。");
} else if (status == 6) {
cm.sendNextPrev((job == 310 ? "Hunter" : "Crossbowman") + " 你需要坚强。但请记住,你不能滥用这种权力,把它用在弱者身上。请正确地使用你的巨大力量,因为……为了让你正确地使用这种力量,这比仅仅变得更强要困难得多。在你更进一步之后,请找到我。我等着你。");
}
} else if (actionx["3thJobI"]) {
if (status == 0) {
if (cm.getPlayer().gotPartyQuestItem("JB3")) {
cm.getPlayer().removePartyQuestItem("JB3");
cm.getPlayer().setPartyQuestItemObtained("JBP");
}
cm.sendNextPrev("因为她是我的克隆,你可以预料到前方将会是一场艰难的战斗。他使用了许多特殊的攻击技能,与你以往所见的完全不同,你的任务是成功地与他一对一地战斗。在秘密通道中有一个时间限制,所以你必须在规定时间内打败他。祝你好运,希望你带着#b#t4031059##k。");
}
} else if (actionx["3thJobC"]) {
cm.getPlayer().removePartyQuestItem("JBP");
cm.gainItem(4031059, -1);
cm.gainItem(4031057, 1);
cm.dispose();
}
} | 412 | 0.793642 | 1 | 0.793642 | game-dev | MEDIA | 0.648729 | game-dev | 0.522705 | 1 | 0.522705 |
randomguy3725/MoonLight | 8,226 | src/main/java/net/minecraft/world/gen/feature/WorldGenSavannaTree.java | package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.BlockNewLeaf;
import net.minecraft.block.BlockNewLog;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class WorldGenSavannaTree extends WorldGenAbstractTree
{
private static final IBlockState field_181643_a = Blocks.log2.getDefaultState().withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.ACACIA);
private static final IBlockState field_181644_b = Blocks.leaves2.getDefaultState().withProperty(BlockNewLeaf.VARIANT, BlockPlanks.EnumType.ACACIA).withProperty(BlockLeaves.CHECK_DECAY, Boolean.FALSE);
public WorldGenSavannaTree(boolean p_i45463_1_)
{
super(p_i45463_1_);
}
public boolean generate(World worldIn, Random rand, BlockPos position)
{
int i = rand.nextInt(3) + rand.nextInt(3) + 5;
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 <= 256)
{
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j)
{
int k = 1;
if (j == position.getY())
{
k = 0;
}
if (j >= position.getY() + 1 + i - 2)
{
k = 2;
}
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l)
{
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1)
{
if (j >= 0 && j < 256)
{
if (!this.func_150523_a(worldIn.getBlockState(blockpos$mutableblockpos.set(l, j, i1)).getBlock()))
{
flag = false;
}
}
else
{
flag = false;
}
}
}
}
if (!flag)
{
return false;
}
else
{
Block block = worldIn.getBlockState(position.down()).getBlock();
if ((block == Blocks.grass || block == Blocks.dirt) && position.getY() < 256 - i - 1)
{
this.func_175921_a(worldIn, position.down());
EnumFacing enumfacing = EnumFacing.Plane.HORIZONTAL.random(rand);
int k2 = i - rand.nextInt(4) - 1;
int l2 = 3 - rand.nextInt(3);
int i3 = position.getX();
int j1 = position.getZ();
int k1 = 0;
for (int l1 = 0; l1 < i; ++l1)
{
int i2 = position.getY() + l1;
if (l1 >= k2 && l2 > 0)
{
i3 += enumfacing.getFrontOffsetX();
j1 += enumfacing.getFrontOffsetZ();
--l2;
}
BlockPos blockpos = new BlockPos(i3, i2, j1);
Material material = worldIn.getBlockState(blockpos).getBlock().getMaterial();
if (material == Material.air || material == Material.leaves)
{
this.func_181642_b(worldIn, blockpos);
k1 = i2;
}
}
BlockPos blockpos2 = new BlockPos(i3, k1, j1);
for (int j3 = -3; j3 <= 3; ++j3)
{
for (int i4 = -3; i4 <= 3; ++i4)
{
if (Math.abs(j3) != 3 || Math.abs(i4) != 3)
{
this.func_175924_b(worldIn, blockpos2.add(j3, 0, i4));
}
}
}
blockpos2 = blockpos2.up();
for (int k3 = -1; k3 <= 1; ++k3)
{
for (int j4 = -1; j4 <= 1; ++j4)
{
this.func_175924_b(worldIn, blockpos2.add(k3, 0, j4));
}
}
this.func_175924_b(worldIn, blockpos2.east(2));
this.func_175924_b(worldIn, blockpos2.west(2));
this.func_175924_b(worldIn, blockpos2.south(2));
this.func_175924_b(worldIn, blockpos2.north(2));
i3 = position.getX();
j1 = position.getZ();
EnumFacing enumfacing1 = EnumFacing.Plane.HORIZONTAL.random(rand);
if (enumfacing1 != enumfacing)
{
int l3 = k2 - rand.nextInt(2) - 1;
int k4 = 1 + rand.nextInt(3);
k1 = 0;
for (int l4 = l3; l4 < i && k4 > 0; --k4)
{
if (l4 >= 1)
{
int j2 = position.getY() + l4;
i3 += enumfacing1.getFrontOffsetX();
j1 += enumfacing1.getFrontOffsetZ();
BlockPos blockpos1 = new BlockPos(i3, j2, j1);
Material material1 = worldIn.getBlockState(blockpos1).getBlock().getMaterial();
if (material1 == Material.air || material1 == Material.leaves)
{
this.func_181642_b(worldIn, blockpos1);
k1 = j2;
}
}
++l4;
}
if (k1 > 0)
{
BlockPos blockpos3 = new BlockPos(i3, k1, j1);
for (int i5 = -2; i5 <= 2; ++i5)
{
for (int k5 = -2; k5 <= 2; ++k5)
{
if (Math.abs(i5) != 2 || Math.abs(k5) != 2)
{
this.func_175924_b(worldIn, blockpos3.add(i5, 0, k5));
}
}
}
blockpos3 = blockpos3.up();
for (int j5 = -1; j5 <= 1; ++j5)
{
for (int l5 = -1; l5 <= 1; ++l5)
{
this.func_175924_b(worldIn, blockpos3.add(j5, 0, l5));
}
}
}
}
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
private void func_181642_b(World p_181642_1_, BlockPos p_181642_2_)
{
this.setBlockAndNotifyAdequately(p_181642_1_, p_181642_2_, field_181643_a);
}
private void func_175924_b(World worldIn, BlockPos p_175924_2_)
{
Material material = worldIn.getBlockState(p_175924_2_).getBlock().getMaterial();
if (material == Material.air || material == Material.leaves)
{
this.setBlockAndNotifyAdequately(worldIn, p_175924_2_, field_181644_b);
}
}
}
| 412 | 0.813965 | 1 | 0.813965 | game-dev | MEDIA | 0.939032 | game-dev | 0.971293 | 1 | 0.971293 |
EQAditu/AdvancedCombatTracker | 105,288 | Localization/en-US/Advanced Combat Tracker.exe.InternalStrings.cs |
using System;
using System.Windows.Forms;
using Advanced_Combat_Tracker;
using System.Reflection;
[assembly: AssemblyTitle("ActLocalization-InternalStrings")]
[assembly: AssemblyDescription("A sample of an ACT plugin that changes localization strings.")]
[assembly: AssemblyVersion("287.0.0.0")]
namespace ActLocalization
{
public class InternalStrings
#if XMLINCLUDED
#else
: IActPluginV1 // Disabled if part of the ActLocalization csproj
#endif
{
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
{
EditLocalizations();
pluginStatusText.Text = "Plugin Started";
pluginScreenSpace.Parent.Controls.Remove(pluginScreenSpace);
}
internal static bool TryEditLocalization(string Key, string Value)
{
if (ActGlobals.ActLocalization.LocalizationStrings.ContainsKey(Key))
{
ActGlobals.ActLocalization.LocalizationStrings[Key].DisplayedText = Value;
return true;
}
ActGlobals.oFormActMain.WriteDebugLog(String.Format("Localization key ({0}) does not exist.", Key));
return false;
}
internal static void EditLocalizations()
{
TryEditLocalization("attackTypeTerm-all", "All"); // The localized term for an AttackType object that contains swings merged from other AttackTypes
TryEditLocalization("attackTypeTerm-melee", "Melee"); // auto-attack type, non-skill
TryEditLocalization("btnFeedbackSubmit-Text2", "Please restart to submit more."); //
TryEditLocalization("contextMenu-gridAppend", "Append \", {0}\""); //
TryEditLocalization("contextMenu-gridAppendLine", "Append \"<newline>\n{0}\""); //
TryEditLocalization("contextMenu-gridCopy", "Copy \"{0}\""); //
TryEditLocalization("damageTypeTerm-incDamage", "Incoming Damage"); //
TryEditLocalization("damageTypeTerm-incHealing", "Incoming Healing"); //
TryEditLocalization("damageTypeTerm-outDamage", "Outgoing Damage"); //
TryEditLocalization("damageTypeTerm-outHealing", "Outgoing Healing"); //
TryEditLocalization("data-dnumBlock", "Block"); //
TryEditLocalization("data-dnumDeath", "Death"); //
TryEditLocalization("data-dnumMiss", "Miss"); //
TryEditLocalization("data-dnumNoDamage", "No Damage"); //
TryEditLocalization("data-dnumParry", "Parry"); //
TryEditLocalization("data-dnumResist", "Resist"); //
TryEditLocalization("data-dnumRiposte", "Riposte"); //
TryEditLocalization("data-timerStringNone", "<None>"); //
TryEditLocalization("encounterData-defaultEncounterName", "Encounter"); //
TryEditLocalization("encounterTerm-merged", "Merged({0})"); //
TryEditLocalization("exportFormattingDesc-critheal%", "The percentage of heals that were critical."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-critheals", "The number of heals that were critical."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-crithit%", "The percentage of damaging attacks that were critical."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-crithits", "The number of damaging attacks that were critical."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-cures", "The total number of times the combatant cured or dispelled"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-custom", "Enter your custom text into the above text box before appending."); //
TryEditLocalization("exportFormattingDesc-damage", "The amount of damage from auto-attack, spells, CAs, etc done to other combatants."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-damage%", "This value represents the percent share of all damage done by allies in this encounter."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-damagetaken", "The total amount of damage this combatant received."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-deaths", "The total number of times this character was killed by another."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-dps", "The damage total of the combatant divided by their personal duration, formatted as 12.34"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-DPS", "The damage total of the combatatant divided by their personal duration, formatted as 12"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-duration", "The duration of the combatant or the duration of the encounter, displayed as mm:ss"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-DURATION", "The duration of the combatant or encounter displayed in whole seconds."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-extdps", "The damage total of the combatant divided by the duration of the encounter, formatted as 12.34 -- This is more commonly used than DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-EXTDPS", "The damage total of the combatant divided by the duration of the encounter, formatted as 12 -- This is more commonly used than DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-exthps", "The healing total of the combatant divided by the duration of the encounter, formatted as 12.34"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-EXTHPS", "The healing total of the combatant divided by the duration of the encounter, formatted as 12"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-healed", "The numerical total of all heals, wards or similar sourced from this combatant."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-healed%", "This value represents the percent share of all healing done by allies in this encounter."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-heals", "The total number of heals from this combatant."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-healstaken", "The total amount of healing this combatant received."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-hitfailed", "Any type of failed attack that was not a miss. This includes resists, reflects, blocks, dodging, etc."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-hits", "The number of attack attempts that produced damage. IE a spell successfully doing damage."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-kills", "The total number of times this character landed a killing blow."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-maxheal", "The highest single healing amount formatted as [Combatant-]SkillName-Healing#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-MAXHEAL", "The highest single healing amount formatted as [Combatant-]Healing#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-maxhealward", "The highest single healing/warding amount formatted as [Combatant-]SkillName-Healing#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-MAXHEALWARD", "The highest single healing/warding amount formatted as [Combatant-]Healing#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-maxhit", "The highest single damaging hit formatted as [Combatant-]SkillName-Damage#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-MAXHIT", "The highest single damaging hit formatted as [Combatant-]Damage#"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-misses", "The number of auto-attacks or CAs that produced a miss message."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-name", "The combatant's name."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME", "The combatant's name shortened to a number of characters after a colon, like: \"NAME:5\""); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME10", "The combatant's name, up to 10 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME11", "The combatant's name, up to 11 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME12", "The combatant's name, up to 12 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME13", "The combatant's name, up to 13 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME14", "The combatant's name, up to 14 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME15", "The combatant's name, up to 15 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME3", "The combatant's name, up to 3 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME4", "The combatant's name, up to 4 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME5", "The combatant's name, up to 5 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME6", "The combatant's name, up to 6 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME7", "The combatant's name, up to 7 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME8", "The combatant's name, up to 8 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-NAME9", "The combatant's name, up to 9 characters will be displayed."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-newline", "Formatting after this element will appear on a new line."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-powerdrain", "The amount of power this combatant drained from others."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-powerheal", "The amount of power this combatant replenished to others."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-swings", "The number of attack attempts. This includes any auto-attacks or abilities, also including resisted abilities that do no damage."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-tab", "Formatting after this element will appear in a relative column arrangement. (The formatting example cannot display this properly)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-threatdelta", "The amount of direct threat output relative to zero."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-threatstr", "The amount of direct threat output that was increased/decreased."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-title", "The title of the completed encounter. This may only be used in Allies formatting."); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-tohit", "The percentage of hits to swings as 12.34"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingDesc-TOHIT", "The percentage of hits to swings as 12"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-critheal%", "Critical Heal Percentage"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-critheals", "Critical Heal Count"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-crithit%", "Critical Hit Percentage"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-crithits", "Critical Hit Count"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-cures", "Cure or Dispel Count"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-custom", "Custom Text"); //
TryEditLocalization("exportFormattingLabel-damage", "Damage"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-damage%", "Damage %"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-damagetaken", "Damage Received"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-deaths", "Deaths"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-dps", "DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-DPS", "Short DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-duration", "Duration"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-DURATION", "Short Duration"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-extdps", "Encounter DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-EXTDPS", "Short Encounter DPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-exthps", "Encounter HPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-EXTHPS", "Short Encounter HPS"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-healed", "Healed"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-healed%", "Healed %"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-heals", "Heal Count"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-healstaken", "Healing Received"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-hitfailed", "Other Avoid"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-hits", "Hits"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-kills", "Killing Blows"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-maxheal", "Highest Heal"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-MAXHEAL", "Short Highest Heal"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-maxhealward", "Highest Heal/Ward"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-MAXHEALWARD", "Short Highest Heal/Ward"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-maxhit", "Highest Hit"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-MAXHIT", "Short Highest Hit"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-misses", "Misses"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-name", "Name"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME", "Short Name"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME10", "Name (10 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME11", "Name (11 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME12", "Name (12 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME13", "Name (13 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME14", "Name (14 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME15", "Name (15 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME3", "Name (3 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME4", "Name (4 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME5", "Name (5 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME6", "Name (6 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME7", "Name (7 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME8", "Name (8 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-NAME9", "Name (9 chars)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-newline", "New Line"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-powerdrain", "Power Drain"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-powerheal", "Power Replenish"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-swings", "Swings (Attacks)"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-tab", "Tab Character"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-threatdelta", "Threat Delta"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-threatstr", "Threat Increase/Decrease"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-title", "Encounter Title"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-tohit", "To Hit %"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("exportFormattingLabel-TOHIT", "Short To Hit %"); // DEPRECATED: Only old plugins use this.
TryEditLocalization("fileDialogDefault-actExport", "MultipleEncounters.act"); //
TryEditLocalization("fileDialogFilter-actExport", "ACT Binary File (*.act)|*.act"); //
TryEditLocalization("fileDialogFilter-exportHtml", "HTML File (*.html)|*.html"); //
TryEditLocalization("fileDialogFilter-gameLogs", "Game Log Files|{0}|Text Files (*.txt)|*.txt|Log Files (*.log)|*.log|Any File (*.*)|*.*"); //
TryEditLocalization("fileDialogFilter-plugins", "All Plugin Types|*.exe;*.dll;*.cs;*.vb;|Dynamic Link Library (*.dll)|*.dll|CSharp(C#) Source File (*.cs)|*.cs|Visual Basic.NET Source File (*.vb)|*.vb"); //
TryEditLocalization("fileDialogFilter-saveGraph", "Portable Network Graphics (*.png)|*.png"); //
TryEditLocalization("fileDialogFilter-saveTableImage", "Portable Network Graphics (*.png)|*.png"); //
TryEditLocalization("fileDialogFilter-triggerSound", "Waveform Files (*.wav)|*.wav"); //
TryEditLocalization("fileDialogFilter-xml", "XML File (*.xml)|*.xml"); //
TryEditLocalization("fileDialogTitle-actExport", "Export Encounter to Data File"); //
TryEditLocalization("fileDialogTitle-exportHtml", "Export Encounter to HTML"); //
TryEditLocalization("fileDialogTitle-importHistoryNoLogMatch", "Open log file containing {0} {1} to {2} {3}"); // Date range (to)
TryEditLocalization("fileDialogTitle-importSettingsXml", "Import Settings from XML"); //
TryEditLocalization("fileDialogTitle-saveGraph", "Save graph as..."); //
TryEditLocalization("fileDialogTitle-saveScreenshot", "Save ACT window screenshot..."); //
TryEditLocalization("fileDialogTitle-saveTableImage", "Save graph as..."); //
TryEditLocalization("fileDialogTitle-xmlEncounter", "Export Encounter to XML"); //
TryEditLocalization("graphAdv-termDps", "DPS"); //
TryEditLocalization("graphAdv-toolTip", "+{0} ({1} sec average)"); // sec = second
TryEditLocalization("graphAttackTypes-noDataError", "This sorting method has no available data."); //
TryEditLocalization("graphCombatant-toolTip", "+{0} ({1:#,0} sec average)"); // sec = second
TryEditLocalization("graphEncText-noDataError", "The table currently has no data to graph..."); //
TryEditLocalization("graphEncText-noDataSortingError", "No rows with compatible data to graph...\nTry sorting the table by another column."); //
TryEditLocalization("helpPanel-btnApplyDark", "This will apply some starting colors to use with pseudo-dark themes. For best results, restart ACT after applying. \n\nPS. WinForms will never theme well with what Microsoft offers."); //
TryEditLocalization("helpPanel-btnApplyDark2", "This will apply some starting colors to use with pseudo-dark themes. For best results, restart ACT after applying. \n\nPS. WinForms will never theme well with what Microsoft offers."); //
TryEditLocalization("helpPanel-btnExportUIBrowser", "Press this button to start a wizard allowing you to set the EQ2's web browser to ACT's encounter index and optionally extracting a browser UI replacement with a collapsable interface and controls for maximum screen space."); //
TryEditLocalization("helpPanel-btnImportFile", "To import encounters from your logfile, select the start and ending date with the choosers and select the log file to parse."); //
TryEditLocalization("helpPanel-btnOdbcDropTables", "This will perform the DROP command on each table ACT uses. This will delete all table data and remove the tables from the datasource."); //
TryEditLocalization("helpPanel-btnOdbcTestConnection", "This will attempt to log into the ODBC datasource specified in the Connection String."); //
TryEditLocalization("helpPanel-btnOdbcValidateTables", "This will make sure the ODBC datasource has the required tables and the tables have the required columns. If anything is missing, ACT will attempt to create or alter the tables. Success is required to do SQL exporting."); //
TryEditLocalization("helpPanel-btnResetAll", "This will reset all of the colors defined in the sub-pages and will require a restart of ACT."); //
TryEditLocalization("helpPanel-btnResetColors", "Resetting color/font settings will require ACT to be restarted."); //
TryEditLocalization("helpPanel-btnResetOdbcHacks", "This button will delete all ODBC hacks and replace them with a set of known hacks for various datasources, such as MSSQL, MS Access, Postgres..."); //
TryEditLocalization("helpPanel-cbAutoLoadLogs", "ACT should check every few seconds for existing logs to have been updated and switch to those currently used logs. (It will not check for new files automatically)"); //
TryEditLocalization("helpPanel-cbBlockisHit", "When checked, a hit that reports that it fails to inflict any damage will still be considered a Hit. When unchecked, only an attack that does damage is considered successful."); //
TryEditLocalization("helpPanel-cbCullAll", "When a new zone listing is created, ACT will keep the listed number of \"All\" zone-wide encounters and cull the older."); //
TryEditLocalization("helpPanel-cbCullCount", "When an encounter ends, normal encounters are culled to the listed number. This applies to encounters in any current or previous zone but will not affect \"All\" zone-wide encounters."); //
TryEditLocalization("helpPanel-cbCullCountIgnoreNoAlly", "Encounters with no allies, marked \"Encounter\" will not add to the count when determining the number of old encounters to cull."); //
TryEditLocalization("helpPanel-cbCullNoAlly", "When an encounter ends, all encounters (except for the last) labeled \"Encounter\" will be removed."); //
TryEditLocalization("helpPanel-cbCullOther", "When a new zone listing is created, ACT will keep the normal encounters of this many previous zones."); //
TryEditLocalization("helpPanel-cbCullTimer", "When an encounter ends, all encounters (except for \"All\" zone-wide encounters) older than this time limit will be removed."); //
TryEditLocalization("helpPanel-cbCurrentOdbc", "When in combat, ACT can export to a temporary table called current_table on your ODBC datasource every few seconds. Every export, the table will be deleted and refilled to reflect the current encounter. This option is only recommended if you have a very quick connection to your datasource."); //
TryEditLocalization("helpPanel-cbDisableIncrementalCaching", "This will disable the new incremental caching for encounter tables and mini parse exports. Only use this if real-time calculations are different than imported encounters."); //
TryEditLocalization("helpPanel-cbDoubleBufferLV", "When checked, ACT will attempt to enable minimal redrawing of the main table. Windows versions before WindowsXP normally do not have this ability and may cause undesired results."); //
TryEditLocalization("helpPanel-cbEncSilenceCut", "When enabled, an encounter's duration will be reduced when there are no hostile actions recorded for this many seconds. This setting should be lower than the above end encounter idle timer. This setting will not increase the duration of an enounter past its last hostile action."); //
TryEditLocalization("helpPanel-cbExFile", "At the end of combat, this option will export to a macro file something similar to what a clipboard export would look like. This file export is not restricted to 256 characters like the clipboard export, however it can only output 16 lines. Once the export is created, you can display the results by using the command:\n\n/do_file_commands act-export.txt\n\nYou can create an EQ2 macro to trigger this command. The macro file export will attempt to tabulate the data to make viewing it easier.\n\nYou must set the below option with what channel you wish to display the export to beforehand. Leaving the channel prefix blank will cause the macro file not to function unless the Text Only Formatting options prefix a channel to *every* line."); //
TryEditLocalization("helpPanel-cbExFileColumnAlign", "When enabled, the text export will be aligned into a table where each cell is padded to the length of the longest entry in that column. It is recommended you use a text formatter such as {NAME10} instead of {name} or that column may have excessive padding."); //
TryEditLocalization("helpPanel-cbExGraph", "When checked, HTML exports will include a main encounter graph."); //
TryEditLocalization("helpPanel-cbExHTML", "EQ2 comes with an integrated web browser based on FireFox. This can be used to view data exported by ACT while in fullscreen. The main encounter table will be exported as HTML to be viewed within the EQ2 HTML window. To access the HTML window, type: \"/browser\""); //
TryEditLocalization("helpPanel-cbExHTMLFTP", "If checked, when ACT exports EQ2 compatible HTML files, it will attempt to upload them to an FTP server of your choice. Make sure to test your settings before use."); //
TryEditLocalization("helpPanel-cbExOdbc", "This will enable SQL exporting via ODBC automatically when an encounter ends.\n\nTo use this feature, you need an ODBC driver to connect to your datasource and to fill out the Connection String with the remote host info. http://connectionstrings.com/ can help you make a connection string for your specific SQL datasource."); //
TryEditLocalization("helpPanel-cbExportBeep", "When checked, any exporting to the clipboard will cause a default system beep. This is a good indication of when an encounter is ended and there is new data to paste into EQ2."); //
TryEditLocalization("helpPanel-cbExportDurationWallTime", "For text exports such as duration/DURATION, usually the duration is calculated as EndTime-StartTime. This setting will allow the duration text export to use the LastEstimatedTime of the logfile as the EndTime of the encounter as long as it is in-combat. When out of combat, it will always use the encounter's EndTime."); //
TryEditLocalization("helpPanel-cbExportFilterSpace", "When checked, the Mini Parse window and clipboard exporting will exclude any combatants with spaces in their names. This will exclude most mobs such as 'a giant bat' or 'King Drayek', but not 'Anguis' or 'Frostbite'."); //
TryEditLocalization("helpPanel-cbExText", "Combatant summaries for the encounter will be exported to the clipboard after an encounter has ended. These summaries can be pasted into EQ2 by pressing Ctrl-V, and customized under General Options -> Text Only Formatting -> Clipboard Export Formatting."); //
TryEditLocalization("helpPanel-cbFrameBorders", "This setting will add colored panels to the edge of ACT's window to cover up the permanent gray borders of the tab controls."); //
TryEditLocalization("helpPanel-cbGCollectOnClear", "Enabling this will cause ACT to call GCCollect when clearing the encounters. Doing this will cause the Clear Encounters button to take longer and has been known to completely freeze ACT until restart. Only use this if you have problems with ACT never freeing memory over time."); //
TryEditLocalization("helpPanel-cbGermanMergeNames", "If enabled, combatants with grammatical changes such as: ruhiger Wachposten, ruhigen Wachpostens s, ruhigen Wachposten, ruhige Wachposten, ruhigen Wachposten en; will all show up as the same combatant. (Which ever showed up first in an encounter)"); //
TryEditLocalization("helpPanel-cbGExpEnd", "If 'You gain bonus experience for defeating the encounter!' is seen, the encounter will be considered ended. \n('You convert experience into achievement experience!' twice in a single second will also trigger this.)"); //
TryEditLocalization("helpPanel-cbGraphSoloInc", "When unchecked, solo combatant graphs will only show DPS lines for outgoing damage. When checked, incoming damage and incoming heal DPS lines will also be generated. (This will slightly increase the CPU time used to generate)"); //
TryEditLocalization("helpPanel-cbHtmlTimers", "When checked, ACT will export an HTML page displaying the current view of the Timers Window. The timer view will have the same dimensions as the original window, so resize it to your needs."); //
TryEditLocalization("helpPanel-cbIdleEnd", "If no combat actions such as attacking are observed for N number of seconds, the encounter will be considered ended."); //
TryEditLocalization("helpPanel-cbIdleTimerEnd", "A previously defaulted non-option, ACT can internally count seconds of inactivity instead of waiting on a log timestamp with a time sufficiently after the last combat action. If disabled, ACT will only end encounters based off of timestamps, and if no new log lines are parsed, its possible to never end an encounter *until* a new log timestamp is seen from EQ2. When enabled, the timer will not strictly end an encounter based off the timer, but two seconds after (in absense of log timestamps)."); //
TryEditLocalization("helpPanel-cbKillEnd", "When an allied combatant kills another, the encounter will be considered ended."); //
TryEditLocalization("helpPanel-cbLcdRoute", "When the ACT Clipboard Sharer is connected, using this option will route all LCD traffic to the G15 LCD on the connected computer's keyboard. This allows you to run ACT on a different computer than EQ2 and retain all LCD functionality."); //
TryEditLocalization("helpPanel-cbLongEncDuration", "Previously when only using timed encounter ending, heals being cast while the delay was counting down could affect the encounter's total duration, and therefore ExtDPS. If unchecked, heals after the last combat action will still be recorded up until the encounter is terminated, but will not affect the duration of the encounter."); //
TryEditLocalization("helpPanel-cbMiniClickThrough", "When enabled, mouse actions will not affect the Mini Window. When transparency is set, this allows you to both see through and click on things behind the window. Of course you can no longer move or close the window by normal means until click-through is disabled. NOTE: You may toggle this option by right-clicking the main window 'Show Mini' button."); //
TryEditLocalization("helpPanel-cbMiniColumnAlign", "When enabled, the text export will be aligned into a table where each cell is padded to the length of the longest entry in that column. The alignment is dependant on the font selected. It is recommended you use a text formatter such as {NAME10} instead of {name} or that column may have excessive padding."); //
TryEditLocalization("helpPanel-cbMultiDamageIsOne", "When enabled, an attack that has multiple damage types, such as \"300 crushing, 5 poison and 5 disease damage\" will show up as one total attack: 300/5/5 crushing/poison/disease, internally seen as 310. If disabled, each damage type will show up as an individual swing, IE three attacks: 300 crushing; 5 poison; 5 disease. Having a single attack show up as multiple will have consequences when calculating ToHit%."); //
TryEditLocalization("helpPanel-cbOnlyGraphAllies", "When checked, simple encounter bar graphs will only show your allies."); //
TryEditLocalization("helpPanel-cbOriginalLoglineCustomTriggers", "When enabled, the log lines passed to Custom Triggers are the original log lines instead of the version modified by plugins or without timestamps."); //
TryEditLocalization("helpPanel-cbOriginalLoglineViewLogs", "When enabled, the log lines appearing in View Logs are the original log lines instead of the version modified by plugins."); //
TryEditLocalization("helpPanel-cbPetIsMaster", "When checked, a pet will not show as its own entry, but as a spell under their master. When unchecked, the pet is considered a seperate combatant and has its own statistics unrelated to its master.\nThis setting is not retroactive, and will not combine or seperate a pet from its master if the encounter has already taken place. Only future encounters will be affected by this setting.\n\n\nSince LU19 and <Purpose tags> showing under a pet's name and not in log files, parsers cannot automatically see who a pet belongs to."); //
TryEditLocalization("helpPanel-cbRecalcWardedHits", "If enabled, no-damage hits or reduced damage hits immediately following a ward absorbtion will be increased by the absorbtion amount. Stoneskin's no-damage hits cannot be recalculated."); //
TryEditLocalization("helpPanel-cbRecordLogs", "When checked, ACT will record all log lines that appear during an encounter. You may then right click an encounter, select View Logs and view/search through them. Disabling this option will reduce memory usage by a bit less than 45% when compared to default settings. Exported ACT files will retain these recorded logs."); //
TryEditLocalization("helpPanel-cbRestrictToAll", "When checked, under each combatant, the only Damage Types entries that will be fully populated will be the ones marked (Ref) for Reference. Instead of 'Melee (Out)' showing All, crush, and slash it will only show All, which is a combination of crush/slash. Crush and slash will still be found under 'All Outgoing (Ref)' due to the (Ref) tag; the listing will simply be more crowded.\nEnabling this options willl reduce CPU usage by a bit less than 10% and reduce memory usage by a bit more than 10% when compared to default settings. Unchecked, this option will populate all entries in their logical listings."); //
TryEditLocalization("helpPanel-cbSExpEnd", "If 'You gain experience!' is seen, the encounter will be considered ended. \n('You convert experience into achievement experience!' will also trigger this.)"); //
TryEditLocalization("helpPanel-cbSqlSafeMode", "In safe mode, SQL commands will be sent one at a time and server response checked. Otherwise commands will be sent in 100 row batches, which while faster will be more problematic to debug."); //
TryEditLocalization("helpPanel-cbSwarmIsMaster", "When enabled, \"Дух огня (персонажа)\", \"Wässrige Horde des Character\" and other similarly named pets will have their attack damage added to their master instead of as their own named entry. Incoming attacks will *not* be redirected to their master's data."); //
TryEditLocalization("helpPanel-cbUnblockFiles", "Files downloaded by browsers will have a file attribute marking them to be blocked for direct execution by Windows. This setting will scan files and folders ACT tries to use for this filesystem flag and offer to unset the flag. This is very important for plugins."); //
TryEditLocalization("helpPanel-cbWebServerEnabled", "The ACT Web Interface is somewhat similar to the EQ2 HTML exports in appearance. Dissimilarly, the web interface is not made up of intermediary HTML files but generated HTML upon request. By default, you can see auto-updating pages of the current encounter table, Mini-Window text(with support for multiple presets), spell timers and a page that can browse through all of ACT's encounter data in memory. Context-menu reports based on that data are not currently available but plugins can be made to expand the web interface."); //
TryEditLocalization("helpPanel-cbWebServerShowReq", "If enabled, all HTTP requests will be shown. Otherwise things like auto-updating portions of pages or .css/.js files will be hidden (unless very large). One request to '/timers'(always shown) may initiate requests to '/ACT.js', '/ACT.css' and '/timers.body'(optionally shown) as well."); //
TryEditLocalization("helpPanel-cbWmpRequireInvoke", "Require sounds to be played on the UI thread. Do not use if ACT seems to freeze when expecting sound playback."); //
TryEditLocalization("helpPanel-cbZoneAllListing", "As the first encounter of each Zone branch, an \"All\" entry can exist which will combine all data from other encounters for that zone. As encounters progress within that zone, the All entry will be updated in real time. The All encounter entry will be identical to a merged encounter of all encounters within that zone.\n\nDisabling this option will reduce memory and CPU usage a bit more than 10% when compared to default options."); //
TryEditLocalization("helpPanel-ccDGAllyText", "The foreground color of combatant names that are marked as allies."); //
TryEditLocalization("helpPanel-ccDGPersonalBackcolor", "The background color of the main table row containing your combatant."); //
TryEditLocalization("helpPanel-ccEncLabel1", "The color for encounters where all enemies have been defeated."); //
TryEditLocalization("helpPanel-ccEncLabel2", "The color for encounters where the outcome was unknown."); //
TryEditLocalization("helpPanel-ccEncLabel3", "The color for encounters where all allies were defeated."); //
TryEditLocalization("helpPanel-ColorRestart", "Changing these colors will require ACT to be restarted."); //
TryEditLocalization("helpPanel-CurrentExports", "Checking this will create a custom HTML page with an auto updating graph or table. The page will auto-refresh at the user specified interval providing more or less a real-time view of the encounter."); //
TryEditLocalization("helpPanel-ddlGraphPriority", "This setting will change the priority of graph generation. All programs have a priority, usually Normal by default, and this priority defines how much CPU time should be given to the current task. If set to Lowest(Idle), graph generation will only take CPU time not used by other applications. If EQ2 is running, this will be next to nothing. Normal priority will give equal amounts of CPU time to ACT and any other task, such as EQ2. Above Normal(Not recommended) will give graph generation more priority than most other programs and may cause noticable stuttering in EQ2 momentary freezing. ACT's UI may also become unresponsive during graph generation."); //
TryEditLocalization("helpPanel-ddlLanguage", "This will change the parsing engine to another language or Spell Timers only mode."); //
TryEditLocalization("helpPanel-defaultText", "Mouse-over an item to view a more detailed explanation."); //
TryEditLocalization("helpPanel-ExFTPPASV", "If you are behind a router or have multiple NICs you may need to use Passive mode transfers. If the target FTP server is under the same conditions(a PASV only state), you must use Active mode. Two machines that require PASV mode cannot establish FTP transfers."); //
TryEditLocalization("helpPanel-gbOdbcHacks", "This section contains rules to modify all commands sent to the datasource if the connection string matches the rule. You may use the Reset button to pre-populate known rules for reference."); //
TryEditLocalization("helpPanel-GraphSize", "This will set the image dimentions of the graph in HTML exporting and EQ2 viewing."); //
TryEditLocalization("helpPanel-GraphType", "Select a graphing method for the main encounter display."); //
TryEditLocalization("helpPanel-invertLuminosity", "These settings will invert the luminosity value of colors that might be defined by plugins, such as main table cell colors. Perfect grays when inverted will be the same, but you may apply offsets to the inverted value to brighten/darken colors and add/remove color saturation as a whole. These settings will not change colors explicitly defined above."); //
TryEditLocalization("helpPanel-IO_ExportAct", "This feature will export a compressed binary file which can be later imported by ACT to recreate the encounter. If you wish to export more than one encounter as a single file, use the Show Checkboxes feature on the Main tab."); //
TryEditLocalization("helpPanel-IO_ExportHtml", "This feature will export the selected encounters into a single static HTML file which is then controlled by JavaScript and CSS."); //
TryEditLocalization("helpPanel-IO_ImportAct", "This feature is specifically for importing *.act files exported by ACT."); //
TryEditLocalization("helpPanel-IO_ImportClip", "Press the Import Clipboard button to import the clipboard contents as though importing a log file."); //
TryEditLocalization("helpPanel-IO_ImportLog", "Select the starting and end points before selecting the file to parse."); //
TryEditLocalization("helpPanel-IO_XmlFile", "This feature was added by user request. I don't know of any practical use for it."); //
TryEditLocalization("helpPanel-lblExFileLines", "ACT will only create macro files with up to this many commands. NOTE: EQ2 has server side filtering to prevent spam in public channels. No matter what, you cannot exceed 16 chat commands in a public channel within a short amount of time."); //
TryEditLocalization("helpPanel-lblExportSound", "The sound for when ACT creates clipboard exports, macro exports, etc either manually or immediately after combat."); //
TryEditLocalization("helpPanel-lblSplitFile", "As long as another program has not locked the file, ACT will attempt to rename the file with a date when opening or closing a file. (When over this size)"); //
TryEditLocalization("helpPanel-lblWebServerPort", "The listening port to accept HTTP requests from. If you use a non-standard port (80), clients must add that port to their URL notation like the following: http://127.0.0.1:80/"); //
TryEditLocalization("helpPanel-LogPriority", "This setting will change the priority of normal log parsing. All programs have a priority, usually Normal by default, and this priority defines how much CPU time should be given to the current task. If set to Lowest(Idle), log parsing will only take CPU time not used by other applications. If EQ2 is running, this will be next to nothing. Normal priority will give equal amounts of CPU time to ACT and any other task, such as EQ2.\n\nIf ACT seems unable to keep up with log parsing tasks while EQ2 is running, you may wish to set this to Above Normal.\n\nFor this setting to take effect, you must restart ACT or Close and Reopen the current log."); //
TryEditLocalization("helpPanel-Options_MiniParse", "The Mini Parse window is a small text only display of the current encounter. It may also show a graph if you click the red button in the corner. To change the included information, create a preset the new export format."); //
TryEditLocalization("helpPanel-Options_Odbc", "This section is for exporting ACT data into SQL datasources. ACT uses ODBC connectivity in order to connect to these datasources and the local machine must have an ODBC driver installed to communicate to the desired type of datasource."); //
TryEditLocalization("helpPanel-Options_SelectiveParsing", "The purpose of selective parsing is to restrict the data that appears. The list at the left decides which combatants are used for data/exports."); //
TryEditLocalization("helpPanel-Options_Sound", "This panel will configure the different sounds ACT will generally make for different events. Command sounds are when you interact with ACT by typing in a game, like '/act end' or '/e end'. Misc sounds are when ACT tries to randomly get your attention for a miscellaneous purpose. This could be an update or even an error playing a non-existent sound.\n\nThe bottom radio buttons change through what API ACT tries to make sounds through. Windows API is very basic for compatibility purposes. WMP is sufficient in most cases."); //
TryEditLocalization("helpPanel-Options_TableAttackType", "These are the columns that will appear in the Main tab tables when clicking on TreeView nodes such as 'crush' or 'Smite'. This table lists all of the individual combat actions of the selected skill name."); //
TryEditLocalization("helpPanel-Options_TableCombatant", "These are the columns that will appear in the Main tab tables when clicking on TreeView nodes such as 'PlayerName' or 'MobName'. This table lists all of the damage type categories of the combatant."); //
TryEditLocalization("helpPanel-Options_TableDamageType", "These are the columns that will appear in the Main tab tables when clicking on TreeView nodes such as 'Outgoing Damage' or 'Healed'. This table lists all of the skill names of the selected damage type category."); //
TryEditLocalization("helpPanel-Options_TableEnc", "These are the columns that will appear in the Main tab tables when clicking on TreeView nodes such as 'Mobname - [1:23] 12:01:02 PM'. This table lists all of the combatants of the selected encounter."); //
TryEditLocalization("helpPanel-Options_TableZone", "These are the columns that will appear in the Main tab tables when clicking on TreeView nodes such as 'Import/Merge [1]' or 'ZoneName [3] 12:00:00 PM'. This table lists all of the encounters of that node(Zone)."); //
TryEditLocalization("helpPanel-rbSParseFull", "Full selective parsing should only be used in small groups where there are other groups near by. When the encounter begins, the settings are locked to that encounter. Using this feature may cause the ExtDPS calculations to differ from other copies of ACT or other parsers depending on the limiting options they use. Once an encounter has taken place, you cannot add or remove combatants to it without reparsing that battle. Full selective parsing will create data gaps and should not be used while using ACT to analyze battles or statistics as it will not show a complete \"picture\" of the encounter."); //
TryEditLocalization("helpPanel-SampleType", "These settings affect how many DPS plots there are along the X-Axis. If an encounter is one minute long, and Fixed number of DPS samples(6) is selected, there will be six X-Axis plots in 10 second intervals. If DPS samples every 15 seconds is selected, there will be four DPS plots at 15 second intervals. Fixed number is useful for keeping a graph readable no matter how long the encounter, and fixed sample durations is useful for comparisons to other time lines."); //
TryEditLocalization("helpPanel-soundTts-correction", "Uses regular expressions to find parts of a TTS string and replaces them with a specified correction. Mostly this is used to correct pronunciation."); //
TryEditLocalization("helpPanel-soundTts-lblTtsMethod", "The currently used TTS engine method"); //
TryEditLocalization("helpPanel-soundTts-linkTtsCpl", "Opens the classic Text To Speech Control Panel applet. The Windows 10/11 Settings app only affects UWP apps, not ACT."); //
TryEditLocalization("helpPanel-soundTts-rbTtsSapiDirect", "Uses the Windows SAPI directly. This will have a different volume curve when compared to the other setting and other WAV sound files."); //
TryEditLocalization("helpPanel-soundTts-rbTtsSapiWav", "Uses temporary WAV files created by Windows SAPI. This method was originally created for low resource machines that could not play TTS reliably while playing a demanding CPU bound game."); //
TryEditLocalization("helpPanel-soundTts-TestTts", "Enter a text string to speak with the current rules and engine"); //
TryEditLocalization("helpPanel-tbActTitle", "This changes the title text of ACT's main window. {0} is replaced with Import/Export indicators. {1} is replaced with combat indicators. {2} is replaced with log activity indicators. {3} is replaced by the current zone name. {4} is replaced by the current log time. {5} is replaced by the currently estimated time.\n\nDefault: {0}{1}Advanced Combat Tracker{2} - {3} - Log Time: {4} (Est. {5})"); //
TryEditLocalization("helpPanel-tbCharName", "If a log file is open this setting is ignored; however if ACT is used as an offline parser only, this setting will be used to fill in your name instead of using 'YOU'."); //
TryEditLocalization("helpPanel-tbConvertXml", "You may paste a portion of ACT's configuration file in this textbox and convert it into a snippet. Someone copying this snippet and clicking the [Import XML] button in the corner will import the contained config settings."); //
TryEditLocalization("helpPanel-tbExFileName", "This export file name is a relative file path to the game folder or may be an absolute path."); //
TryEditLocalization("helpPanel-TextFormatAddPreset", "Save these format options to the drop down list."); //
TryEditLocalization("helpPanel-TextFormatAllies", "Allies formatting string. (First Line Format)"); //
TryEditLocalization("helpPanel-TextFormatAlliesOnly", "When checked, only combatants who have proven themselves allies in the encounter will be included in the export. This includes healing you or other proven allies, or attacking your foes. If you do not make any allies during the encounter, all combatants will be exported."); //
TryEditLocalization("helpPanel-TextFormatAlliesStats", "When checked, the totals of your allies will be prefixed to the normal export."); //
TryEditLocalization("helpPanel-TextFormatPlayers", "Per-player formatting string. (Repeating Format)"); //
TryEditLocalization("helpPanel-TextFormatPreset", "Replace the current formatters with a saved preset."); //
TryEditLocalization("helpPanel-TextFormatRemovePreset", "Remove the currently selected format from the drop down list."); //
TryEditLocalization("helpPanel-TextFormatSort", "The sorting method this formatting option will use."); //
TryEditLocalization("helpPanel-xmlShare", "This section is designed for importing small snippets of settings such as Custom Triggers or Spell Timers. Typically these snippets will be parsed from game chat but may also be copied from elsewhere and pasted.\n\nWhen an XML snippet is detected in chat, by default the character name and type of data will appear in the third(yellow) ListBox. You may then click on the data to review it in the TextBox to the right and either import or delete the entry.\n\nIf you wish to always import data from a particular character, you may enter their name into the TextBox above the yellow ListBox and click the above Add button. Similarly there is a list of characters to always ignore data from. You may temporarily disable an accept/reject entry by unchecking it or you may simply use the Remove button on either list.\n\nYou may possibly come across an XML snippet from another source made for this feature. Instead of having someone send it to you in a tell, you may paste it directly into the larger TextBox above the Import/Delete buttons. It will then appear as a custom entry allowing you to Import or Delete it.\n\nYou may create a snippet from your own data by going into either the Spell Timers options page or Custom Triggers tab, right-clicking the entry in the list and selecting Copy as Sharable XML. If sending in EQ2 chat, the XML snippet must be by itself with no other chat or spaces."); //
TryEditLocalization("helpPanel-xmlSubscription", "This section is for keeping up to date with external ACT settings. XML configuration files can be put on the web and upon startup or on demand, ACT can check these files for updates(based on the timestamp). ACT can be set to automatically import or notify the user of these updates.\n\nThe top ListBox will contain the external URLs of the files already being watched. To add an entry, enter the URL into the labeled TextBox, select an update option and click Add/Edit. As update options, you can have ACT check but ignore updated files, notify you of updates using a message box or automatically import the external XML file upon detected updates. The Query URL button will list the general contents of the URL, if valid, and list when it was marked changed. The View in browser link will open the URL in your default web browser.\n\nThe Check Now button will on demand check all of the URLs for changes and check-mark the updated files. If the URL has been updated but set to be ignored, it will be marked with a gray checkmark. You may manually check or uncheck an entry by clicking on it.\n\nThe Update Checked button will import all entries with a normal checkmark regardless of if they were detected as changed."); //
TryEditLocalization("htmlText-currentEncounter", "Current Encounter"); //
TryEditLocalization("htmlText-lastEnc", "Last Encounter"); //
TryEditLocalization("htmlText-lastUpdated", "Last Updated: "); //
TryEditLocalization("htmlText-return", "Return to Index"); //
TryEditLocalization("htmlText-timers", "Timers Window"); //
TryEditLocalization("ioExport", "Export Encounters"); //
TryEditLocalization("ioExportAct", "Export to an *.act File"); //
TryEditLocalization("ioExportHtml", "Export to an HTML Page"); //
TryEditLocalization("ioImport", "Import Encounters"); // Import/Export tab treeview
TryEditLocalization("ioImportAct", "Import an *.act File"); //
TryEditLocalization("ioImportClip", "Import the Clipboard"); //
TryEditLocalization("ioImportLog", "Import a Log File"); //
TryEditLocalization("ioOdbc", "Export to SQL/ODBC"); //
TryEditLocalization("ioXmlFile", "Export to an XML File"); //
TryEditLocalization("mergedEncounterTerm-all", "All"); // The localized term for the merged All encounter at the top of zone breakdowns
TryEditLocalization("messageBox-avoidanceCopyDetail", "\n\nDo you wish to copy this to the windows clipboard?"); //
TryEditLocalization("messageBox-clipboardNoText", "The clipboard cannot be converted to plain text data."); //
TryEditLocalization("messageBox-clipConnectError", "\n\nIs the specified computer running the ACT Clipboard Sharer application?\n\nDO NOT USE THIS FEATURE IF THE GAME AND ACT ARE RUNNING ON THE SAME SYSTEM"); //
TryEditLocalization("messageBox-cullHistory", "{0} of {1} total records deleted."); //
TryEditLocalization("messageBox-duplicatePlugin", "The plugin {0} appears to be loaded multiple times."); //
TryEditLocalization("messageBox-eq2FolderWizard", "Detected EQ2 path is:\n{0}\n\nIs this correct?"); //
TryEditLocalization("messageBox-eq2NotFound", "EverQuest2.exe was not found in this folder. If you are using an international version, you may need to select an 'LP_REGION_??_??' folder."); //
TryEditLocalization("messageBox-exportNoEncounters", "Please select an encounter in the treeview."); //
TryEditLocalization("messageBox-exportNoOptions", "Please select something to display in the export."); //
TryEditLocalization("messageBox-feedbackNoComments", "You did not enter any comments."); //
TryEditLocalization("messageBox-feedbackNoEmail", "You did not enter your email address. If you need technical support or help there will be no way to contact you. \nIf you are reporting a rare bug, without more information from you it may be impossible to fix.\n\nAre you sure you wish to leave your email blank?"); //
TryEditLocalization("messageBox-feedbackShort", "Your feedback seems to be very short. If you are reporting a problem, the more you describe it the better. If you do not sufficiently describe the problem, I must resort to guessing what your problem is... which may get no response at all.\n\nDo you wish to continue with sending the feedback?"); //
TryEditLocalization("messageBox-feedbackSuccess", "Feedback complete."); //
TryEditLocalization("messageBox-ftpConnectionTest", "ACT may become unresponsive during this test. Please wait at least 30 seconds while the test is performing, and allow access through firewall notifications if they appear."); //
TryEditLocalization("messageBox-ftpTestSuccess", "\n\n=============================\nThe test completed sucessfully.\n\n"); //
TryEditLocalization("messageBox-htmlNoFileAccess", "Could not write to required files.\n\n{0}"); //
TryEditLocalization("messageBox-importDateTimeFail", "Could not find the specified date range within the file."); //
TryEditLocalization("messageBox-importHistoryNoLogMatch", "Could not find a log file for your character that likely had the date range. Please find this file."); //
TryEditLocalization("messageBox-importParseError", "Encountered an unrecoverable error while parsing:\n{0}\nParse position: {1}\n\n{2}\n\nIgnore this error and continue?"); //
TryEditLocalization("messageBox-invalidRegex", "There was a problem with the regular expression syntax:\n{0}\n\nPlease click the Regular Expression link or visit the forums for more help on creating Regex matches."); //
TryEditLocalization("messageBox-localSecurityPolicy", "The application was disallowed to perform the operation due to security settings of the local machine.\nIf you are running this application from a networked computer, please copy and run it locally.\n\n"); //
TryEditLocalization("messageBox-noFileFound", "The specified path does not exist."); //
TryEditLocalization("messageBox-odbcDropTables", "This procedure will delete all ACT related table data and remove the tables from the database.\nOnce completed, this cannot be undone and the tables will have to be recreated before ACT can store data on them once again.\n\nAre you sure you wish to continue?"); //
TryEditLocalization("messageBox-openLogWizard", "\nIs the displayed log file the one you wish to open with ACT?"); //
TryEditLocalization("messageBox-openLogWizardNoFolder", "No logs folder exists within this folder. You must have logging enabled within EQ2 to use ACT. Type \"/log\" within EQ2 to determine the logging status."); //
TryEditLocalization("messageBox-openLogWizardNoLogs", "No logs seem to exist in this folder or subfolder. You must have logging enabled within EQ2 to use ACT. Type \"/log\" within EQ2 to determine the logging status."); //
TryEditLocalization("messageBox-playerRemoveError", "Please select a name in the list to remove."); //
TryEditLocalization("messageBox-pluginCompileError", "There were errors compiling the plugin source file.\n\nPlease refer to the Plugin Info panel for more information."); //
TryEditLocalization("messageBox-pluginImageError", "The selected file is either not a valid plugin for ACT or has been corrupted."); //
TryEditLocalization("messageBox-pluginInvalid", "This assembly does not have a class that implements ACT's plugin interface, or scanning the assembly threw an error."); //
TryEditLocalization("messageBox-removePlugin", "Are you sure you wish to remove plugin {0}?"); //
TryEditLocalization("messageBox-searchResults", "Search returned {0} results."); //
TryEditLocalization("messageBox-sortingColumnError", "Select a column entry to sort by."); //
TryEditLocalization("messageBoxText-abilityRedirectError", "Please fill in both the Ability and Into fields and select an ability type."); //
TryEditLocalization("messageBoxText-addCalcTimer", "The lowest calculated recast has been sent to the spell timer options. Do you wish to add/replace this timer now?"); //
TryEditLocalization("messageBoxText-AlreadyLoadedAssembly", "This file is already loaded into memory. You should restart ACT before proceeding."); //
TryEditLocalization("messageBoxText-colorRestart", "You should restart ACT to finalize these color changes."); //
TryEditLocalization("messageBoxText-combatantRenameError", "Please fill in both the Before and After fields."); //
TryEditLocalization("messageBoxText-ctBenchComplete1", "The baseline benchmark did not consume enough time to be useful. Please select another encounter that has more log lines available."); //
TryEditLocalization("messageBoxText-ctBenchComplete2", "Benchmarking complete.\n\nIdentify the Custom Triggers that are many times more expensive than the baseline for optimizations. Alternatively, restrict them to a specific zone if not already done."); //
TryEditLocalization("messageBoxText-ctBenchNoSelection", "Please select an encounter in the left-side TreeView."); //
TryEditLocalization("messageBoxText-ctBenchSmallSelection", "Please select an encounter with more than 1000 log line entries."); //
TryEditLocalization("messageBoxText-customTriggerDeleteMultiple", "Really delete {0} custom triggers under '{1}'?"); //
TryEditLocalization("messageBoxText-exFilePrefixBlank", "Leaving this blank field is dangerous and will result in macro files that will not function unless the used Clipboard Format properly prefixes channel commands to every line."); //
TryEditLocalization("messageBoxText-fatalUnhandledException", "An unhandled exception has occurred. ACT may close.\nPress Ctrl-C to copy this MessageBox.\n\n{0}"); //
TryEditLocalization("messageBoxText-getPlugins429", "The remote server returned a 429 status error.\n\nThis may mean you have tried to access this resource too many times recently. Please try again later."); //
TryEditLocalization("messageBoxText-getPluginsApplied", "The plugin has been added and started."); //
TryEditLocalization("messageBoxText-getPluginsAppliedZip", "From the ZIP, {0} plugin(s) have been added and started."); //
TryEditLocalization("messageBoxText-getPluginsApplyFail", "The downloaded file did not contain a plugin that could be loaded."); //
TryEditLocalization("messageBoxText-getPluginsUnknownFile", "The downloaded file was not of the expected type for a plugin."); //
TryEditLocalization("messageBoxText-importAbort", "Do you wish to abort the import process?"); //
TryEditLocalization("messageBoxText-noPluginPath", "The plugin file \"{0}\" cannot be found. Did you mean to use the Get Plugins dialog?"); //
TryEditLocalization("messageBoxText-pluginInternetBlocked", "{0}\n\n---\n\nSuggestion: The plugin ({1}) may be blocked from loading because it is marked as from the Internet. Please right-click the file, select Properties and Unblock the file.\n\nIf this plugin came with any other files, unblock them as well."); //
TryEditLocalization("messageBoxText-pluginWizParserAdded", "The parsing plugin has been added and started."); //
TryEditLocalization("messageBoxText-restartAct", "You must restart ACT to apply changes."); //
TryEditLocalization("messageBoxText-spellTimerDeleteMultiple", "Really delete {0} spell timers under '{1}'?"); //
TryEditLocalization("messageBoxText-startupWizEQ2", "Will ACT be used for EverQuest II?"); //
TryEditLocalization("messageBoxText-startupWizFF14", "Will ACT be used for Final Fantasy XIV?"); //
TryEditLocalization("messageBoxText-startupWizManualSelect", "Please manually select your game log file."); //
TryEditLocalization("messageBoxText-startupWizParserWarn", "Simple detection suggests that you may already have a parsing plugin enabled. Check the Plugins tab before adding another."); //
TryEditLocalization("messageBoxText-unblock1a", "The following {0} file(s) were downloaded from the Internet and are still blocked:\n\n{1}\n\nUnblock? Press [Cancel] to stop asking."); //
TryEditLocalization("messageBoxText-unblock1b", "{0} more files..."); // A count of additional blocked files not listed.
TryEditLocalization("messageBoxText-unblockFail", "Not all files could be unblocked. Try running ACT as admin.\n\n{0}"); //
TryEditLocalization("messageBoxText-viewLogsDisabled", "ACT currently is not allowed to store log lines with encounter objects.\n\nLook for an option called 'Record all log lines while parsing.' in the Misc options page."); //
TryEditLocalization("messageBoxText-xmlShareInvalid", "This feature is for importing XML Share snippets, only. If you wish to import an XML configuration file, use the Import button in Options -> Configuration Import/Export."); //
TryEditLocalization("messageboxText-xmlShareUnknown", "{0}: No XML Snippet Handler marked the snippet as consumed. Does this share type require a plugin?"); //
TryEditLocalization("messageBoxText-xmlSnippetNotUsed", "{0}: No XML Snippet Handler marked the snippet as used. This share type may require a plugin."); //
TryEditLocalization("messageBoxText-xmlSubsImportNoUpdates", "There are no external XML files that need to be updated."); //
TryEditLocalization("messageBoxText-xmlSubsImportQuestion1", "{0} -- is outdated.\n\n"); // {0} is a URL
TryEditLocalization("messageBoxText-xmlSubsImportQuestion2", "Warning: {0} -- is outdated but ignored.\n\n"); // {0} is a URL
TryEditLocalization("messageBoxText-xmlSubsImportQuestion3", "Import these now?"); //
TryEditLocalization("messageBoxText-xmlSubsUpdatesComplete", "{0} external XML file(s) have been imported."); //
TryEditLocalization("messageBoxTitle-abilityRedirectError", "Invalid Entry"); //
TryEditLocalization("messageBoxTitle-addCalcTimer", "Add Timer Now?"); //
TryEditLocalization("messageBoxTitle-avoidanceCopyDetail", "Per hit average damage avoided: {0}"); //
TryEditLocalization("messageBoxTitle-clipboardNoText", "Clipboard import failed"); //
TryEditLocalization("messageBoxTitle-clipConnectError", "Clipboard Connection Failed"); //
TryEditLocalization("messageBoxTitle-combatantRenameError", "Invalid Entry"); //
TryEditLocalization("messageBoxTitle-ctBenchComplete", "Complete"); //
TryEditLocalization("messageBoxTitle-ctBenchInvalid", "Invalid Selection"); //
TryEditLocalization("messageBoxTitle-cullHistory", "Cull History"); //
TryEditLocalization("messageBoxTitle-customTriggerDeleteMultiple", "Delete multiple triggers?"); //
TryEditLocalization("messageBoxTitle-duplicatePlugin", "Duplicate Plugin"); //
TryEditLocalization("messageBoxTitle-eq2FolderWizard", "Detected EQ2 Folder"); //
TryEditLocalization("messageBoxTitle-eq2NotFound", "Could not confirm folder selection"); //
TryEditLocalization("messageBoxTitle-error", "Error"); //
TryEditLocalization("messageBoxTitle-exFilePrefixBlank", "DoFileCommands Channel Prefix"); //
TryEditLocalization("messageBoxTitle-exportNoEncounters", "Nothing to export"); //
TryEditLocalization("messageBoxTitle-fatalUnhandledException", "Fatal Error - Unhandled Exception"); //
TryEditLocalization("messageBoxTitle-feedbackFail", "Feedback not submitted"); //
TryEditLocalization("messageBoxTitle-feedbackNoConnect", "Connection to feedback server failed"); //
TryEditLocalization("messageBoxTitle-feedbackNoSend", "Sending feedback data failed"); //
TryEditLocalization("messageBoxTitle-feedbackWarning", "Feedback Warning"); //
TryEditLocalization("messageBoxTitle-fileError", "File Unavailable"); //
TryEditLocalization("messageBoxTitle-ftpTestFail", "Test incomplete"); //
TryEditLocalization("messageBoxTitle-ftpTestSuccess", "Test complete"); //
TryEditLocalization("messageBoxTitle-getPluginsApplied", "Plugin Applied"); //
TryEditLocalization("messageBoxTitle-getPluginsApplyFail", "Plugin Load Failure"); //
TryEditLocalization("messageBoxTitle-getPluginsApplyFail2", "Error applying plugin"); //
TryEditLocalization("messageBoxTitle-getPluginsError1", "Error retrieving plugin list"); //
TryEditLocalization("messageBoxTitle-getPluginsUnknownFile", "Unknown file type"); //
TryEditLocalization("messageBoxTitle-historyDatabase", "History Database"); //
TryEditLocalization("messageBoxTitle-htmlNoFileAccess", "File Access Denied"); //
TryEditLocalization("messageBoxTitle-importAbort", "Abort?"); //
TryEditLocalization("messageBoxTitle-importFail", "Parse failed"); //
TryEditLocalization("messageBoxTitle-importParseError", "Parsing Failed"); //
TryEditLocalization("messageBoxTitle-invalidRegex", "Invalid Regular Expression"); //
TryEditLocalization("messageBoxTitle-loadError", "Load Error"); //
TryEditLocalization("messageBoxTitle-localSecurityPolicy", "Security Exception"); //
TryEditLocalization("messageBoxTitle-noFileFound", "File Not Found"); //
TryEditLocalization("messageBoxTitle-noPluginPath", "Invalid Browse Path"); //
TryEditLocalization("messageBoxTitle-odbcDropTables", "ACT ODBC database removal"); //
TryEditLocalization("messageBoxTitle-odbcHackError", "Could not add OdbcHack"); //
TryEditLocalization("messageBoxTitle-odbcQueryError", "ODBC Connection Query Failed"); //
TryEditLocalization("messageBoxTitle-openLogWizard", "Detected log file"); //
TryEditLocalization("messageBoxTitle-openLogWizardNoFolder", "No logs folder"); //
TryEditLocalization("messageBoxTitle-openLogWizardNoLogs", "No logfiles found"); //
TryEditLocalization("messageBoxTitle-playerRemoveError", "No Selection"); //
TryEditLocalization("messageBoxTitle-pluginCompileError", "Compile Error"); //
TryEditLocalization("messageBoxTitle-pluginImageError", "Bad image format"); //
TryEditLocalization("messageBoxTitle-pluginInitFail", "Plugin Initialization Failed"); //
TryEditLocalization("messageBoxTitle-pluginInvalid", "Invalid Plugin"); //
TryEditLocalization("messageBoxTitle-pluginWizTitleError", "Could not retrieve plugin titles"); //
TryEditLocalization("messageBoxTitle-removePlugin", "Remove Plugin?"); //
TryEditLocalization("messageBoxTitle-restartAct", "Restart"); //
TryEditLocalization("messageBoxTitle-searchResults", "Search Complete"); //
TryEditLocalization("messageBoxTitle-serverStartError", "Could not start the server"); //
TryEditLocalization("messageBoxTitle-sortingColumnError", "Nothing Selected"); //
TryEditLocalization("messageBoxTitle-spellTimerDeleteMultiple", "Delete multiple spell timers?"); //
TryEditLocalization("messageBoxTitle-startupLogError", "Error loading last log file"); //
TryEditLocalization("messageBoxTitle-startupWizEQ2", "EQ2?"); //
TryEditLocalization("messageBoxTitle-startupWizFF14", "FFXIV?"); //
TryEditLocalization("messageBoxTitle-startupWizManualSelect", "Select log file"); //
TryEditLocalization("messageBoxTitle-startupWizParserWarn", "Plugin event in-use"); //
TryEditLocalization("messageBoxTitle-unblock", "Unblock files?"); //
TryEditLocalization("messageBoxTitle-unblockFail", "Unblock Failure"); //
TryEditLocalization("messageBoxTitle-updateAct", "Update?"); //
TryEditLocalization("messageBoxTitle-updateCheckFail", "ACT version check failed"); //
TryEditLocalization("messageBoxTitle-updateError", "Error Updating"); //
TryEditLocalization("messageBoxTitle-viewLogsDisabled", "Log recording disabled"); //
TryEditLocalization("messageBoxTitle-xmlPrefError", "XML Preferences Error"); //
TryEditLocalization("messageboxTitle-xmlShareError", "Error adding XML Share"); //
TryEditLocalization("messageBoxTitle-xmlShareError", "Error parsing XML Share"); //
TryEditLocalization("messageBoxTitle-xmlSnippetError", "Error adding XML Share"); //
TryEditLocalization("messageBoxTitle-xmlSubsImportQuestion", "XML Subscriptions"); //
TryEditLocalization("messageBoxTitle-xmlSubsUpdatesComplete", "Updates Complete"); //
TryEditLocalization("messageBox-updateAct", "This will close the program and start the update.\nDo you wish to continue?"); //
TryEditLocalization("messageBox-updateCheckFail", "Unable to obtain version info from web.\n"); //
TryEditLocalization("messageBox-xmlPrefLoadError", "The XML settings file may be corrupt or unusable. Consider loading a backup from 'Configuration Import/Export' options."); //
TryEditLocalization("messageBox-xmlReadError", "Error while parsing XML settings: Line #{0} ({1})\n{2}\n\n Attempting default setting"); // A non-syntax error when reading XML setting files
TryEditLocalization("messageBox-xmlSyntaxError", "The XML settings file may be corrupt or unusable. Loading defaults where applicable.\n{0}"); // The XML file was not parsable
TryEditLocalization("notifText-clipboardReadFail", "Could not get text from the clipboard..."); //
TryEditLocalization("notifText-oldSslError", "This version of Windows cannot create a secure channel to download plugins/updates. You will need to download this file manually.\n\nWould you like to open your default browser to the file download?"); //
TryEditLocalization("notifText-ongoingDownload", "There is an ongoing download that is taking longer than expected."); //
TryEditLocalization("notifText-unknownAssembly", "The following assemblies were not recognized. If they are plugins or from plugins, they should be deleted or moved to another folder to avoid \"wrong version\" load issues.\n\n{0}"); //
TryEditLocalization("notifText-UnzipError", "The following file could not be extracted: {0}"); //
TryEditLocalization("notifText-windowOutOfBounds", "{0}({1}) was found out of bounds of all displays and could not be restored to its old location/size."); //
TryEditLocalization("notifText-xmlShareAdded", "A ({0}) from ({1}) has been added to ACT."); //
TryEditLocalization("notifText-xmlShareDetected", "A ({0}) from ({1}) has been detected in the log file.\n\nWould you like to import this to ACT?\n\n\n\n\n[Also in Options -> Configuration Import/Export -> XML Share Snippets]"); //
TryEditLocalization("notifText-xmlSnippetError", "There was an unexpected error importing this XML snippet.\n\n{0}"); //
TryEditLocalization("notifText-xmlSnippetIncomplete", "The shared XML seems to be missing required attributes to be imported"); //
TryEditLocalization("notifText-xmlSnippetNotHandled", "The XML Snippet was not marked as handled. Does this share type require a plugin?"); //
TryEditLocalization("notifTitle-clipboardReadFail", "Clipboard Error"); //
TryEditLocalization("notifTitle-imageSaveException", "Could not save image."); //
TryEditLocalization("notifTitle-oldSslError", "Unable to Download"); //
TryEditLocalization("notifTitle-ongoingDownload", "Ongoing Download ({0}%)"); //
TryEditLocalization("notifTitle-unknownAssembly", "Unknown assemblies in ACT's folder. (Click Show to open folder)"); //
TryEditLocalization("notifTitle-UnzipError", "Unzip error"); //
TryEditLocalization("notifTitle-webserverError", "Webserver error"); //
TryEditLocalization("notifTitle-webserverException", "Webserver closed"); //
TryEditLocalization("notifTitle-windowOutOfBounds", "Window Out of Bounds"); //
TryEditLocalization("notifTitle-xmlShareAdded", "ACT XML Share"); //
TryEditLocalization("notifTitle-xmlSnippetError", "XML Share error"); //
TryEditLocalization("notifTitle-xmlSnippetIncomplete", "XML Share incomplete"); //
TryEditLocalization("notifTitle-xmlSnippetNotHandled", "XML Share not handled"); //
TryEditLocalization("opColorFont", "Color and Font Settings"); //
TryEditLocalization("opColorGraphing", "Graphing"); //
TryEditLocalization("opColorMisc", "Miscellaneous"); //
TryEditLocalization("opColorUserInterface", "Main User Interface"); //
TryEditLocalization("opDataCorrection", "Data Correction"); //
TryEditLocalization("opDataCorrectionMisc", "Miscellaneous"); //
TryEditLocalization("opDataCorrectionRedirect", "Ability Redirect"); //
TryEditLocalization("opDataCorrectionRename", "Combatant Rename"); //
TryEditLocalization("opEncCulling", "Encounter Culling"); //
TryEditLocalization("opFileHTML", "HTML File Generation"); //
TryEditLocalization("opGraphing", "Graphing"); //
TryEditLocalization("opImportExport", "Configuration Import/Export"); //
TryEditLocalization("opMainTable", "Main Table/Encounters"); //
TryEditLocalization("opMainTableGen", "General"); //
TryEditLocalization("opMiniParse", "Mini Parse Window"); //
TryEditLocalization("opMisc", "Miscellaneous"); // Options tab treeview
TryEditLocalization("opOdbc", "ODBC (SQL)"); //
TryEditLocalization("opOutputDisplay", "Output Display"); //
TryEditLocalization("opSelectiveParsing", "Selective Parsing"); //
TryEditLocalization("opSound", "Sound Settings"); //
TryEditLocalization("opSoundTts", "Text to Speech"); //
TryEditLocalization("opTableAttackType", "AttackType View Options"); //
TryEditLocalization("opTableCombatant", "Combatant View Options"); //
TryEditLocalization("opTableDamageType", "DamageType View Options"); //
TryEditLocalization("opTableEncounter", "Encounter View Options"); //
TryEditLocalization("opTableZone", "Zone View Options"); //
TryEditLocalization("opTextExports", "Text Export Settings"); //
TryEditLocalization("opWebServer", "ACT Web Server"); //
TryEditLocalization("opXmlShare", "XML Share Snippets"); //
TryEditLocalization("opXmlSubs", "XML Config Subscriptions"); //
TryEditLocalization("sliderText-badPluginLocation", "{0} should not be loaded from ACT's installation folder. It may cause file locking issues or other hard to diagnose problems. Please move it to a sub-folder or other location such as %APPDATA%\Advanced Combat Tracker\Plugins\."); //
TryEditLocalization("sliderText-logFileTimeError", "This log file is not valid for the current parsing plugin. (It cannot read the timestamps)\n\nPlease verify that you have the correct parsing plugin enabled and *only* one parsing plugin enabled."); //
TryEditLocalization("sliderText-oldLog", "The currently open log file has not been modified for over a week. Please ensure /log is on in-game and you have selected the correct log file."); //
TryEditLocalization("sliderText-pluginRestart", "You should restart ACT to apply the new plugin load order."); //
TryEditLocalization("sliderTitle-badPluginLocation", "Bad Plugin Location"); //
TryEditLocalization("sliderTitle-oldLog", "Old Log File"); //
TryEditLocalization("specialAttackTerm-increase", "Increase"); // One possible use is threat increase
TryEditLocalization("specialAttackTerm-killing", "Killing"); //
TryEditLocalization("specialAttackTerm-melee", "melee"); //
TryEditLocalization("specialAttackTerm-none", "None"); // What appears in the Special column of an attack when the attack is normal
TryEditLocalization("specialAttackTerm-nonMelee", "non-melee"); //
TryEditLocalization("specialAttackTerm-unknown", "unknown"); //
TryEditLocalization("specialAttackTerm-wardAbsorb", "Absorption"); //
TryEditLocalization("specialAttackTerm-warded", "warded"); //
TryEditLocalization("tooltip-regexWildcardWarn", "Be careful about using wildcards like .* without need."); //
TryEditLocalization("trayButton-benchShow", "Show Benchmarks"); //
TryEditLocalization("trayButton-continue", "Continue"); //
TryEditLocalization("trayButton-ignore", "Ignore For Now"); //
TryEditLocalization("trayButton-ignoreRestart", "Ignore"); //
TryEditLocalization("trayButton-never", "Never ask again"); //
TryEditLocalization("trayButton-no", "No"); //
TryEditLocalization("trayButton-notNow", "Not now"); //
TryEditLocalization("trayButton-ok", "OK"); //
TryEditLocalization("trayButton-openActLog", "Open error log"); //
TryEditLocalization("trayButton-openLogs", "Open Logs Folder"); //
TryEditLocalization("trayButton-restartAct", "Restart"); //
TryEditLocalization("trayButton-skip", "Skip"); //
TryEditLocalization("trayButton-yes", "Yes"); //
TryEditLocalization("trayText-ctBench2", "Custom Trigger log parsing has been behind for 10 seconds. You may need to add more Custom Trigger threads in the Options page or optimize your current Custom Triggers to be more effiecient.\n\nWould you like to open the Custom Trigger Benchmark to identify problematic Custom Triggers?"); //
TryEditLocalization("trayText-encClearGcCollect", "{0:0,0} bytes allocated difference"); //
TryEditLocalization("trayText-eventExceptions1", "In the last minute, these plugins caused exceptions in event handlers:\n"); //
TryEditLocalization("trayText-eventExceptions2", "{0} [{1} time(s)]"); //
TryEditLocalization("trayText-findZoneBusy", "Finding the zone name in the log file appears to be taking a long time. Do you wish to skip scanning?\n\n{0} {1:0,0} bytes"); //
TryEditLocalization("trayText-globalMutex", "There is already another running copy of ACT. You should close ALL running copies and restart ACT.\n\nYou may disable this warning by adding \n-skipmutex to the commandline parameters. You may block new instances by adding -onlyone."); //
TryEditLocalization("trayText-LinuxConfigurationErrors", "A subset of Linux users cannot make web requests in ACT due to an app.config setting that is considered \"unrecognized\". This configuration helps support HiDPI displays but is otherwise unnecessary.\n\nWould you like to remove this configuration?"); //
TryEditLocalization("trayText-parsingBusy", "Log line parsing has been behind for 10 seconds. A plugin subscribed to BeforeLogLine/OnLogLine may be processing synchronously and taking too long."); //
TryEditLocalization("trayText-restartACT", "Restarting ACT is required to complete changes. \n\n{0}"); //
TryEditLocalization("trayText-xmlPrefErrorCount", "There were {0} errors encountered while loading settings.\nIf you just changed ACT versions, these errors may be a one-time result of ACT settings changing names/locations."); //
TryEditLocalization("trayTitle-ctBench", "Custom Triggers lagging behind"); //
TryEditLocalization("trayTitle-eventUnhandledException", "Event Handler Unhandled Exceptions"); //
TryEditLocalization("trayTitle-findZoneBusy", "Scanning Log File"); //
TryEditLocalization("trayTitle-globalMutex", "Multiple Instances"); //
TryEditLocalization("trayTitle-LinuxConfigurationErrors", "WebRequest exception"); //
TryEditLocalization("trayTitle-parsingBusy", "Log Parsing lagging behind"); //
TryEditLocalization("trayTitle-restartAct", "ACT Restart Requested"); //
TryEditLocalization("trayTitle-unhandledException", "Unhandled Exception in ACT"); //
TryEditLocalization("trayTitle-updateAvailable", "ACT Update Available"); //
TryEditLocalization("trayTitle-xmlPrefErrorCount", "Config Load Errors"); //
TryEditLocalization("ttOptionsXmlShare-invalidXml", "Invalid XML: Use this field to paste XML share text"); //
TryEditLocalization("ttOptionsXmlShare-noName", "A name must be entered"); //
TryEditLocalization("ttOptionsXmlShare-xmlMissingAttributes", "The shared XML seems to be missing required attributes to be imported"); //
TryEditLocalization("tts-commandTest", "Command name"); //
TryEditLocalization("tts-spellExpired", "{0} expired"); // Text to Speech: SpellName expired
TryEditLocalization("tts-spellExpiredTest", "Spellname expired"); //
TryEditLocalization("tts-spellStarted", "{0} started"); // Text to Speech: SpellName started
TryEditLocalization("tts-spellStartedTest", "Spellname started"); //
TryEditLocalization("tts-spellWarning", "{0} warning"); // Text to Speech: SpellName warning
TryEditLocalization("tts-spellWarningTest", "Spellname warning"); //
TryEditLocalization("ui-customTriggerGeneralCategory", " General"); // There is a space before the term for sorting purposes. Also for Spell Timer categories.
TryEditLocalization("ui-customTriggerSearch", "Custom Trigger threads"); // Search terms for the Options tab to show Custom Trigger thread count
TryEditLocalization("uiFormActMain-Title0", "{0}{1}Advanced Combat Tracker{2} - {3} - Log Time: {4} (Est. {5})"); //
TryEditLocalization("uiFormActMain-Title1", "*Combat* "); // Shown on the titlebar
TryEditLocalization("uiFormActMain-Title2a", "Log Active"); //
TryEditLocalization("uiFormActMain-Title2b", "Log Idle"); //
TryEditLocalization("uiFormActMain-Title3", "[Exporting]"); //
TryEditLocalization("uiFormActMain-Title4", "[Importing]"); //
TryEditLocalization("uiFormActMain-Title5", "[ODBC]"); //
TryEditLocalization("uiFormAvoidanceReport-avoidCount", "Count"); //
TryEditLocalization("uiFormAvoidanceReport-avoidCount2", "Avoids"); //
TryEditLocalization("uiFormAvoidanceReport-avoidDamage", "Damage Avoided By Average"); //
TryEditLocalization("uiFormAvoidanceReport-avoidHps", "EncHPS"); //
TryEditLocalization("uiFormAvoidanceReport-avoidLabel", "[{4}] {0}'s {1} vs {2} = {3:0} Avg"); // vs = verses, Avg = average
TryEditLocalization("uiFormAvoidanceReport-avoidTitle", "Avoid-Other Report for {0} (Click a row for details)"); //
TryEditLocalization("uiFormAvoidanceReport-avoidTitle2", "{0}'s Avoidance Report (Click a row for details)"); //
TryEditLocalization("uiFormAvoidanceReport-avoidType", "Type"); //
TryEditLocalization("uiFormAvoidanceReport-noDamage", "No Damage (Stoneskin)"); //
TryEditLocalization("uiFormAvoidanceReport-percAvoids", "% of Avoids"); //
TryEditLocalization("uiFormAvoidanceReport-percSwings", "% of Swings"); //
TryEditLocalization("uiFormAvoidanceReport-specialTitle", "{0}'s Special Attack Report"); //
TryEditLocalization("uiFormAvoidanceReport-swings", "Swings"); //
TryEditLocalization("uiFormAvoidanceReport-total", "TOTAL"); //
TryEditLocalization("uiFormByCombatantLookup-title", "{0} Breakdown by Combatant"); //
TryEditLocalization("uiFormCustomEncRange-custom", "CustomEnc"); //
TryEditLocalization("uiFormCustomTriggerBenchmark-bench1", "<Benchmark>"); //
TryEditLocalization("uiFormCustomTriggerBenchmark-benchBaseline", "<Baseline benchmark...>"); //
TryEditLocalization("uiFormCustomTriggerBenchmark-benchRunning", "text"); // <Running>
TryEditLocalization("uiFormCustomTriggerBenchmark-lineCount", "{0:#,0} log lines in this encounter."); //
TryEditLocalization("uiFormEncounterVcr-currentHealth", "Current Health: {0:0.00%} of {1:#,0}"); //
TryEditLocalization("uiFormEncounterVcr-damageTaken", "Damage taken: {0:0.00%} of {1:#,0}"); //
TryEditLocalization("uiFormEncounterVcr-healingTaken", "Healing taken: {0:0.00%} of {1:#,0}"); //
TryEditLocalization("uiFormEncounterVcr-linked", "Linked @ T+{0}"); //
TryEditLocalization("uiFormEncounterVcr-paused", "Paused @ T+{0}"); //
TryEditLocalization("uiFormEncounterVcr-play", "Play @ T+{0}"); //
TryEditLocalization("uiFormEncounterVcr-play4", "4x Play @ T+{0}"); //
TryEditLocalization("uiFormEncounterVcr-rewind", "Rewind @ T+{0}"); //
TryEditLocalization("uiFormExportFormat-edit", "Edit Directly"); //
TryEditLocalization("uiFormExportFormat-noSelection", "No Element Selected"); //
TryEditLocalization("uiFormExportFormat-save", "Save"); //
TryEditLocalization("uiFormGetPlugins-headerLabel", "Plugin Description (Added: {1} - Modified: {2} {3})"); //
TryEditLocalization("uiFormImportProgress-batchStep", "Batch {0} of {1}"); //
TryEditLocalization("uiFormImportProgress-complete", "Operation Complete"); //
TryEditLocalization("uiFormImportProgress-importStats", "{0:#,0}s\n{1:#,0}\n{2:#,0} per sec\n{3:#,0} k\n{4:#,0} k/s"); //
TryEditLocalization("uiFormImportProgress-progressPerc", "Progress: {0}%"); //
TryEditLocalization("uiFormImportProgress-timeElapsed", "Operation Time Elapsed: {0:#,0}s\n"); //
TryEditLocalization("uiFormMiniParse-switchTooltip", "Switch between text and graph modes"); //
TryEditLocalization("uiFormMiniParse-title", "Mini Parse"); //
TryEditLocalization("uiFormMiniParse-titleCombat", "Mini Parse - *Combat*"); //
TryEditLocalization("uiFormMiniParse-valueTooltip", "Val: {0:0} Y: {1}"); //
TryEditLocalization("uiFormPerformanceWizard-advanced", "Advanced"); //
TryEditLocalization("uiFormPerformanceWizard-simple", "Simple"); //
TryEditLocalization("uiFormResistsDeathReport-deathLegend", "Time: Dmg (Dmg - Heal) [Dmg Total]\n"); //
TryEditLocalization("uiFormResistsDeathReport-deathTitle", "Death Report"); //
TryEditLocalization("uiFormResistsDeathReport-reportCopyLeft", "Click to copy to the left...\n"); //
TryEditLocalization("uiFormSpellRecastCalc-delaysLabel", "Checked Delays: "); //
TryEditLocalization("uiFormSpellRecastCalc-title", "Spell Recast Calculation - {0} -> {1}"); //
TryEditLocalization("uiFormSpellTimers-displayRemaining", "{0:00}m {1:00}s{2}"); // 01m 30s
TryEditLocalization("uiFormSpellTimers-displayTooltip", "{0}s - {1}"); // 12s - SpellName
TryEditLocalization("uiFormSpellTimersPanel-optionsTooltip", "Right-click for options"); //
TryEditLocalization("uiFormSpellTimers-searchPH", "Search name or tooltip"); // Placeholder to show when textbox is empty
TryEditLocalization("uiFormSqlQuery-connectionInfo", "ServerVersion: {0}, Database: {1}, DataSource: {2}"); //
TryEditLocalization("uiFormSqlQuery-rowsAffected", "\n{0} - Rows affected: {1}"); //
TryEditLocalization("uiFormSqlQuery-tableCommitError", "\n{0} - {1} has the following error: {2} -- and has been ignored."); // 0 = timestamp, 1 = table row text, 2 = error text
TryEditLocalization("uiFormStartupWizard-eq2FolderFound", "EQ2 Logs folder found."); //
TryEditLocalization("uiFormStartupWizard-eq2FolderFound2", "EQ2 Logs folder not found."); //
TryEditLocalization("uiFormStartupWizard-eq2FolderTitle", "Select your EQ2 installation folder"); //
TryEditLocalization("uiFormStartupWizard-loaded", "Click here to choose a plugin for your game..."); //
TryEditLocalization("uiFormStartupWizard-loading", "Please wait..."); //
TryEditLocalization("uiFormStartupWizard-pluginInfo", "Added: {1} - Modified: {2} {3}"); //
TryEditLocalization("uiFormStartupWizard-pluginLog", "Plugin selected log file."); //
TryEditLocalization("uiFormStartupWizard-pluginLog2", "Log file status unknown. Plugin may regenerate later."); //
TryEditLocalization("uiFormTimeLine-alignType1", "Us"); //
TryEditLocalization("uiFormTimeLine-alignType2", "Them"); //
TryEditLocalization("uiFormTimeLine-classType1", "Tanks"); //
TryEditLocalization("uiFormTimeLine-classType2", "Healers"); //
TryEditLocalization("uiFormTimeLine-classType3", "Melee DPS"); //
TryEditLocalization("uiFormTimeLine-classType4", "Other DPS"); //
TryEditLocalization("uiFormTimeLine-title1", "Timeline - {0} {1:0.00}%"); //
TryEditLocalization("uiFormTimeLine-title2", "Timeline"); //
TryEditLocalization("uiFormTimeLine-toolTipError", "This tool tip is too large. Please Middle-Click to view separately."); //
TryEditLocalization("uiFormUpdater-checking", "Checking version from web..."); //
TryEditLocalization("uiFormUpdater-download1", "Downloading update... connecting..."); //
TryEditLocalization("uiFormUpdater-download2", "Downloading update: {0:#,0} of {1:#,0} KB."); //
TryEditLocalization("uiFormUpdater-download3", "Downloading update: {0:#,0} KB read..."); //
TryEditLocalization("uiFormUpdater-download4", "Download is complete. Click Update to continue."); //
TryEditLocalization("uiFormUpdater-downloadError", "There was an error updating:\n"); //
TryEditLocalization("uiFormUpdater-noUpdates", "No updates available."); //
TryEditLocalization("uiFormUpdater-updateAvailable", "Update to {0} available.\nPress Download to retrieve."); //
TryEditLocalization("uiIoImportClip-clipStatus", "The Windows clipboard contains {0:#,0} characters."); //
TryEditLocalization("uiIoImportClip-noText", "The clipboard did not contain text data."); //
TryEditLocalization("uiIoXmlFile-exportCanceled", "Export canceled..."); //
TryEditLocalization("uiIoXmlFile-exportComplete", "Export to {0} has completed.\n{1:0} seconds elapsed."); //
TryEditLocalization("uiIoXmlFile-exporting", "Exporting XML...\nPlease wait..."); //
TryEditLocalization("uiLoading-init10", "InitACT 10... (Setting up log file, scanning for zone/name info)"); //
TryEditLocalization("uiLoading-init11", "InitACT 11... (Setting up data objects)"); //
TryEditLocalization("uiLoading-init12", "InitACT 12... (Scanning for blocked Internet files)"); //
TryEditLocalization("uiLoading-init13", "InitACT 13... (Setting processor affinity)"); //
TryEditLocalization("uiLoading-init14", "InitACT 14... (Initializing main table style)"); //
TryEditLocalization("uiLoading-init15", "InitACT 15... (Validating columns and export variables)"); //
TryEditLocalization("uiLoading-init16", "InitACT 16... (Starting log watcher)"); //
TryEditLocalization("uiLoading-init17", "InitACT 17... (Resetting tab views)"); //
TryEditLocalization("uiLoading-init18", "InitACT 18... (Resetting combobox styles, checking parser events)"); //
TryEditLocalization("uiLoading-init19", "InitACT 19... (Checking for updates, setting initial viewstate)"); //
TryEditLocalization("uiLoading-init20", "InitACT 20... (Checking plugins)"); //
TryEditLocalization("uiLoading-init21", "InitACT 21... (Setting up history database)"); //
TryEditLocalization("uiLoading-init22", "InitACT 22... (Checking ACT's folder, XML subs)"); //
TryEditLocalization("uiLoading-init23", "InitACT 23... (Checking config backups)"); //
TryEditLocalization("uiLoading-initExit", "Exiting InitACT..."); //
TryEditLocalization("ui-loadingPlugin", "Loading plugin {0}..."); // Shown during InitACT
TryEditLocalization("uiOpMisc-logPaused", "Parsing Paused..."); //
TryEditLocalization("uiOpMisc-logPosition1", "Reading {0}\nAt position: {1:0,0}."); // Shown in the Misc options panel
TryEditLocalization("uiOpMisc-logPosition2a", " ({0} lines behind.)"); //
TryEditLocalization("uiOpMisc-logPosition3", " ({0} CustomTrigger lines behind.)"); //
TryEditLocalization("uiOpMisc-logPosition4", "\nSyncing companion files: "); //
TryEditLocalization("uiOpMisc-logResumed", "Parsing Resumed..."); //
TryEditLocalization("uiOptionsImportExport-xmlConverted", "XML Converted. The above may be copied as an ACT Config Snippet to paste."); //
TryEditLocalization("uiOptionsOdbc-connectSuccess", "ODBC Connection Succeeded"); //
TryEditLocalization("uiOptionsOdbc-tableCreated", "'{0}' created successfully."); //
TryEditLocalization("uiOptionsOdbc-tableDropped", "'{0}' dropped successfully."); //
TryEditLocalization("uiOptionsOdbc-tableValidated", "'{0}' validated successfully."); //
TryEditLocalization("uiOptions-searchDefault", "Search Options..."); // What is shown in the searchbox when empty
TryEditLocalization("uiOptionsSound-soundMethod", "Sound Method:"); //
TryEditLocalization("uiOptionsSound-ttsMethod", "TTS Method:"); //
TryEditLocalization("uiOptionsXmlShare-customEntry", "* Custom Entry *"); //
TryEditLocalization("uiOptionsXmlShare-pasteHere", "(Paste XML Here)"); //
TryEditLocalization("uiOpWebServer-sessionStats", "Session stats | During the last 10s\n{0:#,0} bytes in | {3:0.00} KB/s in\n{1:#,0} bytes out | {4:0.00} KB/s out\n{2} unique clients | {5} unique clients"); //
TryEditLocalization("uiPlugins-fileDetails", "{3}\n{0,0} bytes, Last Modified: {1} - {2}"); //
TryEditLocalization("ui-processPriority", "Normal"); //
TryEditLocalization("ui-processPriority-", "Below Normal"); //
TryEditLocalization("ui-processPriority--", "Lowest"); //
TryEditLocalization("ui-processPriority+", "Above Normal"); //
TryEditLocalization("ui-ReadLogClosed", "Logfile closed."); //
TryEditLocalization("ui-ReadLogException", "System Message: {0}"); // ReadLog throws an exception, this is displayed in the Options tab
TryEditLocalization("ui-ReadLogPaused", "Parsing Paused..."); //
TryEditLocalization("ui-ReadLogResumed", "Parsing Resumed..."); //
TryEditLocalization("ui-soundTypeBeep", "Beep"); //
TryEditLocalization("ui-soundTypeNone", "None"); //
TryEditLocalization("ui-soundTypeSound", "Sound"); //
TryEditLocalization("ui-soundTypeTts", "TTS"); //
TryEditLocalization("ui-spellTimerTooltip", "{0} - {1}s."); // Abbreviated 's.' stands for seconds.
TryEditLocalization("ui-tableColumnError", "ERROR"); // Message shown in the main table when a cell's data provider throws an exception
TryEditLocalization("uiText-actExport1", "Exporting..."); //
TryEditLocalization("uiText-actExport2", "{0} exported."); //
TryEditLocalization("uiText-actExportError1", "File Error: {0}"); //
TryEditLocalization("uiText-actExportError2", "Unexpected error: {0}"); //
TryEditLocalization("uiText-actExportError3", "Error while parsing ACT/XML file: Line #"); //
TryEditLocalization("uiText-actExportError4", "The ACT file was corrupt, and may be an incompatible version.\n"); //
TryEditLocalization("uiText-assemblyReport1", "\nACT assemblies:"); //
TryEditLocalization("uiText-assemblyReport2", "\nPlugin assemblies:"); //
TryEditLocalization("uiText-assemblyReport3", "\nAdditional assemblies:"); //
TryEditLocalization("uiText-clipConnectDisc", "Not Connected."); //
TryEditLocalization("uiText-clipConnectError1", "The IP/Port syntax is invalid."); //
TryEditLocalization("uiText-clipConnectFail", "Connection Failed."); //
TryEditLocalization("uiText-clipConnectStart1", "Attempting connection..."); //
TryEditLocalization("uiText-clipConnectStart2", "Connected to {0}:{1}."); //
TryEditLocalization("uiText-customTriggerClear", "Clear Items"); //
TryEditLocalization("uiText-customTriggerColLogLine", "Log line"); //
TryEditLocalization("uiText-customTriggerColTimeStamp", "Time Stamp"); //
TryEditLocalization("uiText-customTriggerCopy1", "Copy Search Results"); //
TryEditLocalization("uiText-customTriggerCopy2", "Copy Selection"); //
TryEditLocalization("uiText-customTriggerCopy3", "Copy All"); //
TryEditLocalization("uiText-customTriggerFindNext", "Find Next"); //
TryEditLocalization("uiText-customTriggerFindPrev", "Find Prev"); //
TryEditLocalization("uiText-customTriggerSearch", "Search triggered log lines..."); //
TryEditLocalization("uiText-customTriggerSearchRegex", "Search as Regex"); //
TryEditLocalization("uiText-customTriggerSearchText", "Search as Text"); //
TryEditLocalization("uiText-exitAct", "Exiting ACT..."); //
TryEditLocalization("ui-textExportDefault", "[Current Default]"); //
TryEditLocalization("uiText-htmlComplete", "Export to {0} has completed.\n{1} seconds elapsed."); //
TryEditLocalization("uiText-htmlGen", "Generating HTML...\n"); //
TryEditLocalization("uiText-htmlWrite", "Writing HTML to file..."); //
TryEditLocalization("uiText-n", "N"); // No
TryEditLocalization("uiText-odbcCalc", "Data calculated for {0} in {1} secs."); //
TryEditLocalization("uiText-odbcComplete", "ODBC export has completed.\n{0} seconds elapsed.\n{1} errors."); //
TryEditLocalization("uiText-odbcComplete2", " Please see the General Options tab ODBC section for error descriptions."); //
TryEditLocalization("uiText-odbcGen1", "{0}, {1}.\nGenerating SQL..."); //
TryEditLocalization("uiText-odbcGen2", "{0}, {1}.\nGenerating SQL... {2}%"); //
TryEditLocalization("uiText-odbcGen3", "{0}, {1}.\nGenerating SQL... {2}% | {3}%"); //
TryEditLocalization("uiText-odbcGen4", "{0}, {1}.\nGenerating SQL... {2}% | {3}% | {4}%"); //
TryEditLocalization("uiText-odbcSending", "{0}, {1}.\nSending SQL to datasource... {2}%"); //
TryEditLocalization("uiText-odbcSent", "{0:0,0} SQL commands sent for {1} in {2} secs."); //
TryEditLocalization("uiText-odbcSent2", "{0:0,0} rows sent in {1} commands for {2} in {3} secs."); //
TryEditLocalization("uiText-pluginDefaultLabel", "No Status"); //
TryEditLocalization("uiText-pluginEnabled", "Enabled"); //
TryEditLocalization("uiText-pluginInfoParts1", "FileName: "); //
TryEditLocalization("uiText-pluginInfoParts10", "Comments: "); //
TryEditLocalization("uiText-pluginInfoParts2", "OriginalFilename: "); //
TryEditLocalization("uiText-pluginInfoParts3", "FileVersion: "); //
TryEditLocalization("uiText-pluginInfoParts4", "ProductVersion: "); //
TryEditLocalization("uiText-pluginInfoParts5", "FileDescription: "); //
TryEditLocalization("uiText-pluginInfoParts6", "ProductName: "); //
TryEditLocalization("uiText-pluginInfoParts7", "CompanyName: "); //
TryEditLocalization("uiText-pluginInfoParts8", "LegalCopyright: "); //
TryEditLocalization("uiText-pluginInfoParts9", "LegalTrademarks: "); //
TryEditLocalization("uiText-pluginInfoTitle1", "Assembly Info:\n"); //
TryEditLocalization("uiText-pluginInfoTitle2", "Source File Info:\n"); //
TryEditLocalization("uiText-startupWizLogFileInfo", "{0}\{1}\nFile size: {2:0,0} Last Modified: {3}"); //
TryEditLocalization("uiText-xmlSubsQueryInfo", "Last updated: {0} {1}"); //
TryEditLocalization("uiText-y", "Y"); // Yes
TryEditLocalization("uiTitle-act", "Advanced Combat Tracker"); //
TryEditLocalization("ui-webserverStatus", "Server Status"); //
TryEditLocalization("webDesc-browse", "Browse through all of the tables that ACT currently has in memory."); //
TryEditLocalization("webDesc-current", "Any encounter currently active can be found here. Page will refresh every 5 seconds."); //
TryEditLocalization("webDesc-mini", "The Mini Window text-only display of the current encounter. Page will refresh every 5 seconds."); //
TryEditLocalization("webDesc-timers", "View a table of spell timers ACT is currently tracking. Page will refresh every 2 seconds."); //
TryEditLocalization("webText-actUi", "ACT Web Interface"); //
TryEditLocalization("webText-browse", "Browse"); //
TryEditLocalization("webText-copyAll", "Copy All to Clipboard"); // OBSOLETE
TryEditLocalization("webText-currentEncounter", "Current Encounter"); //
TryEditLocalization("webText-currentNoEncounter", "No Encounter"); //
TryEditLocalization("webText-loading", "Loading..."); //
TryEditLocalization("webText-miniNoEncounter", "No Encounter"); //
TryEditLocalization("webText-miniNoFormat", "No Text Format Selected"); //
TryEditLocalization("webText-reload", "Reload"); //
TryEditLocalization("webText-timers", "Spell Timers"); //
TryEditLocalization("webText-timersNormal", "Normal View"); //
TryEditLocalization("webText-timersNoTimers", "No Spell Timers to display."); //
TryEditLocalization("webText-timersSimple", "Simple View"); //
TryEditLocalization("webTitle-browse", "Browse ACT's Encounter Data"); //
TryEditLocalization("webTitle-current", "Current Encounter Table"); //
TryEditLocalization("webTitle-mini", "Current Mini Window Text"); //
TryEditLocalization("webTitle-timers", "Timers Window Table"); //
TryEditLocalization("zoneDataTerm-import", "Import"); //
TryEditLocalization("zoneDataTerm-importMerge", "Import/Merge - [{0}]"); //
TryEditLocalization("zoneTerm-import", "Import Zone"); //
TryEditLocalization("zoneTerm-unknown", "Unknown Zone"); //
}
public void DeInitPlugin()
{
}
}
}
| 412 | 0.931002 | 1 | 0.931002 | game-dev | MEDIA | 0.594315 | game-dev | 0.618594 | 1 | 0.618594 |
wilhantian/BadGame | 4,167 | Classes/GameManager.cpp | #include "GameManager.h"
#include "Hero.h"
#include "StaticData.h"
USING_NS_CC;
GameManager* GameManager::gameManager = nullptr;
GameManager* GameManager::getInstance()
{
if(!gameManager)
{
gameManager = new GameManager();
gameManager->retain(); //+1
}
return gameManager;
}
void GameManager::initPhysicsWorld(float gravity)
{
world = new b2World(b2Vec2(0, -gravity));
world->SetContactListener(this);
//Ļλ
sceneX = Director::getInstance()->getVisibleSize().width / 2;
sceneY = Director::getInstance()->getVisibleSize().height / 2;
}
GameManager::GameManager()
{
hero = nullptr;
//ʼԴ
initRes();
//ʼ
initPhysicsWorld(GRAVITY);
//level = 0;
}
GameManager::~GameManager()
{
//CC_SAFE_RELEASE(gameManager);
CC_SAFE_DELETE(world);
}
b2World* GameManager::getWorld()
{
return world;
}
void GameManager::step(float time)
{
//--Ӣϴλ
Vec2 heroLastPostion = hero->getPosition();
world->Step(time, 8, 3);
//¾λáǶ
for(b2Body* body=world->GetBodyList(); body; body=body->GetNext())
{
Sprite* sprite = (Sprite*)body->GetUserData();
if(sprite == NULL)
continue;
sprite->setPosition(body->GetPosition().x*PTM_RATIO, body->GetPosition().y*PTM_RATIO);
sprite->setRotation(-1*CC_RADIANS_TO_DEGREES(body->GetAngle())); //ýǶ
}
//ͷٻջе
for(auto it = _deleteSprites.begin(); it != _deleteSprites.end(); )
{
(*it)->removePhysicsSprite();
it = _deleteSprites.erase(it);
}
//--Ӣ۵ǰλ
Vec2 heroNowPostion = hero->getPosition();
sceneX = sceneX + heroLastPostion.x - heroNowPostion.x;
sceneY = sceneY + heroLastPostion.y - heroNowPostion.y;
GameManager::getInstance()->gameLayer->setPosition(sceneX, sceneY);
}
void GameManager::pushDeleteSprite(PhysicsSprite* sprite)
{
_deleteSprites.pushBack(sprite);
}
void GameManager::BeginContact(b2Contact* contact)
{
GameObject* a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
GameObject* b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
a->BeginContact(b, contact);
b->BeginContact(a, contact);
}
void GameManager::EndContact(b2Contact* contact)
{
GameObject* a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
GameObject* b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
a->EndContact(b, contact);
b->EndContact(a, contact);
}
void GameManager::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
GameObject* a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
GameObject* b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
a->PreSolve(b, contact, oldManifold);
b->PreSolve(a, contact, oldManifold);
}
void GameManager::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
{
GameObject* a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
GameObject* b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
a->PostSolve(b, contact, impulse);
b->PostSolve(a, contact, impulse);
}
/*ʼԴ*/
void GameManager::initRes()
{
std::string path = FileUtils::getInstance()->fullPathForFilename("load.xml");
ValueMap vm = FileUtils::getInstance()->getValueMapFromFile(path);
for (int i = 0; i < vm.size(); i++)
{
char buf[12];
sprintf(buf, "%d", i+1);
std::string s = vm.at(buf).asString();
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s);
}
vm.clear();
}
Animation* GameManager::getAnimation(const char* src, float delay, unsigned int loops)
{
Vector<SpriteFrame*> frames;
char _src[30];
for(int i=0; i<10000; i++)
{
sprintf(_src, "%s%04d", src, i);
SpriteFrame* sf = SpriteFrameCache::getInstance()->getSpriteFrameByName(_src);
if(sf == nullptr)
{
break;
}
frames.pushBack(sf);
}
return Animation::createWithSpriteFrames(frames, delay, loops);
}
cocos2d::Animate* GameManager::getAnimate(const char* src, float delay /*= 0.0f*/, unsigned int loops /*= 1U*/)
{
Animation* animation = getAnimation(src, delay, loops);
return Animate::create(animation);
}
void GameManager::destroyInstance()
{
CC_SAFE_DELETE(gameManager);
}
// void GameManager::setLevel(int level)
// {
// GameManager::level = level;
// }
//
// int GameManager::getLevel()
// {
// return level;
// }
| 412 | 0.724872 | 1 | 0.724872 | game-dev | MEDIA | 0.958413 | game-dev | 0.882643 | 1 | 0.882643 |
pcraster/pcraster | 2,106 | source/mldd/Tests/mldd_outedgeiteratortest.cc | #define BOOST_TEST_MODULE pcraster mldd out_edge_iterator
#include <boost/test/unit_test.hpp>
#include "stddefx.h"
#include "mldd_outedgeiterator.h"
BOOST_AUTO_TEST_CASE(constructor)
{
using namespace mldd;
{
OutEdgeIterator begin(Vertex(1,1),0,0);
OutEdgeIterator end (Vertex(1,1));
size_t i=0;
for(OutEdgeIterator oi=begin; oi!=end; ++oi) {
i++;
}
BOOST_CHECK(!i);
}
{
OutEdgeIterator begin(Vertex(1,1),(1<<0)|(1<<6),0);
OutEdgeIterator end (Vertex(1,1));
size_t i=0;
for(OutEdgeIterator oi=begin; oi!=end; ++oi) {
Edge e=oi.edge();
BOOST_CHECK(e.source()==Vertex(1,1));
switch (i) {
case 0: BOOST_CHECK(e.target()==Vertex(2,0)); break;
case 1: BOOST_CHECK(e.target()==Vertex(0,1)); break;
};
i++;
}
BOOST_CHECK(i==2);
}
{
OutEdgeIterator begin(Vertex(1,1),(1<<0)|(1<<1),0);
OutEdgeIterator end (Vertex(1,1));
size_t i=0;
for(OutEdgeIterator oi=begin; oi!=end; ++oi) {
Edge e=oi.edge();
BOOST_CHECK(e.source()==Vertex(1,1));
switch (i) {
case 0: BOOST_CHECK(e.target()==Vertex(2,0)); break;
case 1: BOOST_CHECK(e.target()==Vertex(2,1)); break;
};
i++;
}
BOOST_CHECK(i==2);
}
{ // any() must do the same
OutEdgeIterator begin(Vertex(1,1),(1<<0)|(1<<1),0);
size_t i=0;
for(OutEdgeIterator oi=begin; oi.any(); ++oi) {
Edge e=oi.edge();
BOOST_CHECK(e.source()==Vertex(1,1));
switch (i) {
case 0: BOOST_CHECK(e.target()==Vertex(2,0)); break;
case 1: BOOST_CHECK(e.target()==Vertex(2,1)); break;
};
i++;
}
BOOST_CHECK(i==2);
}
{
OutEdgeIterator begin(Vertex(1,1),0xFF,0);
OutEdgeIterator end (Vertex(1,1));
size_t i=0;
OutEdgeIterator oi=begin;
for( ; oi != end /* oi.any() */; ++oi) {
i++;
Edge e=oi.edge();
BOOST_CHECK(e.source()==Vertex(1,1));
}
BOOST_CHECK(i==8);
// keep at past the end
++oi;
BOOST_CHECK(oi==end);
++oi;
BOOST_CHECK(oi==end);
}
}
| 412 | 0.850779 | 1 | 0.850779 | game-dev | MEDIA | 0.60892 | game-dev | 0.974572 | 1 | 0.974572 |
Silverlan/pragma | 5,209 | core/shared/src/entities/components/bone_merge_component.cpp | // SPDX-FileCopyrightText: (c) 2024 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#include "stdafx_shared.h"
#include "pragma/entities/components/bone_merge_component.hpp"
#include "pragma/entities/entity_component_manager_t.hpp"
#include "pragma/entities/components/base_animated_component.hpp"
#include "pragma/entities/components/base_model_component.hpp"
#include "pragma/model/model.h"
using namespace pragma;
bool BoneMergeComponent::can_merge(const Model &mdl, const Model &mdlParent, bool includeRootBones)
{
auto &skeleton = mdl.GetSkeleton();
auto &skeletonParent = mdlParent.GetSkeleton();
for(auto &bone : skeleton.GetBones()) {
if(!includeRootBones && bone->parent.expired())
continue; // We're filtering out root bones because there's usually no point in merging them
if(skeletonParent.LookupBone(bone->name) != -1)
return true;
}
return false;
}
ComponentEventId BoneMergeComponent::EVENT_ON_TARGET_CHANGED = pragma::INVALID_COMPONENT_ID;
void BoneMergeComponent::RegisterEvents(pragma::EntityComponentManager &componentManager, TRegisterComponentEvent registerEvent) { EVENT_ON_TARGET_CHANGED = registerEvent("ON_TARGET_CHANGED", ComponentEventInfo::Type::Broadcast); }
void BoneMergeComponent::RegisterMembers(pragma::EntityComponentManager &componentManager, TRegisterComponentMember registerMember)
{
using T = BoneMergeComponent;
{
using TTarget = pragma::EntityURef;
auto memberInfo = create_component_member_info<T, TTarget, static_cast<void (T::*)(const TTarget &)>(&T::SetTarget), static_cast<const TTarget &(T::*)() const>(&T::GetTarget)>("target", TTarget {});
registerMember(std::move(memberInfo));
}
}
BoneMergeComponent::BoneMergeComponent(BaseEntity &ent) : BaseEntityComponent(ent) {}
void BoneMergeComponent::Initialize()
{
BaseEntityComponent::Initialize();
BindEventUnhandled(BaseModelComponent::EVENT_ON_MODEL_CHANGED, [this](std::reference_wrapper<pragma::ComponentEvent> evData) { SetTargetDirty(); });
BindEventUnhandled(BaseAnimatedComponent::EVENT_POST_ANIMATION_UPDATE, [this](std::reference_wrapper<pragma::ComponentEvent> evData) { MergeBonePoses(); });
}
void BoneMergeComponent::InitializeLuaObject(lua_State *l) { pragma::BaseLuaHandle::InitializeLuaObject<std::remove_reference_t<decltype(*this)>>(l); }
void BoneMergeComponent::OnRemove()
{
BaseEntityComponent::OnRemove();
SetTargetDirty();
}
void BoneMergeComponent::SetTarget(const pragma::EntityURef &target)
{
m_target = target;
SetTargetDirty();
BroadcastEvent(EVENT_ON_TARGET_CHANGED);
}
const pragma::EntityURef &BoneMergeComponent::GetTarget() const { return m_target; }
void BoneMergeComponent::SetTargetDirty()
{
m_animC = pragma::ComponentHandle<pragma::BaseAnimatedComponent> {};
m_animCParent = pragma::ComponentHandle<pragma::BaseAnimatedComponent> {};
m_boneMappings.clear();
SetTickPolicy(pragma::TickPolicy::Always);
UpdateBoneMappings();
}
void BoneMergeComponent::OnTick(double tDelta)
{
BaseEntityComponent::OnTick(tDelta);
UpdateBoneMappings();
}
void BoneMergeComponent::UpdateBoneMappings()
{
auto &ent = GetEntity();
auto *entTgt = m_target.GetEntity(GetGame());
if(!entTgt)
return;
auto animC = ent.GetAnimatedComponent();
auto animCTgt = entTgt->GetAnimatedComponent();
if(animC.expired() || animCTgt.expired())
return;
auto &mdl = ent.GetModel();
auto &mdlTgt = entTgt->GetModel();
if(!mdl || !mdlTgt)
return;
auto &skeleton = mdl->GetSkeleton();
auto &skeletonTgt = mdlTgt->GetSkeleton();
for(auto &boneTgt : skeletonTgt.GetBones()) {
auto boneId = skeleton.LookupBone(boneTgt->name);
if(boneId == -1)
continue;
if(m_boneMappings.size() == m_boneMappings.capacity())
m_boneMappings.reserve(m_boneMappings.size() * 2 + 10);
m_boneMappings.push_back({});
auto &mapping = m_boneMappings.back();
mapping.boneId = boneId;
mapping.parentBoneId = boneTgt->ID;
}
m_animC = animC;
m_animCParent = animCTgt;
animC->SetPostAnimationUpdateEnabled(true);
SetTickPolicy(TickPolicy::Never);
}
void BoneMergeComponent::OnEntityComponentAdded(BaseEntityComponent &component)
{
BaseEntityComponent::OnEntityComponentAdded(component);
auto *animC = dynamic_cast<BaseAnimatedComponent *>(&component);
if(animC) {
SetTickPolicy(pragma::TickPolicy::Always);
UpdateBoneMappings();
}
}
void BoneMergeComponent::OnEntityComponentRemoved(BaseEntityComponent &component)
{
BaseEntityComponent::OnEntityComponentRemoved(component);
auto *animC = dynamic_cast<BaseAnimatedComponent *>(&component);
if(animC) {
SetTickPolicy(pragma::TickPolicy::Always);
UpdateBoneMappings();
}
}
void BoneMergeComponent::MergeBonePoses()
{
if(m_animC.expired() || m_animCParent.expired())
return;
auto &poses = m_animC->GetBoneTransforms();
auto &posesParent = m_animCParent->GetBoneTransforms();
for(auto &mapping : m_boneMappings) {
if(mapping.boneId >= poses.size() || mapping.parentBoneId >= posesParent.size())
continue;
umath::ScaledTransform pose;
if(!m_animCParent->GetBonePose(mapping.parentBoneId, pose, umath::CoordinateSpace::Object))
continue;
m_animC->SetBonePose(mapping.boneId, pose, umath::CoordinateSpace::Object);
}
m_animC->SetAbsolutePosesDirty();
}
| 412 | 0.918783 | 1 | 0.918783 | game-dev | MEDIA | 0.935514 | game-dev | 0.882758 | 1 | 0.882758 |
HongchengQ/HunkyMeow | 5,162 | src/main/java/emu/grasscutter/server/game/GameServerPacketHandler.java | package emu.grasscutter.server.game;
import static emu.grasscutter.config.Configuration.GAME_INFO;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.net.packet.*;
import emu.grasscutter.server.event.game.ReceivePacketEvent;
import emu.grasscutter.server.game.GameSession.SessionState;
import it.unimi.dsi.fastutil.ints.*;
import lombok.val;
public final class GameServerPacketHandler {
private final Int2ObjectMap<PacketHandler> handlers;
public GameServerPacketHandler(Class<? extends PacketHandler> handlerClass) {
this.handlers = new Int2ObjectOpenHashMap<>();
this.registerHandlers(handlerClass);
}
public void registerPacketHandler(Class<? extends PacketHandler> handlerClass) {
try {
var opcode = handlerClass.getAnnotation(Opcodes.class);
if (opcode == null || opcode.disabled() || opcode.value() <= 0) {
return;
}
var packetHandler = handlerClass.getDeclaredConstructor().newInstance();
this.handlers.put(opcode.value(), packetHandler);
} catch (Exception e) {
Grasscutter.getLogger()
.warn("Unable to register handler {}.", handlerClass.getSimpleName(), e);
}
}
public void registerHandlers(Class<? extends PacketHandler> handlerClass) {
var handlerClasses = Grasscutter.reflector.getSubTypesOf(handlerClass);
for (var obj : handlerClasses) {
this.registerPacketHandler(obj);
}
// Debug
Grasscutter.getLogger()
.debug("Registered {} {}s", this.handlers.size(), handlerClass.getSimpleName());
}
public void handle(GameSession session, int opcode, byte[] header, byte[] payload) {
PacketHandler handler = this.handlers.get(opcode);
if (handler != null) {
try {
SessionState state = session.getState();
// 优先检查需要立即关闭会话的状态
// 不要滥用 session.close() 因为客户端会重连 所以很多时候会导致客户端弹窗堆积
if (state == SessionState.ACCOUNT_BANNED) {
session.close();
Grasscutter.getLogger().debug("客户端连接拒绝 因为账号处于黑名单中");
return;
} else if (state == SessionState.WAITING_SERVER_LUA || state == SessionState.SERVER_MAX_PLAYER_OVERFLOW) {
Grasscutter.getLogger().debug("客户端连接拒绝 因为服务端未初始化完成或人数到达上限");
return;
} else if (state == SessionState.DB_OVERLOAD) {
Grasscutter.getLogger().debug("客户端连接拒绝 因为服务端数据库排队列表过多");
return;
}
// 其次根据传来的 CMD_ID 判断是否符合相应的条件
if (opcode == PacketOpcodes.PingReq) {
// Always continue if packet is ping request
if (state == SessionState.NONE) System.out.println("???");; // 这里只是为了不让编辑器报警告
} else if (opcode == PacketOpcodes.GetPlayerTokenReq) {
if (state != SessionState.WAITING_FOR_TOKEN){
Grasscutter.getLogger().debug("-1 WAITING_FOR_TOKEN 客户端连接拒绝 因为 state 错误");
return;
}
} else if (opcode == PacketOpcodes.PlayerLoginReq) {
if (state != SessionState.WAITING_FOR_LOGIN) {
Grasscutter.getLogger().debug("-2 WAITING_FOR_LOGIN 客户端连接拒绝 因为 state 错误");
return;
}
} else if (opcode == PacketOpcodes.SetPlayerBornDataReq) {
if (state != SessionState.PICKING_CHARACTER) {
Grasscutter.getLogger().debug("-3 PICKING_CHARACTER 客户端连接拒绝 因为 state 错误");
return;
}
} else {
if (state != SessionState.ACTIVE) {
Grasscutter.getLogger().debug("-4 ACTIVE 客户端连接拒绝 因为 state 错误");
return;
}
}
// 调用事件处理
ReceivePacketEvent event = new ReceivePacketEvent(session, opcode, payload);
event.call();
if (!event.isCanceled()) // If event is not canceled, continue.
handler.handle(session, header, event.getPacketData());
} catch (Exception ex) {
val player = session.getPlayer();
int sessionUid = 0;
if (player != null) sessionUid = player.getUid();
Grasscutter.getLogger().error("Error handling packet (opcode: {}, uid: {})", opcode, sessionUid, ex);
}
return; // Packet successfully handled
}
// 记录未处理的包
if ((GAME_INFO.logPackets == ServerDebugMode.MISSING || GAME_INFO.logPackets == ServerDebugMode.ALL)
&& !PacketOpcodesUtils.LOOPUPDATE_PACKETS.contains(opcode)) {
Grasscutter.getLogger().info(
"Unhandled packet ({}): {}",
opcode,
PacketOpcodesUtils.getOpcodeName(opcode)
);
}
}
}
| 412 | 0.941702 | 1 | 0.941702 | game-dev | MEDIA | 0.722693 | game-dev,networking | 0.969389 | 1 | 0.969389 |
lynx-chess/Lynx | 3,779 | src/Lynx/UCI/Commands/GUI/PositionCommand.cs | using Lynx.Model;
using NLog;
using System.Diagnostics.CodeAnalysis;
namespace Lynx.UCI.Commands.GUI;
/// <summary>
/// position[fen | startpos] moves ....
/// set up the position described in fenstring on the internal board and
/// play the moves on the internal chess board.
/// if the game was played from the start position the string "startpos" will be sent
/// Note: no "new" command is needed. However, if this position is from a different game than
/// the last position sent to the engine, the GUI should have sent a "ucinewgame" inbetween.
/// </summary>
public sealed class PositionCommand
{
public const string Id = "position";
public const string StartPositionString = "startpos";
public const string MovesString = "moves";
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
public static Game ParseGame(ReadOnlySpan<char> positionCommandSpan, Span<Move> movePool)
{
try
{
// We divide the position command in these two sections:
// "position startpos ||"
// "position startpos || moves e2e4 e7e5"
// "position fen 8/8/8/8/8/8/8/8 w - - 0 1 ||"
// "position fen 8/8/8/8/8/8/8/8 w - - 0 1 || moves e2e4 e7e5"
Span<Range> items = stackalloc Range[2];
positionCommandSpan.Split(items, "moves", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var initialPositionSection = positionCommandSpan[items[0]];
// We divide in these two parts
// "position startpos ||" <-- If "fen" doesn't exist in the section
// "position || (fen) 8/8/8/8/8/8/8/8 w - - 0 1" <-- If "fen" does exist
Span<Range> initialPositionParts = stackalloc Range[2];
initialPositionSection.Split(initialPositionParts, "fen", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
ReadOnlySpan<char> fen = initialPositionSection[initialPositionParts[0]].Length == Id.Length // "position" o "position startpos"
? initialPositionSection[initialPositionParts[1]]
: Constants.InitialPositionFEN.AsSpan();
var movesSection = positionCommandSpan[items[1]];
Span<Range> moves = stackalloc Range[(movesSection.Length / 5) + 1]; // Number of potential half-moves provided in the string
movesSection.Split(moves, ' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return new Game(fen, movesSection, moves, movePool);
}
catch (Exception e)
{
_logger.Error(e, "Error parsing position command '{0}'", positionCommandSpan.ToString());
return new Game(Constants.InitialPositionFEN);
}
}
public static bool TryParseLastMove(string positionCommand, Game game, [NotNullWhen(true)] out Move? lastMove)
{
var moveString = positionCommand
.Split(' ', StringSplitOptions.RemoveEmptyEntries)[^1];
Span<Move> movePool = stackalloc Move[Constants.MaxNumberOfPseudolegalMovesInAPosition];
Span<BitBoard> attacks = stackalloc BitBoard[12];
Span<BitBoard> attacksBySide = stackalloc BitBoard[2];
var evaluationContext = new EvaluationContext(attacks, attacksBySide);
if (!MoveExtensions.TryParseFromUCIString(
moveString,
MoveGenerator.GenerateAllMoves(game.CurrentPosition, ref evaluationContext, movePool),
out lastMove))
{
_logger.Warn("Error parsing last move {0} from position command {1}", lastMove, positionCommand);
return false;
}
return true;
}
}
| 412 | 0.949469 | 1 | 0.949469 | game-dev | MEDIA | 0.880099 | game-dev | 0.964242 | 1 | 0.964242 |
TerraFirmaCraft/TerraFirmaCraft | 2,625 | src/main/java/net/dries007/tfc/common/recipes/ingredients/HeatIngredient.java | /*
* Licensed under the EUPL, Version 1.2.
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*/
package net.dries007.tfc.common.recipes.ingredients;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.neoforged.neoforge.common.crafting.IngredientType;
import net.dries007.tfc.common.Lore;
import net.dries007.tfc.common.component.heat.HeatCapability;
import net.dries007.tfc.config.TFCConfig;
import net.dries007.tfc.util.tooltip.Tooltips;
import net.dries007.tfc.world.Codecs;
public record HeatIngredient(float min, float max) implements PreciseIngredient
{
private static final float MIN = Float.NEGATIVE_INFINITY;
private static final float MAX = Float.POSITIVE_INFINITY;
public static final MapCodec<HeatIngredient> CODEC = RecordCodecBuilder.<HeatIngredient>mapCodec(i -> i.group(
Codecs.POSITIVE_FLOAT.optionalFieldOf("min", MIN).forGetter(c -> c.min),
Codecs.POSITIVE_FLOAT.optionalFieldOf("max", MAX).forGetter(c -> c.max)
).apply(i, HeatIngredient::new)).flatXmap(
c -> c.min == MIN && c.max == MAX ? DataResult.error(() -> "Must have one of min or max") : DataResult.success(c),
DataResult::success
);
public static final StreamCodec<ByteBuf, HeatIngredient> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.FLOAT, c -> c.min,
ByteBufCodecs.FLOAT, c -> c.max,
HeatIngredient::new
);
public static Ingredient min(float min)
{
return new HeatIngredient(min, MAX).toVanilla();
}
@Override
public boolean test(ItemStack stack)
{
final float temperature = HeatCapability.getTemperature(stack);
return temperature >= min && temperature <= max;
}
@Override
public ItemStack modifyStackForDisplay(ItemStack stack)
{
HeatCapability.setStaticTemperature(stack, min != MIN ? min : max);
Lore.append(stack, Tooltips.require(
min == MIN ? null : TFCConfig.CLIENT.heatTooltipStyle.get().formatColored(min),
max == MAX ? null : TFCConfig.CLIENT.heatTooltipStyle.get().formatColored(max)
));
return stack;
}
@Override
public IngredientType<?> getType()
{
return TFCIngredients.HEAT.get();
}
}
| 412 | 0.826719 | 1 | 0.826719 | game-dev | MEDIA | 0.949569 | game-dev | 0.888404 | 1 | 0.888404 |
Albeoris/Memoria | 3,322 | Assembly-CSharp/Global/XInputTestCS.cs | using Assets.Scripts.Common;
using System;
using UnityEngine;
using XInputDotNetPure;
using Object = System.Object;
public class XInputTestCS : MonoBehaviour
{
private void Start()
{
}
private void Update()
{
this.prevState = this.state;
this.state = global::GamePad.GetState(this.playerIndex);
if (this.prevState.Buttons.A == ButtonState.Released && this.state.Buttons.A == ButtonState.Pressed)
{
base.GetComponent<Renderer>().material.color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, 1f);
}
if (this.prevState.Buttons.A == ButtonState.Pressed && this.state.Buttons.A == ButtonState.Released)
{
base.GetComponent<Renderer>().material.color = new Color(1f, 1f, 1f, 1f);
}
global::GamePad.SetVibration(this.playerIndex, this.state.Triggers.Left, this.state.Triggers.Right);
base.transform.localRotation *= Quaternion.Euler(0f, this.state.ThumbSticks.Left.X * 25f * Time.deltaTime, 0f);
if (this.prevState.Buttons.Start == ButtonState.Released && this.state.Buttons.Start == ButtonState.Pressed)
{
SceneDirector.Replace("Bundle", SceneTransition.FadeOutToBlack_FadeIn, true);
}
}
private void OnGUI()
{
String text = "Use left stick to turn the cube, hold A to change color\n";
text += String.Format("IsConnected {0} Packet #{1}\n", this.state.IsConnected, this.state.PacketNumber);
text += String.Format("\tTriggers {0} {1}\n", this.state.Triggers.Left, this.state.Triggers.Right);
text += String.Format("\tD-Pad {0} {1} {2} {3}\n", new Object[]
{
this.state.DPad.Up,
this.state.DPad.Right,
this.state.DPad.Down,
this.state.DPad.Left
});
text += String.Format("\tButtons Start {0} Back {1} Guide {2}\n", this.state.Buttons.Start, this.state.Buttons.Back, this.state.Buttons.Guide);
text += String.Format("\tButtons LeftStick {0} RightStick {1} LeftShoulder {2} RightShoulder {3}\n", new Object[]
{
this.state.Buttons.LeftStick,
this.state.Buttons.RightStick,
this.state.Buttons.LeftShoulder,
this.state.Buttons.RightShoulder
});
text += String.Format("\tButtons A {0} B {1} X {2} Y {3}\n", new Object[]
{
this.state.Buttons.A,
this.state.Buttons.B,
this.state.Buttons.X,
this.state.Buttons.Y
});
text += String.Format("\tSticks Left {0} {1} Right {2} {3}\n", new Object[]
{
this.state.ThumbSticks.Left.X,
this.state.ThumbSticks.Left.Y,
this.state.ThumbSticks.Right.X,
this.state.ThumbSticks.Right.Y
});
text = text + "\tHono Axis Raw :" + PersistenSingleton<HonoInputManager>.Instance.GetAxis();
text += (((Int32)Input.GetJoystickNames().Length <= 0) ? String.Empty : ("\nJoyStick Name : " + Input.GetJoystickNames()[0]));
GUI.Label(new Rect(0f, 0f, (Single)Screen.width, (Single)Screen.height), text);
}
private Boolean playerIndexSet;
private PlayerIndex playerIndex;
private GamePadState state;
private GamePadState prevState;
}
| 412 | 0.756686 | 1 | 0.756686 | game-dev | MEDIA | 0.813765 | game-dev | 0.910516 | 1 | 0.910516 |
KoshakMineDEV/Lumi | 4,129 | src/main/java/cn/nukkit/level/generator/Generator.java | package cn.nukkit.level.generator;
import cn.nukkit.Server;
import cn.nukkit.block.BlockID;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.level.DimensionData;
import cn.nukkit.level.DimensionEnum;
import cn.nukkit.level.Level;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.MainLogger;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author MagicDroidX
* Nukkit Project
*/
public abstract class Generator implements BlockID {
public static final int TYPE_OLD = 0;
public static final int TYPE_INFINITE = 1;
public static final int TYPE_FLAT = 2;
public static final int TYPE_NETHER = 3;
public static final int TYPE_THE_END = 4;
public static final int TYPE_VOID = 5;
public abstract int getId();
public DimensionData getDimensionData() {
DimensionData dimensionData = DimensionEnum.getDataFromId(this.getDimension());
if (dimensionData == null) {
dimensionData = DimensionEnum.OVERWORLD.getDimensionData();
}
return dimensionData;
}
@Deprecated
public int getDimension() {
return Level.DIMENSION_OVERWORLD;
}
private static final Map<String, Class<? extends Generator>> nameList = new HashMap<>();
private static final Map<Integer, Class<? extends Generator>> typeList = new HashMap<>();
public static boolean addGenerator(Class<? extends Generator> clazz, String name, int type) {
name = name.toLowerCase(Locale.ROOT);
if (clazz != null && !Generator.nameList.containsKey(name)) {
Generator.nameList.put(name, clazz);
if (!Generator.typeList.containsKey(type)) {
Generator.typeList.put(type, clazz);
}
return true;
}
return false;
}
public static String[] getGeneratorList() {
String[] keys = new String[Generator.nameList.size()];
return Generator.nameList.keySet().toArray(keys);
}
public static Class<? extends Generator> getGenerator(String name) {
name = name.toLowerCase(Locale.ROOT);
if (Generator.nameList.containsKey(name)) {
return Generator.nameList.get(name);
}
return OldNormal.class;
}
public static Class<? extends Generator> getGenerator(int type) {
if (Generator.typeList.containsKey(type)) {
return Generator.typeList.get(type);
}
return OldNormal.class;
}
public static String getGeneratorName(Class<? extends Generator> c) {
for (Map.Entry<String, Class<? extends Generator>> entry : Generator.nameList.entrySet()) {
if (entry.getValue() == c) {
return entry.getKey();
}
}
return "unknown";
}
public static int getGeneratorType(Class<? extends Generator> c) {
for (Map.Entry<Integer, Class<? extends Generator>> entry : Generator.typeList.entrySet()) {
if (entry.getValue() == c) {
return entry.getKey();
}
}
return Generator.TYPE_INFINITE;
}
public static CompoundTag loadNBT(final String path) {
try (final InputStream inputStream = Server.class.getClassLoader().getResourceAsStream(path)) {
return NBTIO.readCompressed(inputStream);
} catch (final IOException e) {
MainLogger.getLogger().error("Error while loading: " + path);
throw new RuntimeException(e);
}
}
public abstract void init(ChunkManager level, NukkitRandom random);
public abstract void populateStructure(final int chunkX, final int chunkZ);
public abstract void generateChunk(int chunkX, int chunkZ);
public abstract void populateChunk(int chunkX, int chunkZ);
public abstract Map<String, Object> getSettings();
public abstract String getName();
public abstract Vector3 getSpawn();
public abstract ChunkManager getChunkManager();
}
| 412 | 0.788218 | 1 | 0.788218 | game-dev | MEDIA | 0.930212 | game-dev | 0.950073 | 1 | 0.950073 |
Flipper76/Kali-Zero-Firmware | 5,863 | applications/external/nfc_magic/scenes/nfc_magic_scene_write.c | #include "../nfc_magic_app_i.h"
enum {
NfcMagicSceneWriteStateCardSearch,
NfcMagicSceneWriteStateCardFound,
};
NfcCommand nfc_mafic_scene_write_gen1_poller_callback(Gen1aPollerEvent event, void* context) {
NfcMagicApp* instance = context;
furi_assert(event.data);
NfcCommand command = NfcCommandContinue;
if(event.type == Gen1aPollerEventTypeDetected) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventCardDetected);
} else if(event.type == Gen1aPollerEventTypeRequestMode) {
event.data->request_mode.mode = Gen1aPollerModeWrite;
} else if(event.type == Gen1aPollerEventTypeRequestDataToWrite) {
const MfClassicData* mfc_data =
nfc_device_get_data(instance->source_dev, NfcProtocolMfClassic);
event.data->data_to_write.mfc_data = mfc_data;
} else if(event.type == Gen1aPollerEventTypeSuccess) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventWorkerSuccess);
command = NfcCommandStop;
} else if(event.type == Gen1aPollerEventTypeFail) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventWorkerFail);
command = NfcCommandStop;
}
return command;
}
NfcCommand nfc_mafic_scene_write_gen4_poller_callback(Gen4PollerEvent event, void* context) {
NfcMagicApp* instance = context;
furi_assert(event.data);
NfcCommand command = NfcCommandContinue;
if(event.type == Gen4PollerEventTypeCardDetected) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventCardDetected);
} else if(event.type == Gen4PollerEventTypeRequestMode) {
event.data->request_mode.mode = Gen4PollerModeWrite;
} else if(event.type == Gen4PollerEventTypeRequestDataToWrite) {
NfcProtocol protocol = nfc_device_get_protocol(instance->source_dev);
event.data->request_data.protocol = protocol;
event.data->request_data.data = nfc_device_get_data(instance->source_dev, protocol);
} else if(event.type == Gen4PollerEventTypeSuccess) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventWorkerSuccess);
command = NfcCommandStop;
} else if(event.type == Gen4PollerEventTypeFail) {
view_dispatcher_send_custom_event(
instance->view_dispatcher, NfcMagicCustomEventWorkerFail);
command = NfcCommandStop;
}
return command;
}
static void nfc_magic_scene_write_setup_view(NfcMagicApp* instance) {
Popup* popup = instance->popup;
popup_reset(popup);
uint32_t state = scene_manager_get_scene_state(instance->scene_manager, NfcMagicSceneWrite);
if(state == NfcMagicSceneWriteStateCardSearch) {
popup_set_icon(instance->popup, 0, 8, &I_NFC_manual_60x50);
popup_set_text(
instance->popup, "Apply the\nsame card\nto the back", 128, 32, AlignRight, AlignCenter);
} else {
popup_set_icon(popup, 12, 23, &I_Loading_24);
popup_set_header(popup, "Writing\nDon't move...", 52, 32, AlignLeft, AlignCenter);
}
view_dispatcher_switch_to_view(instance->view_dispatcher, NfcMagicAppViewPopup);
}
void nfc_magic_scene_write_on_enter(void* context) {
NfcMagicApp* instance = context;
scene_manager_set_scene_state(
instance->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch);
nfc_magic_scene_write_setup_view(instance);
nfc_magic_app_blink_start(instance);
if(instance->protocol == NfcMagicProtocolGen1) {
instance->gen1a_poller = gen1a_poller_alloc(instance->nfc);
gen1a_poller_start(
instance->gen1a_poller, nfc_mafic_scene_write_gen1_poller_callback, instance);
} else {
instance->gen4_poller = gen4_poller_alloc(instance->nfc);
gen4_poller_set_password(instance->gen4_poller, instance->gen4_password);
gen4_poller_start(
instance->gen4_poller, nfc_mafic_scene_write_gen4_poller_callback, instance);
}
}
bool nfc_magic_scene_write_on_event(void* context, SceneManagerEvent event) {
NfcMagicApp* instance = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == NfcMagicCustomEventCardDetected) {
scene_manager_set_scene_state(
instance->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardFound);
nfc_magic_scene_write_setup_view(instance);
consumed = true;
} else if(event.event == NfcMagicCustomEventCardLost) {
scene_manager_set_scene_state(
instance->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch);
nfc_magic_scene_write_setup_view(instance);
consumed = true;
} else if(event.event == NfcMagicCustomEventWorkerSuccess) {
scene_manager_next_scene(instance->scene_manager, NfcMagicSceneSuccess);
consumed = true;
} else if(event.event == NfcMagicCustomEventWorkerFail) {
scene_manager_next_scene(instance->scene_manager, NfcMagicSceneWriteFail);
consumed = true;
}
}
return consumed;
}
void nfc_magic_scene_write_on_exit(void* context) {
NfcMagicApp* instance = context;
if(instance->protocol == NfcMagicProtocolGen1) {
gen1a_poller_stop(instance->gen1a_poller);
gen1a_poller_free(instance->gen1a_poller);
} else {
gen4_poller_stop(instance->gen4_poller);
gen4_poller_free(instance->gen4_poller);
}
scene_manager_set_scene_state(
instance->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch);
// Clear view
popup_reset(instance->popup);
nfc_magic_app_blink_stop(instance);
}
| 412 | 0.976838 | 1 | 0.976838 | game-dev | MEDIA | 0.233317 | game-dev | 0.919306 | 1 | 0.919306 |
LingASDJ/Magic_Ling_Pixel_Dungeon | 6,292 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/special/NyzBombAndBooksRoom.java | //
// Decompiled by Jadx - 756ms
//
package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.special;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Nyz;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Heap;
import com.shatteredpixel.shatteredpixeldungeon.items.Honeypot;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.LeatherArmor;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.Bomb;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.Firebomb;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.Flashbang;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.FrostBomb;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.HolyBomb;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.Noisemaker;
import com.shatteredpixel.shatteredpixeldungeon.items.bombs.RegrowthBomb;
import com.shatteredpixel.shatteredpixeldungeon.items.books.bookslist.GrassKingBooks;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfMagicMapping;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTransmutation;
import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfAugmentation;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.Room;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
import java.util.ArrayList;
import java.util.Iterator;
public class NyzBombAndBooksRoom extends SpecialRoom {
private ArrayList<Item> itemsToSpawn;
public NyzBombAndBooksRoom() {
}
public int minWidth() {
return Math.max(4, (int) (Math.sqrt(itemCount()) + 3.0d));
}
public int minHeight() {
return Math.max(4, (int) (Math.sqrt(itemCount()) + 3.0d));
}
public int itemCount() {
if (this.itemsToSpawn == null) {
this.itemsToSpawn = generateItems();
}
return this.itemsToSpawn.size();
}
public void paint(Level level) {
Painter.fill(level, this, 4);
Painter.fill(level, this, 1, 14);
placeShopkeeper(level);
placeItems(level);
for (Room.Door door : this.connected.values()) {
door.set(Room.Door.Type.REGULAR);
}
}
protected void placeShopkeeper(Level level) {
int pos = level.pointToCell(center());
Mob nxhy = new Nyz();
nxhy.pos = pos;
level.mobs.add(nxhy);
}
protected void placeItems(Level level) {
if (this.itemsToSpawn == null) {
this.itemsToSpawn = generateItems();
}
Point itemPlacement = new Point(entrance());
if (itemPlacement.y == this.top) {
itemPlacement.y++;
} else if (itemPlacement.y == this.bottom) {
itemPlacement.y--;
} else if (itemPlacement.x == this.left) {
itemPlacement.x++;
} else {
itemPlacement.x--;
}
Iterator<Item> it = this.itemsToSpawn.iterator();
while (it.hasNext()) {
Item item = it.next();
if (itemPlacement.x == this.left + 1 && itemPlacement.y != this.top + 1) {
itemPlacement.y--;
} else if (itemPlacement.y == this.top + 1 && itemPlacement.x != this.right - 1) {
itemPlacement.x++;
} else if (itemPlacement.x != this.right - 1 || itemPlacement.y == this.bottom - 1) {
itemPlacement.x--;
} else {
itemPlacement.y++;
}
int cell = level.pointToCell(itemPlacement);
if (level.heaps.get(cell) != null) {
while (true) {
cell = level.pointToCell(random());
if (level.heaps.get(cell) == null && level.findMob(cell) == null) {
break;
}
}
}
level.drop( item, cell ).type = Heap.Type.FOR_SALE;
}
}
protected static ArrayList<Item> generateItems() {
Item rare;
ArrayList<Item> itemsToSpawn2 = new ArrayList<>();
Item w = Generator.random(Generator.wepTiers[3]);
//itemsToSpawn2.add(Generator.random(Generator.misTiers[4]).quantity(2).identify());
itemsToSpawn2.add(new LeatherArmor().identify());
w.cursed = false;
w.level(Random.Int(2,3));
w.identify();
itemsToSpawn2.add(w);
itemsToSpawn2.add (new Flashbang().quantity(1));
itemsToSpawn2.add (new Flashbang().quantity(1));
itemsToSpawn2.add (new Noisemaker().quantity(1));
itemsToSpawn2.add (new RegrowthBomb().quantity(1));
itemsToSpawn2.add (new HolyBomb().quantity(1));
itemsToSpawn2.add (new Firebomb().quantity(1));
itemsToSpawn2.add (new FrostBomb().quantity(1));
//itemsToSpawn2.add(new MerchantsBeacon());
itemsToSpawn2.add(new GrassKingBooks().quantity(1));
itemsToSpawn2.add(new ScrollOfTransmutation());
//itemsToSpawn2.add(new DriedRose());
itemsToSpawn2.add(new ScrollOfMagicMapping());
//itemsToSpawn2.add(new BookBag());
int Int = Random.Int(4);
if (Int == 0) {
itemsToSpawn2.add(new Bomb());
} else if (Int == 1 || Int == 2) {
itemsToSpawn2.add(new Bomb.DoubleBomb());
} else if (Int == 3) {
itemsToSpawn2.add(new Honeypot());
}
itemsToSpawn2.add(new StoneOfAugmentation());
int Int2 = Random.Int(10);
if (Int2 == 0) {
rare = Generator.random(Generator.Category.WAND);
rare.level(0);
} else if (Int2 == 1) {
rare = Generator.random(Generator.Category.SEED);
rare.level(0);
} else {
rare = Generator.random(Generator.Category.POTION);
}
rare.cursed = false;
rare.cursedKnown = true;
itemsToSpawn2.add(rare);
Random.shuffle(itemsToSpawn2);
return itemsToSpawn2;
}
}
| 412 | 0.845038 | 1 | 0.845038 | game-dev | MEDIA | 0.991433 | game-dev | 0.965033 | 1 | 0.965033 |
oriedita/oriedita | 9,591 | oriedita-data/src/main/java/oriedita/editor/databinding/GridModel.java | package oriedita.editor.databinding;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import oriedita.editor.AbstractModel;
import origami.Epsilon;
import java.io.Serializable;
@ApplicationScoped
public class GridModel extends AbstractModel implements Serializable {
private int intervalGridSize;
private int gridSize;
private double gridXA;
private double gridXB;
private double gridXC;
private double gridYA;
private double gridYB;
private double gridYC;
private double gridAngle;
private State baseState;
private int verticalScalePosition;
private int horizontalScalePosition;
private boolean drawDiagonalGridlines;
@Inject
public GridModel() {
reset();
}
public void reset() {
gridSize = 8;
baseState = State.WITHIN_PAPER;
gridAngle = 90.0;
horizontalScalePosition = 0;
verticalScalePosition = 0;
intervalGridSize = 4;
drawDiagonalGridlines = false;
resetGridX();
resetGridY();
notifyAllListeners();
}
public State getBaseState() {
return baseState;
}
public void setBaseState(State newBaseState) {
State oldBaseState = this.baseState;
this.baseState = newBaseState;
this.pcs.firePropertyChange("baseState", oldBaseState, newBaseState);
}
public void advanceBaseState() {
setBaseState(baseState.advance());
}
public boolean getDrawDiagonalGridlines() {
return drawDiagonalGridlines;
}
public void setDrawDiagonalGridlines(boolean newVal) {
this.drawDiagonalGridlines = newVal;
this.pcs.firePropertyChange("drawDiagonalGridlines", !newVal, newVal);
}
public int getVerticalScalePosition() {
return verticalScalePosition;
}
public void setVerticalScalePosition(int newVerticalScalePosition) {
int oldVerticalScalePosition = this.verticalScalePosition;
this.verticalScalePosition = newVerticalScalePosition;
this.pcs.firePropertyChange("verticalScalePosition", oldVerticalScalePosition, newVerticalScalePosition);
}
public int getHorizontalScalePosition() {
return horizontalScalePosition;
}
public void setHorizontalScalePosition(int newHorizontalScalePosition) {
int oldHorizontalScalePosition = this.horizontalScalePosition;
this.horizontalScalePosition = newHorizontalScalePosition;
this.pcs.firePropertyChange("horizontalScalePosition", oldHorizontalScalePosition, newHorizontalScalePosition);
}
public int getGridSize() {
return gridSize;
}
public void setGridSize(final int gridSize) {
int oldGridSize = this.gridSize;
this.gridSize = Math.max(gridSize, 1);
this.pcs.firePropertyChange("gridSize", oldGridSize, this.gridSize);
}
public double getGridXA() {
return gridXA;
}
public void applyGridX(double gridXA, double gridXB, double gridXC) {
if (validateGrid(gridXA, gridXB, gridXC)) {
this.gridXA = gridXA;
this.gridXB = gridXB;
this.gridXC = gridXC;
} else {
resetGridX();
}
}
public void setGridXA(final double gridXA) {
double oldGridXA = this.gridXA;
if (validateGrid(gridXA, gridXB, gridXC)) {
this.gridXA = gridXA;
} else {
resetGridX();
}
this.pcs.firePropertyChange("gridXA", oldGridXA, this.gridXA);
}
public double getGridXB() {
return gridXB;
}
public void setGridXB(final double gridXB) {
double oldGridXB = this.gridXB;
if (validateGrid(gridXA, gridXB, gridXC)) {
this.gridXB = gridXB;
} else {
resetGridX();
}
this.pcs.firePropertyChange("gridXB", oldGridXB, this.gridXB);
}
public int getIntervalGridSize() {
return intervalGridSize;
}
public void setIntervalGridSize(final int intervalGridSize) {
int oldIntervalGridSize = this.intervalGridSize;
this.intervalGridSize = Math.max(intervalGridSize, 1);
this.pcs.firePropertyChange("intervalGridSize", oldIntervalGridSize, this.intervalGridSize);
}
public double getGridXC() {
return gridXC;
}
public void setGridXC(final double gridXC) {
double oldGridXC = this.gridXC;
if (validateGrid(gridXA, gridXB, gridXC)) {
this.gridXC = Math.max(gridXC, 0.0);
} else {
resetGridX();
}
this.pcs.firePropertyChange("gridXC", oldGridXC, this.gridXC);
}
public double getGridYA() {
return gridYA;
}
public void applyGridY(double gridYA, double gridYB, double gridYC) {
if (validateGrid(gridYA, gridYB, gridYC)) {
this.gridYA = gridYA;
this.gridYB = gridYB;
this.gridYC = gridYC;
} else {
resetGridY();
}
}
public void setGridYA(final double gridYA) {
double oldGridYA = this.gridYA;
if (validateGrid(gridYA, gridYB, gridYC)) {
this.gridYA = gridYA;
} else {
resetGridY();
}
this.pcs.firePropertyChange("gridYA", oldGridYA, this.gridYA);
}
public double getGridYB() {
return gridYB;
}
public void setGridYB(final double gridYB) {
double oldGridYB = this.gridYB;
if (validateGrid(gridYA, gridYB, gridYC)) {
this.gridYB = gridYB;
} else {
resetGridY();
}
this.pcs.firePropertyChange("gridYB", oldGridYB, this.gridYB);
}
public double getGridYC() {
return gridYC;
}
public void setGridYC(final double gridYC) {
double oldGridYC = this.gridYC;
if (validateGrid(gridYA, gridYB, gridYC)) {
this.gridYC = Math.max(gridYC, 0.0);
} else {
resetGridY();
}
this.pcs.firePropertyChange("gridYC", oldGridYC, this.gridYC);
}
public double getGridAngle() {
return gridAngle;
}
public void setGridAngle(final double gridAngle) {
double oldAngle = this.gridAngle;
double newAngle = gridAngle;
if (newAngle < Epsilon.GRID_ANGLE_THRESHOLD)
newAngle = Epsilon.GRID_ANGLE_THRESHOLD;
else if(newAngle > 180.0 - Epsilon.GRID_ANGLE_THRESHOLD){
newAngle = 180.0 - Epsilon.GRID_ANGLE_THRESHOLD;
}
this.gridAngle = newAngle;
this.pcs.firePropertyChange("gridAngle", oldAngle, newAngle);
}
private boolean validateGrid(double a, double b, double c) {
double gridLength = a + b * Math.sqrt(c);
if (gridLength < 0.0) {
return false;
}
return !(Math.abs(gridLength) < Epsilon.UNKNOWN_1EN4);
}
public double determineGridXLength() {
return gridXA + gridXB * Math.sqrt(gridXC);
}
public double determineGridYLength() {
return gridYA + gridYB * Math.sqrt(gridYC);
}
public void resetGridY() {
gridYA = 1.0;
gridYB = 0.0;
gridYC = 1.0;
}
public void resetGridX() {
gridXA = 1.0;
gridXB = 0.0;
gridXC = 1.0;
}
public void changeHorizontalScalePosition() {
int horizontalScalePosition = this.horizontalScalePosition + 1;
if (horizontalScalePosition >= intervalGridSize) {
horizontalScalePosition = 0;
}
setHorizontalScalePosition(horizontalScalePosition);
}
public void changeVerticalScalePosition() {
int verticalScalePosition = this.verticalScalePosition + 1;
if (verticalScalePosition >= intervalGridSize) {
verticalScalePosition = 0;
}
setVerticalScalePosition(verticalScalePosition);
}
public void set(GridModel gridModel) {
intervalGridSize = gridModel.getIntervalGridSize();
gridSize = gridModel.getGridSize();
gridXA = gridModel.getGridXA();
gridXB = gridModel.getGridXB();
gridXC = gridModel.getGridXC();
gridYA = gridModel.getGridYA();
gridYB = gridModel.getGridYB();
gridYC = gridModel.getGridYC();
gridAngle = gridModel.getGridAngle();
baseState = gridModel.getBaseState();
verticalScalePosition = gridModel.getVerticalScalePosition();
horizontalScalePosition = gridModel.getHorizontalScalePosition();
drawDiagonalGridlines = gridModel.getDrawDiagonalGridlines();
notifyAllListeners();
}
/**
* The state of the grid, either within the paper, spanning the whole screen or hidden.
*/
public enum State {
HIDDEN(0),
WITHIN_PAPER(1),
FULL(2);
final int state;
State(int state) {
this.state = state;
}
public static State from(String state) {
return from(Integer.parseInt(state));
}
public static State from(int state) {
for (State val : State.values()) {
if (val.getState() == state) {
return val;
}
}
throw new IllegalArgumentException();
}
public State advance() {
return values()[(ordinal() + 1) % values().length];
}
public int getState() {
return state;
}
@Override
public String toString() {
return Integer.toString(state);
}
}
} | 412 | 0.68186 | 1 | 0.68186 | game-dev | MEDIA | 0.431185 | game-dev | 0.691863 | 1 | 0.691863 |
PlatformLab/HomaModule | 22,825 | test/unit_homa_skb.c | // SPDX-License-Identifier: BSD-2-Clause or GPL-2.0+
#include "homa_impl.h"
#include "homa_skb.h"
#define KSELFTEST_NOT_MAIN 1
#include "kselftest_harness.h"
#include "ccutils.h"
#include "mock.h"
#include "utils.h"
static inline struct homa_skb_core *get_skb_core(int core)
{
return &per_cpu(homa_skb_core, core);
}
/* Create an skb with 100 bytes of data in the header and frags of
* 200, 300, and 400 bytes.
*/
static struct sk_buff *test_skb(struct homa *homa)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct sk_buff *skb = homa_skb_alloc_tx(100);
int32_t data[1000];
char *src;
int i;
for (i = 0; i < 1000; i++)
data[i] = 1000000 + 4*i;
src = (char *) data;
memcpy(skb_put(skb, 100), src, 100);
/* Make sure that the first skb fragment will have a nonzero offset
* within its page.
*/
homa_skb_page_alloc(homa, skb_core);
skb_core->page_inuse = 100;
homa_skb_append_to_frag(homa, skb, src + 100, 200);
skb_core->page_inuse = skb_core->page_size;
homa_skb_append_to_frag(homa, skb, src + 300, 300);
skb_core->page_inuse = skb_core->page_size;
homa_skb_append_to_frag(homa, skb, src + 600, 400);
/* Add some data before the transport header, just to make sure
* that functions offset from the proper location.
*/
skb_push(skb, 8);
return skb;
}
/* Add a given number of pages to the page pool for a given core. */
static void add_to_pool(struct homa *homa, int num_pages, int core)
{
struct homa_page_pool *pool = get_skb_core(core)->pool;
int i;
for (i = 0; i < num_pages; i++) {
pool->pages[pool->avail] = alloc_pages(GFP_KERNEL,
HOMA_SKB_PAGE_ORDER);
pool->avail++;
}
}
static struct homa_page_pool *hook_pool;
/* Used to remove a page from hook_pool in a race. */
static void page_alloc_race_hook(char *id)
{
if (strcmp(id, "skb_page_alloc_race") != 0)
return;
if ((hook_pool == NULL) || (hook_pool->avail == 0))
return;
hook_pool->avail--;
put_page(hook_pool->pages[hook_pool->avail]);
}
FIXTURE(homa_skb) {
struct homa homa;
struct sk_buff *skb;
};
FIXTURE_SETUP(homa_skb)
{
homa_init(&self->homa);
self->skb = alloc_skb_fclone(200, GFP_KERNEL);
if (!self->skb)
FAIL("unit_homa_skb setup couldn't allocate skb");
}
FIXTURE_TEARDOWN(homa_skb)
{
kfree_skb(self->skb);
homa_destroy(&self->homa);
unit_teardown();
}
TEST_F(homa_skb, homa_skb_init__success)
{
homa_skb_cleanup(&self->homa);
EXPECT_EQ(NULL, self->homa.page_pools[0]);
mock_numa_mask = 0x83;
EXPECT_EQ(0, homa_skb_init(&self->homa));
EXPECT_NE(NULL, self->homa.page_pools[0]);
EXPECT_NE(NULL, self->homa.page_pools[1]);
EXPECT_EQ(NULL, self->homa.page_pools[2]);
EXPECT_EQ(self->homa.page_pools[1], get_skb_core(0)->pool);
EXPECT_EQ(self->homa.page_pools[1], get_skb_core(1)->pool);
EXPECT_EQ(self->homa.page_pools[0], get_skb_core(2)->pool);
EXPECT_EQ(self->homa.page_pools[0], get_skb_core(6)->pool);
EXPECT_EQ(self->homa.page_pools[1], get_skb_core(7)->pool);
EXPECT_EQ(1, self->homa.max_numa);
}
TEST_F(homa_skb, homa_skb_init__kmalloc_failure)
{
homa_skb_cleanup(&self->homa);
EXPECT_EQ(NULL, self->homa.page_pools[0]);
mock_numa_mask = 0x2;
mock_kmalloc_errors = 0x2;
EXPECT_EQ(ENOMEM, -homa_skb_init(&self->homa));
EXPECT_NE(NULL, self->homa.page_pools[0]);
EXPECT_EQ(NULL, self->homa.page_pools[1]);
EXPECT_EQ(NULL, self->homa.page_pools[2]);
}
TEST_F(homa_skb, homa_skb_cleanup)
{
struct homa_skb_core *skb_core = get_skb_core(2);
skb_core->skb_page = alloc_pages(GFP_KERNEL, 2);
add_to_pool(&self->homa, 5, 2);
add_to_pool(&self->homa, 4, 3);
mock_set_core(3);
homa_skb_stash_pages(&self->homa, 2 * HOMA_SKB_PAGE_SIZE - 100);
EXPECT_EQ(5, get_skb_core(2)->pool->avail);
EXPECT_EQ(2, get_skb_core(3)->pool->avail);
EXPECT_EQ(2, get_skb_core(3)->num_stashed_pages);
homa_skb_cleanup(&self->homa);
EXPECT_EQ(NULL, skb_core->pool);
EXPECT_EQ(NULL, skb_core->skb_page);
EXPECT_EQ(0, get_skb_core(3)->num_stashed_pages);
skb_core = get_skb_core(nr_cpu_ids-1);
EXPECT_EQ(NULL, skb_core->pool);
}
TEST_F(homa_skb, homa_skb_stash_pages)
{
int id = smp_processor_id();
struct homa_skb_core *skb_core;
skb_core = get_skb_core(id);
add_to_pool(&self->homa, 5, id);
EXPECT_EQ(5, skb_core->pool->avail);
EXPECT_EQ(0, skb_core->num_stashed_pages);
/* First attempt: message too small. */
homa_skb_stash_pages(&self->homa, 10000);
EXPECT_EQ(0, skb_core->num_stashed_pages);
/* Second attempt: stash pages. */
homa_skb_stash_pages(&self->homa, 3*HOMA_SKB_PAGE_SIZE - 100);
EXPECT_EQ(3, skb_core->num_stashed_pages);
EXPECT_EQ(2, skb_core->pool->avail);
/* Third attempt: existing stash adequate. */
homa_skb_stash_pages(&self->homa, 3 * HOMA_SKB_PAGE_SIZE - 100);
EXPECT_EQ(3, skb_core->num_stashed_pages);
/* Fourth attempt: not enough pages in pool. */
homa_skb_stash_pages(&self->homa, 8 * HOMA_SKB_PAGE_SIZE - 100);
EXPECT_EQ(5, skb_core->num_stashed_pages);
}
TEST_F(homa_skb, homa_skb_extend_frags__basics)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
char *p1, *p2, *p3;
int length = 100;
p1 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(100, length);
EXPECT_NE(NULL, p1);
length = 200;
p2 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(200, length);
EXPECT_EQ(p1 + 100, p2);
length = 300;
p3 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(300, length);
EXPECT_EQ(p2 + 200, p3);
EXPECT_EQ(600, skb_core->page_inuse);
EXPECT_EQ(600, self->skb->len);
}
TEST_F(homa_skb, homa_skb_extend_frags__merge_but_reduce_length)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
int length = 1000;
char *p1, *p2;
p1 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(1000, length);
EXPECT_NE(NULL, p1);
skb_core->page_size = 2048;
length = 2000;
p2 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(1048, length);
EXPECT_EQ(p1 + 1000, p2);
EXPECT_EQ(2048, skb_core->page_inuse);
}
TEST_F(homa_skb, homa_skb_extend_frags__cant_merge_allocate_new_page)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct sk_buff *skb2 = alloc_skb_fclone(200, GFP_KERNEL);
char *p1, *p2, *p3;
int length;
ASSERT_NE(NULL, skb2);
length = 1000;
p1 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(1000, length);
EXPECT_NE(NULL, p1);
EXPECT_EQ(1000, self->skb->len);
skb_core->page_size = 2048;
length = 1000;
p2 = homa_skb_extend_frags(&self->homa, skb2, &length);
EXPECT_EQ(1000, length);
EXPECT_EQ(p1 + 1024, p2);
EXPECT_EQ(1000, skb2->len);
length = 1000;
p3 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_NE(NULL, p3);
EXPECT_EQ(1000, length);
EXPECT_EQ(2, skb_shinfo(self->skb)->nr_frags);
EXPECT_EQ(0, skb_shinfo(self->skb)->frags[1].offset);
EXPECT_EQ(2000, self->skb->len);
EXPECT_EQ(1000, skb_core->page_inuse);
kfree_skb(skb2);
}
TEST_F(homa_skb, homa_skb_extend_frags__cant_merge_use_same_page_reduce_length)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct sk_buff *skb2 = alloc_skb_fclone(200, GFP_KERNEL);
char *p1, *p2, *p3;
int length;
ASSERT_NE(NULL, skb2);
length = 1000;
p1 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(1000, length);
EXPECT_NE(NULL, p1);
skb_core->page_size = 2048;
length = 500;
p2 = homa_skb_extend_frags(&self->homa, skb2, &length);
EXPECT_EQ(500, length);
EXPECT_EQ(p1 + 1024, p2);
length = 2000;
p3 = homa_skb_extend_frags(&self->homa, self->skb, &length);
EXPECT_EQ(p2 + 512, p3);
EXPECT_EQ(512, length);
EXPECT_EQ(2, skb_shinfo(self->skb)->nr_frags);
EXPECT_EQ(1536, skb_shinfo(self->skb)->frags[1].offset);
EXPECT_EQ(2048, skb_core->page_inuse);
kfree_skb(skb2);
}
TEST_F(homa_skb, homa_skb_page_alloc__free_previous_page)
{
struct homa_skb_core *skb_core = get_skb_core(2);
struct page *old_page;
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
old_page = skb_core->skb_page;
get_page(old_page);
EXPECT_EQ(2, mock_page_refs(old_page));
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_NE(old_page, skb_core->skb_page);
EXPECT_EQ(1, mock_page_refs(old_page));
put_page(old_page);
}
TEST_F(homa_skb, homa_skb_page_alloc__reuse_existing_page)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct sk_buff *skb = homa_skb_alloc_tx(100);
struct page *page;
int length = 100;
homa_skb_extend_frags(&self->homa, skb, &length);
EXPECT_EQ(100, skb_core->page_inuse);
page = skb_core->skb_page;
homa_skb_free_tx(&self->homa, skb);
EXPECT_EQ(1, page_ref_count(skb_core->skb_page));
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_EQ(page, skb_core->skb_page);
EXPECT_EQ(0, skb_core->page_inuse);
}
TEST_F(homa_skb, homa_skb_page_alloc__from_stash)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
add_to_pool(&self->homa, 5, smp_processor_id());
homa_skb_stash_pages(&self->homa, 3*HOMA_SKB_PAGE_SIZE - 100);
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_EQ(HOMA_SKB_PAGE_SIZE, skb_core->page_size);
EXPECT_EQ(0, skb_core->page_inuse);
EXPECT_EQ(2, skb_core->num_stashed_pages);
}
TEST_F(homa_skb, homa_skb_page_alloc__from_pool)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
add_to_pool(&self->homa, 5, smp_processor_id());
EXPECT_EQ(5, skb_core->pool->avail);
EXPECT_EQ(0, skb_core->num_stashed_pages);
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_EQ(4, skb_core->pool->avail);
}
TEST_F(homa_skb, homa_skb_page_alloc__pool_page_taken_while_locking)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
add_to_pool(&self->homa, 1, smp_processor_id());
EXPECT_EQ(1, skb_core->pool->avail);
EXPECT_EQ(0, skb_core->num_stashed_pages);
hook_pool = skb_core->pool;
unit_hook_register(page_alloc_race_hook);
mock_alloc_page_errors = 3;
EXPECT_FALSE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_EQ(NULL, skb_core->skb_page);
EXPECT_EQ(0, skb_core->pool->avail);
}
TEST_F(homa_skb, homa_skb_page_alloc__new_large_page)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
mock_clock_tick = 100;
EXPECT_EQ(0, skb_core->pool->avail);
EXPECT_EQ(0, skb_core->num_stashed_pages);
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_EQ(HOMA_SKB_PAGE_SIZE, skb_core->page_size);
EXPECT_EQ(1, homa_metrics_per_cpu()->skb_page_allocs);
EXPECT_EQ(100, homa_metrics_per_cpu()->skb_page_alloc_cycles);
}
TEST_F(homa_skb, homa_skb_page_alloc__high_order_page_not_available)
{
struct homa_skb_core *skb_core = get_skb_core(2);
mock_clock_tick = 50;
mock_alloc_page_errors = 1;
EXPECT_TRUE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_NE(NULL, skb_core->skb_page);
EXPECT_EQ(PAGE_SIZE, skb_core->page_size);
EXPECT_EQ(0, skb_core->page_inuse);
EXPECT_EQ(1, homa_metrics_per_cpu()->skb_page_allocs);
EXPECT_EQ(50, homa_metrics_per_cpu()->skb_page_alloc_cycles);
}
TEST_F(homa_skb, homa_skb_page_alloc__no_pages_available)
{
struct homa_skb_core *skb_core = get_skb_core(2);
mock_alloc_page_errors = 3;
EXPECT_FALSE(homa_skb_page_alloc(&self->homa, skb_core));
EXPECT_EQ(NULL, skb_core->skb_page);
}
TEST_F(homa_skb, homa_skb_append_to_frag__basics)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct skb_shared_info *shinfo = skb_shinfo(self->skb);
char *p;
/* First append fits in a single block. */
EXPECT_EQ(0, homa_skb_append_to_frag(&self->homa, self->skb, "abcd", 4));
/* Second append spills into a new frag. */
skb_core->page_size = 10;
EXPECT_EQ(0, homa_skb_append_to_frag(&self->homa, self->skb,
"0123456789ABCDEFGHIJ", 21));
EXPECT_EQ(2, shinfo->nr_frags);
EXPECT_EQ(10, skb_frag_size(&shinfo->frags[0]));
p = ((char *) page_address(skb_frag_page(&shinfo->frags[0])))
+ shinfo->frags[0].offset;
p[skb_frag_size(&shinfo->frags[0])] = 0;
EXPECT_STREQ("abcd012345", p);
EXPECT_EQ(15, skb_frag_size(&shinfo->frags[1]));
p = ((char *) page_address(skb_frag_page(&shinfo->frags[1])))
+ shinfo->frags[1].offset;
EXPECT_STREQ("6789ABCDEFGHIJ", p);
}
TEST_F(homa_skb, homa_skb_append_to_frag__no_memory)
{
mock_alloc_page_errors = 3;
EXPECT_EQ(ENOMEM, -homa_skb_append_to_frag(&self->homa, self->skb,
"abcd", 4));
}
TEST_F(homa_skb, homa_skb_append_from_iter__basics)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct iov_iter *iter = unit_iov_iter((void *) 1000, 5000);
struct skb_shared_info *shinfo = skb_shinfo(self->skb);
/* First append fits in a single block. */
unit_log_clear();
EXPECT_EQ(0, homa_skb_append_from_iter(&self->homa, self->skb, iter,
2000));
EXPECT_STREQ("_copy_from_iter 2000 bytes at 1000",
unit_log_get());
/* Second append spills into a new frag. */
skb_core->page_size = 4096;
unit_log_clear();
EXPECT_EQ(0, homa_skb_append_from_iter(&self->homa, self->skb, iter,
3000));
EXPECT_STREQ("_copy_from_iter 2096 bytes at 3000; "
"_copy_from_iter 904 bytes at 5096",
unit_log_get());
EXPECT_EQ(2, shinfo->nr_frags);
EXPECT_EQ(4096, skb_frag_size(&shinfo->frags[0]));
EXPECT_EQ(904, skb_frag_size(&shinfo->frags[1]));
}
TEST_F(homa_skb, homa_skb_append_from_iter__no_memory)
{
struct iov_iter *iter = unit_iov_iter((void *)1000, 5000);
mock_alloc_page_errors = 3;
EXPECT_EQ(ENOMEM, -homa_skb_append_from_iter(&self->homa, self->skb,
iter, 2000));
}
TEST_F(homa_skb, homa_skb_append_from_skb__header_only)
{
struct sk_buff *src_skb = test_skb(&self->homa);
struct sk_buff *dst_skb = homa_skb_alloc_tx(100);
int32_t data[500];
EXPECT_EQ(0, homa_skb_append_from_skb(&self->homa, dst_skb, src_skb,
20, 60));
memset(data, 0, sizeof(data));
homa_skb_get(dst_skb, data, 0, 60);
EXPECT_EQ(1000020, data[0]);
EXPECT_EQ(1000076, data[14]);
kfree_skb(src_skb);
kfree_skb(dst_skb);
}
TEST_F(homa_skb, homa_skb_append_from_skb__error_copying_header)
{
struct homa_skb_core *skb_core = get_skb_core(smp_processor_id());
struct sk_buff *src_skb = test_skb(&self->homa);
struct sk_buff *dst_skb = homa_skb_alloc_tx(100);
mock_alloc_page_errors = -1;
skb_core->page_inuse = skb_core->page_size;
EXPECT_EQ(ENOMEM, -homa_skb_append_from_skb(&self->homa, dst_skb,
src_skb, 20, 60));
kfree_skb(src_skb);
kfree_skb(dst_skb);
}
TEST_F(homa_skb, homa_skb_append_from_skb__header_and_first_frag)
{
struct sk_buff *src_skb = test_skb(&self->homa);
struct sk_buff *dst_skb = homa_skb_alloc_tx(100);
struct skb_shared_info *dst_shinfo;
int32_t data[500];
dst_shinfo = skb_shinfo(dst_skb);
EXPECT_EQ(0, homa_skb_append_from_skb(&self->homa, dst_skb, src_skb,
80, 100));
memset(data, 0, sizeof(data));
homa_skb_get(dst_skb, data, 0, 100);
EXPECT_EQ(1000080, data[0]);
EXPECT_EQ(1000176, data[24]);
EXPECT_EQ(2, dst_shinfo->nr_frags);
EXPECT_EQ(100, dst_skb->len);
kfree_skb(src_skb);
kfree_skb(dst_skb);
}
TEST_F(homa_skb, homa_skb_append_from_skb__multiple_frags)
{
struct sk_buff *src_skb = test_skb(&self->homa);
struct sk_buff *dst_skb = homa_skb_alloc_tx(100);
struct skb_shared_info *dst_shinfo;
int32_t data[500];
dst_shinfo = skb_shinfo(dst_skb);
EXPECT_EQ(0, homa_skb_append_from_skb(&self->homa, dst_skb, src_skb,
320, 600));
memset(data, 0, sizeof(data));
homa_skb_get(dst_skb, data, 0, 600);
EXPECT_EQ(1000320, data[0]);
EXPECT_EQ(1000916, data[149]);
EXPECT_EQ(2, dst_shinfo->nr_frags);
EXPECT_EQ(600, dst_skb->len);
kfree_skb(src_skb);
kfree_skb(dst_skb);
}
TEST_F(homa_skb, homa_skb_append_from_skb__dst_runs_out_of_frags)
{
struct sk_buff *src_skb = test_skb(&self->homa);
struct sk_buff *dst_skb = homa_skb_alloc_tx(100);
struct skb_shared_info *dst_shinfo;
int i, err;
dst_shinfo = skb_shinfo(dst_skb);
mock_max_skb_frags = 4;
for (i = 0; i < 10; i++) {
err = homa_skb_append_from_skb(&self->homa, dst_skb, src_skb,
320, 40);
if (err)
break;
}
EXPECT_EQ(4, i);
EXPECT_EQ(EINVAL, -err);
EXPECT_EQ(4, dst_shinfo->nr_frags);
kfree_skb(src_skb);
kfree_skb(dst_skb);
}
TEST_F(homa_skb, homa_skb_free_many_tx__basics)
{
struct sk_buff *skbs[2];
int i, length;
skbs[0] = homa_skb_alloc_tx(100);
for (i = 0; i < 3; i++) {
length = 2*HOMA_SKB_PAGE_SIZE;
homa_skb_extend_frags(&self->homa, skbs[0], &length);
}
EXPECT_EQ(HOMA_SKB_PAGE_SIZE, length);
skbs[1] = homa_skb_alloc_tx(100);
length = 2 * HOMA_SKB_PAGE_SIZE;
homa_skb_extend_frags(&self->homa, skbs[1], &length);
homa_skb_free_many_tx(&self->homa, skbs, 2);
EXPECT_EQ(3, self->homa.page_pools[0]->avail);
}
TEST_F(homa_skb, homa_skb_free_many_tx__skb_ref_count_not_one)
{
struct sk_buff *skb;
struct page *page;
int length;
skb = homa_skb_alloc_tx(100);
length = HOMA_SKB_PAGE_SIZE;
homa_skb_extend_frags(&self->homa, skb, &length);
EXPECT_EQ(HOMA_SKB_PAGE_SIZE, length);
page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
EXPECT_EQ(2, page_ref_count(page));
skb_get(skb);
EXPECT_EQ(2, refcount_read(&skb->users));
homa_skb_free_many_tx(&self->homa, &skb, 1);
EXPECT_EQ(2, page_ref_count(page));
EXPECT_EQ(1, refcount_read(&skb->users));
kfree_skb(skb);
}
TEST_F(homa_skb, homa_skb_free_many_tx__check_page_order)
{
struct sk_buff *skb;
int i, length;
skb = homa_skb_alloc_tx(100);
for (i = 0; i < 4; i++) {
length = 2 * HOMA_SKB_PAGE_SIZE;
homa_skb_extend_frags(&self->homa, skb, &length);
}
EXPECT_EQ(HOMA_SKB_PAGE_SIZE, length);
struct page *page = skb_frag_page(&skb_shinfo(skb)->frags[2]);
mock_compound_order_mask = 3;
homa_skb_free_many_tx(&self->homa, &skb, 1);
EXPECT_EQ(1, self->homa.page_pools[0]->avail);
EXPECT_EQ(page, self->homa.page_pools[0]->pages[0]);
}
TEST_F(homa_skb, homa_skb_cache_pages__different_numa_nodes)
{
struct page *pages[4];
int i;
for (i = 0; i < 4; i++)
pages[i] = alloc_pages(GFP_KERNEL, HOMA_SKB_PAGE_ORDER);
mock_page_nid_mask = 7;
homa_skb_cache_pages(&self->homa, pages, 4);
EXPECT_EQ(1, self->homa.page_pools[0]->avail);
EXPECT_EQ(3, self->homa.page_pools[1]->avail);
EXPECT_EQ(pages[3], self->homa.page_pools[0]->pages[0]);
EXPECT_EQ(pages[1], self->homa.page_pools[1]->pages[1]);
}
TEST_F(homa_skb, homa_skb_cache_pages__pool_size_exceeded)
{
struct page *pages[6];
int i;
for (i = 0; i < 6; i++)
pages[i] = alloc_pages(GFP_KERNEL, HOMA_SKB_PAGE_ORDER);
homa_skb_cache_pages(&self->homa, pages, 4);
EXPECT_EQ(4, self->homa.page_pools[0]->avail);
put_page(pages[4]);
put_page(pages[5]);
}
TEST_F(homa_skb, homa_skb_get)
{
struct sk_buff *skb = test_skb(&self->homa);
int32_t data[500];
/* Data is entirely in the head. */
memset(data, 0, sizeof(data));
homa_skb_get(skb, data, 20, 40);
EXPECT_EQ(1000020, data[0]);
EXPECT_EQ(1000056, data[9]);
EXPECT_EQ(0, data[10]);
/* Data spans head and first frag. */
memset(data, 0, sizeof(data));
homa_skb_get(skb, data, 80, 60);
EXPECT_EQ(1000080, data[0]);
EXPECT_EQ(1000096, data[4]);
EXPECT_EQ(1000100, data[5]);
EXPECT_EQ(1000136, data[14]);
EXPECT_EQ(0, data[15]);
/* Data spans 3 frags. */
memset(data, 0, sizeof(data));
homa_skb_get(skb, data, 280, 500);
EXPECT_EQ(1000280, data[0]);
EXPECT_EQ(1000296, data[4]);
EXPECT_EQ(1000300, data[5]);
EXPECT_EQ(1000596, data[79]);
EXPECT_EQ(1000600, data[80]);
EXPECT_EQ(1000776, data[124]);
EXPECT_EQ(0, data[125]);
/* Data extends past end of skb. */
memset(data, 0, sizeof(data));
homa_skb_get(skb, data, 960, 100);
EXPECT_EQ(1000960, data[0]);
EXPECT_EQ(1000996, data[9]);
EXPECT_EQ(0, data[10]);
kfree_skb(skb);
}
TEST_F(homa_skb, homa_skb_release_pages__basics)
{
EXPECT_EQ(0UL, self->homa.skb_page_free_time);
mock_clock = 1000000;
self->homa.skb_page_free_time = 500000;
self->homa.skb_page_frees_per_sec = 10;
self->homa.skb_page_pool_min_kb = 0;
add_to_pool(&self->homa, 10, 0);
get_skb_core(0)->pool->low_mark = 7;
add_to_pool(&self->homa, 3, 1);
get_skb_core(1)->pool->low_mark = 2;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(5, get_skb_core(0)->pool->avail);
EXPECT_EQ(3, get_skb_core(1)->pool->avail);
EXPECT_EQ(501000000UL, self->homa.skb_page_free_time);
}
TEST_F(homa_skb, homa_skb_release_pages__not_time_to_free)
{
EXPECT_EQ(0UL, self->homa.skb_page_free_time);
mock_clock = 1000000;
self->homa.skb_page_free_time = 1000001;
self->homa.skb_page_frees_per_sec = 10;
self->homa.skb_page_pool_min_kb = 0;
add_to_pool(&self->homa, 10, 0);
get_skb_core(0)->pool->low_mark = 7;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(10, get_skb_core(0)->pool->avail);
}
TEST_F(homa_skb, homa_skb_release_pages__allocate_skb_pages_to_free)
{
EXPECT_EQ(0, self->homa.pages_to_free_slots);
mock_clock= 1000000;
self->homa.skb_page_frees_per_sec = 10;
self->homa.skb_page_free_time = 500000;
/* First call: no current allocation. */
homa_skb_release_pages(&self->homa);
EXPECT_EQ(5, self->homa.pages_to_free_slots);
/* Second call: free current allocation. */
self->homa.pages_to_free_slots -= 1;
self->homa.skb_page_free_time = 500000;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(5, self->homa.pages_to_free_slots);
}
TEST_F(homa_skb, homa_skb_release_pages__cant_reallocate_skb_pages_to_free)
{
struct homa_page_pool *pool;
EXPECT_EQ(0UL, self->homa.skb_page_free_time);
mock_clock = 1000000;
self->homa.skb_page_free_time = 500000;
self->homa.skb_page_frees_per_sec = 20;
self->homa.skb_page_pool_min_kb = 0;
add_to_pool(&self->homa, 20, 0);
pool = get_skb_core(0)->pool;
pool->low_mark = 15;
EXPECT_EQ(0, self->homa.pages_to_free_slots);
self->homa.skb_pages_to_free = kmalloc_array(4, sizeof(struct page *),
GFP_ATOMIC);
self->homa.pages_to_free_slots = 4;
mock_kmalloc_errors = 1;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(16, get_skb_core(0)->pool->avail);
EXPECT_EQ(4, self->homa.pages_to_free_slots);
}
TEST_F(homa_skb, homa_skb_release_pages__limited_by_min_kb)
{
EXPECT_EQ(0UL, self->homa.skb_page_free_time);
mock_clock = 1000000;
self->homa.skb_page_free_time = 500000;
self->homa.skb_page_frees_per_sec = 20;
self->homa.skb_page_pool_min_kb = (5 * HOMA_SKB_PAGE_SIZE) / 1000;
add_to_pool(&self->homa, 10, 0);
get_skb_core(0)->pool->low_mark = 9;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(6, get_skb_core(0)->pool->avail);
}
TEST_F(homa_skb, homa_skb_release_pages__empty_pool)
{
EXPECT_EQ(0UL, self->homa.skb_page_free_time);
mock_clock= 2000000;
self->homa.skb_page_free_time = 500000;
self->homa.skb_page_frees_per_sec = 1000;
self->homa.skb_page_pool_min_kb = 0;
add_to_pool(&self->homa, 5, 0);
get_skb_core(0)->pool->low_mark = 5;
homa_skb_release_pages(&self->homa);
EXPECT_EQ(0, get_skb_core(0)->pool->avail);
}
| 412 | 0.795413 | 1 | 0.795413 | game-dev | MEDIA | 0.184269 | game-dev | 0.77722 | 1 | 0.77722 |
ProjectEQ/projecteqquests | 1,373 | poknowledge/Crusader_Gimil.pl | #Crusader_Gimil.pl
#Paladin Tomes/Planar Armor Exchange
# items: 4851, 4852, 4853, 4854, 4855, 4856, 4857, 10028, 10037, 22503, 15981
sub EVENT_SAY {
if($text=~/Hail/i){
quest::say("kneels low before $name, offering a humble gesture of respect and greetings. 'The light of Selia embraces thee, my friend. If you reside in our midst in searching for knowledge and guidance, then know that we are your servants in that quest. Should you be a paladin, and your object of faith is of no consequence in this matter, then my services are humbly at your disposal should you need or wish them.'");
}
}
sub EVENT_ITEM {
if((plugin::check_handin(\%itemcount, 4851 => 1)) ||
(plugin::check_handin(\%itemcount, 4852 => 1)) ||
(plugin::check_handin(\%itemcount, 4853 => 1)) ||
(plugin::check_handin(\%itemcount, 4854 => 1)) ||
(plugin::check_handin(\%itemcount, 4855 => 1)) ||
(plugin::check_handin(\%itemcount, 4856 => 1)) ||
(plugin::check_handin(\%itemcount, 4857 => 1))) {#Valorium Armor
quest::say("Thank you, $name.");#Text made up
quest::summonitem(quest::ChooseRandom(10028, 10037, 22503, 15981));#Random gem: Peridot, Diamond, Blue Diamond, Raw Diamond
quest::exp(698775);
}
plugin::try_tome_handins(\%itemcount, $class, 'Paladin');
plugin::return_items(\%itemcount);
}
#END of FILE Zone:poknowledge ID:202237 -- Crusader_Gimil | 412 | 0.889709 | 1 | 0.889709 | game-dev | MEDIA | 0.892403 | game-dev,web-backend | 0.862294 | 1 | 0.862294 |
insthync/LiteNetLibManager | 4,214 | Plugins/UniTask/Runtime/Linq/Pairwise.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IUniTaskAsyncEnumerable<(TSource, TSource)> Pairwise<TSource>(this IUniTaskAsyncEnumerable<TSource> source)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new Pairwise<TSource>(source);
}
}
internal sealed class Pairwise<TSource> : IUniTaskAsyncEnumerable<(TSource, TSource)>
{
readonly IUniTaskAsyncEnumerable<TSource> source;
public Pairwise(IUniTaskAsyncEnumerable<TSource> source)
{
this.source = source;
}
public IUniTaskAsyncEnumerator<(TSource, TSource)> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _Pairwise(source, cancellationToken);
}
sealed class _Pairwise : MoveNextSource, IUniTaskAsyncEnumerator<(TSource, TSource)>
{
static readonly Action<object> MoveNextCoreDelegate = MoveNextCore;
readonly IUniTaskAsyncEnumerable<TSource> source;
CancellationToken cancellationToken;
IUniTaskAsyncEnumerator<TSource> enumerator;
UniTask<bool>.Awaiter awaiter;
TSource prev;
bool isFirst;
public _Pairwise(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
this.source = source;
this.cancellationToken = cancellationToken;
TaskTracker.TrackActiveTask(this, 3);
}
public (TSource, TSource) Current { get; private set; }
public UniTask<bool> MoveNextAsync()
{
cancellationToken.ThrowIfCancellationRequested();
if (enumerator == null)
{
isFirst = true;
enumerator = source.GetAsyncEnumerator(cancellationToken);
}
completionSource.Reset();
SourceMoveNext();
return new UniTask<bool>(this, completionSource.Version);
}
void SourceMoveNext()
{
try
{
awaiter = enumerator.MoveNextAsync().GetAwaiter();
if (awaiter.IsCompleted)
{
MoveNextCore(this);
}
else
{
awaiter.SourceOnCompleted(MoveNextCoreDelegate, this);
}
}
catch (Exception ex)
{
completionSource.TrySetException(ex);
}
}
static void MoveNextCore(object state)
{
var self = (_Pairwise)state;
if (self.TryGetResult(self.awaiter, out var result))
{
if (result)
{
if (self.isFirst)
{
self.isFirst = false;
self.prev = self.enumerator.Current;
self.SourceMoveNext(); // run again. okay to use recursive(only one more).
}
else
{
var p = self.prev;
self.prev = self.enumerator.Current;
self.Current = (p, self.prev);
self.completionSource.TrySetResult(true);
}
}
else
{
self.completionSource.TrySetResult(false);
}
}
}
public UniTask DisposeAsync()
{
TaskTracker.RemoveTracking(this);
if (enumerator != null)
{
return enumerator.DisposeAsync();
}
return default;
}
}
}
} | 412 | 0.930002 | 1 | 0.930002 | game-dev | MEDIA | 0.275259 | game-dev | 0.983196 | 1 | 0.983196 |
hyperledger-labs/splice | 9,515 | canton/community/common/src/test/scala/com/digitalasset/canton/util/TwoPhasePriorityAccumulatorTest.scala | // Copyright (c) 2025 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.digitalasset.canton.util
import com.digitalasset.canton.BaseTest
import com.digitalasset.canton.util.TwoPhasePriorityAccumulator.ItemHandle
import com.digitalasset.canton.util.TwoPhasePriorityAccumulatorTest.Item
import org.scalatest.wordspec.AnyWordSpec
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import scala.annotation.tailrec
import scala.collection.concurrent.TrieMap
class TwoPhasePriorityAccumulatorTest extends AnyWordSpec with BaseTest {
private def priority[A](itemWithPriority: (A, Int)): Int = itemWithPriority._2
s"${classOf[TwoPhasePriorityAccumulator[?, ?]].getSimpleName}" should {
"drain all items in ascending priority order" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
accumulator.isAccumulating shouldBe true
val items = Seq("first" -> 1, "second" -> 2, "third" -> 0)
items.foreach { case (item, priority) =>
accumulator.accumulate(item, priority).value
}
accumulator.isAccumulating shouldBe true
accumulator.getPhase shouldBe None
accumulator.stopAccumulating(()) shouldBe None
accumulator.isAccumulating shouldBe false
accumulator.getPhase shouldBe Some(())
accumulator.drain().toSeq shouldBe items.sortBy(priority)
}
"be empty by default" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
accumulator.stopAndDrain(()).toSeq shouldBe Seq.empty
}
"allow the same item to be added multiple times" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
val items = Seq("first" -> 1, "second" -> 2, "first" -> 3, "first" -> 1, "first" -> 0)
items.foreach((accumulator.accumulate _).tupled(_).value)
accumulator.stopAccumulating(())
accumulator.drain().toSeq shouldBe items.sortBy(priority)
}
"accumulation stops upon draining" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Int](None)
val items = Seq("first" -> 1, "second" -> 2)
items.foreach((accumulator.accumulate _).tupled(_).value)
val label = 10
accumulator.stopAccumulating(label)
accumulator.accumulate("third", 3) shouldBe Left(label)
val iter = accumulator.drain()
accumulator.accumulate("forth", 4) shouldBe Left(label)
iter.toSeq shouldBe items.sortBy(priority)
}
"support removal via the handle" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
val items = Seq("first", "second", "third", "forth", "first", "first")
val handles = items.zipWithIndex.map((accumulator.accumulate _).tupled(_).value)
handles.zipWithIndex.foreach { case (handle, index) =>
if (index % 2 == 0) {
handle.remove() shouldBe true
}
}
accumulator.stopAccumulating(())
accumulator.drain().toSeq shouldBe items.zipWithIndex.filterNot(_._2 % 2 == 0)
}
"removal succeeds only once" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
val items = Seq("first", "second", "third", "forth")
val handles = items.zipWithIndex.map((accumulator.accumulate _).tupled(_).value)
handles(0).remove() shouldBe true
handles(0).remove() shouldBe false
accumulator.stopAccumulating(())
val iter = accumulator.drain()
iter.hasNext shouldBe true
iter.next() shouldBe (items(1) -> 1)
handles(1).remove() shouldBe false
val removals34 = Seq(handles(2), handles(3)).map(_.remove())
val drained34 = iter.toSeq
drained34.size + removals34.count(identity) shouldBe 2
}
"can be stopped only once" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Int](None)
val label = 5
accumulator.stopAccumulating(label) shouldBe None
accumulator.getPhase shouldBe Some(label)
accumulator.accumulate("first", 1) shouldBe Left(label)
accumulator.stopAccumulating(label + 1) shouldBe Some(label)
accumulator.getPhase shouldBe Some(label)
accumulator.accumulate("second", 2) shouldBe Left(label)
accumulator.stopAccumulating(label + 2) shouldBe Some(label)
accumulator.getPhase shouldBe Some(label)
}
"parallel drainings are disjoint and ascending in priority" in {
val accumulator = new TwoPhasePriorityAccumulator[String, Unit](None)
val items = Seq(
"first",
"second",
"third",
"forth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
)
items.zipWithIndex.foreach((accumulator.accumulate _).tupled(_).value)
accumulator.stopAccumulating(())
val iter1 = accumulator.drain()
val iter2 = accumulator.drain()
val iter3 = accumulator.drain()
val iters = Seq(iter1, iter2, iter3)
val drainedB = Seq.newBuilder[(Int, (String, TwoPhasePriorityAccumulator.Priority))]
@tailrec def roundRobin(index: Int, lastDrainedIndex: Int): Unit = {
val iter = iters(index)
if (iter.hasNext) {
drainedB += index -> iter.next()
roundRobin((index + 1) % iters.size, index)
} else if (index == lastDrainedIndex)
// Stop if we've gone through all iterators and they are all empty
()
else roundRobin((index + 1) % iters.size, lastDrainedIndex)
}
roundRobin(0, 0)
val drained = drainedB.result()
drained
.map { case (_, itemWithPriority) => itemWithPriority }
.sortBy { case (_, priority) => priority } shouldBe items.zipWithIndex
forAll(drained.groupBy { case (index, _) => index }) { case (index, drainedI) =>
val priorities = drainedI.map { case (_, itemWithPriority) => priority(itemWithPriority) }
priorities.sorted shouldBe priorities
}
}
"clean up obsolete items" in {
val accumulator = new TwoPhasePriorityAccumulator[Item, Unit](Some(_.isObsolete))
val items = Seq("first", "second", "third", "forth", "fifth", "sixth").map(Item.apply)
val handles = items.map(accumulator.accumulate(_, 0).value)
val obsoleteIndices = Seq(1, 3, 5)
obsoleteIndices.foreach { index =>
items(index).markObsolte()
}
accumulator.removeObsoleteTasks()
val notRemoved = handles.map(_.remove()).zipWithIndex.collect { case (false, index) => index }
notRemoved shouldBe obsoleteIndices
accumulator.stopAccumulating(())
val drained = accumulator.drain()
drained.toSeq shouldBe Seq.empty
}
"behave correctly if races occur" in {
// We simulate races by hijacking the obsolete item clean-up flag.
// This makes this unit test an ugly white-box test
val obsoleteRef = new AtomicReference[Item => Boolean](_ => false)
val afterRegistrationRef = new AtomicReference[() => Unit](() => ())
val accumulator =
new TwoPhasePriorityAccumulator[Item, Unit](Some(item => obsoleteRef.get()(item))) {
override protected def afterRegistration(): Unit = afterRegistrationRef.get()()
}
val items = Seq("first", "second", "third", "forth", "fifth", "sixth").map(Item.apply)
val priority = 0
val handles = items.take(3).map(accumulator.accumulate(_, priority).value)
val drainedRef =
new AtomicReference[Seq[(Item, TwoPhasePriorityAccumulator.Priority)]](Seq.empty)
val accumulatedRef = TrieMap.empty[Item, Either[Unit, ItemHandle]]
afterRegistrationRef.set { () =>
// This runs while we're accumulating items(3)
afterRegistrationRef.set { () =>
// This runs while we're accumulating items(3,4)
obsoleteRef.set { item =>
// This runs while we're accumulating items(3,4,5)
if (item == items(2)) {
// Use item(2) as a flag to ensure this executes only once
handles(2).remove()
afterRegistrationRef.set(() => ())
obsoleteRef.set(_ => false)
// Completely drain the accumulator
// This will run before the accumulator is inserted,
// and so we expect the result of the accumulation to be a left
drainedRef.set(accumulator.stopAndDrain(()).toSeq)
}
false
}
val item = items(5)
val handle = accumulator.accumulate(item, priority)
accumulatedRef.put(item, handle)
}
val item = items(4)
val handle = accumulator.accumulate(item, priority)
accumulatedRef.put(item, handle)
}
accumulator.accumulate(items(3), priority).value
drainedRef.get().toSet shouldBe
Seq(items(0), items(1), items(3), items(4)).map(_ -> priority).toSet
accumulatedRef.keySet shouldBe Set(items(4), items(5))
// items(4) gets drained and therefore should be a handle
accumulatedRef(items(4)).value
// items(5) does not get drained and must therefore be a Left
accumulatedRef(items(5)) shouldBe Left(())
}
}
}
object TwoPhasePriorityAccumulatorTest {
private final case class Item(name: String) {
val obsoleteFlag: AtomicBoolean = new AtomicBoolean()
def isObsolete: Boolean = obsoleteFlag.get()
def markObsolte(): Unit = obsoleteFlag.set(true)
}
}
| 412 | 0.938857 | 1 | 0.938857 | game-dev | MEDIA | 0.514378 | game-dev | 0.987986 | 1 | 0.987986 |
Sigma-Skidder-Team/SigmaRemap | 1,252 | src/main/java/mapped/Class256.java | package mapped;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.Minecraft;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
public class Class256 extends LayerRenderer<PandaEntity, Class2867<PandaEntity>> {
private static String[] field915;
public Class256(Class5714<PandaEntity, Class2867<PandaEntity>> var1) {
super(var1);
}
public void render(MatrixStack var1, IRenderTypeBuffer var2, int var3, PandaEntity var4, float var5, float var6, float var7, float var8, float var9, float var10) {
ItemStack var13 = var4.getItemStackFromSlot(EquipmentSlotType.MAINHAND);
if (var4.method5189() && !var4.method5214()) {
float var14 = -0.6F;
float var15 = 1.4F;
if (var4.method5193()) {
var14 -= 0.2F * MathHelper.sin(var8 * 0.6F) + 0.2F;
var15 -= 0.09F * MathHelper.sin(var8 * 0.6F);
}
var1.push();
var1.translate(0.1F, (double)var15, (double)var14);
Minecraft.getInstance().getFirstPersonRenderer().renderItemSide(var4, var13, ItemCameraTransformsTransformType.GROUND, false, var1, var2, var3);
var1.pop();
}
}
}
| 412 | 0.750382 | 1 | 0.750382 | game-dev | MEDIA | 0.816896 | game-dev,graphics-rendering | 0.734452 | 1 | 0.734452 |
Sigma-Skidder-Team/SigmaRemap | 2,126 | src/main/java/mapped/Class4874.java | package mapped;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import net.minecraft.entity.player.ServerPlayerEntity;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
public abstract class Class4874<T extends Class4457> implements Class4907<T> {
private final Map<Class8019, Set<Class9282<T>>> field22708 = Maps.newIdentityHashMap();
@Override
public final void method15049(Class8019 var1, Class9282<T> var2) {
this.field22708.computeIfAbsent(var1, var0 -> Sets.newHashSet()).add(var2);
}
@Override
public final void method15050(Class8019 var1, Class9282<T> var2) {
Set var5 = this.field22708.get(var1);
if (var5 != null) {
var5.remove(var2);
if (var5.isEmpty()) {
this.field22708.remove(var1);
}
}
}
@Override
public final void method15051(Class8019 var1) {
this.field22708.remove(var1);
}
public abstract T method15047(JsonObject var1, Class9587 var2, Class9366 var3);
public final T method15054(JsonObject var1, Class9366 var2) {
Class9587 var5 = Class9587.method37223(var1, "player", var2);
return this.method15047(var1, var5, var2);
}
public void method15053(ServerPlayerEntity var1, Predicate<T> var2) {
Class8019 var5 = var1.method2823();
Set<Class9282<T>> var6 = this.field22708.get(var5);
if (var6 != null && !var6.isEmpty()) {
LootContext var7 = Class6671.method20332(var1, var1);
List<Class9282<T>> var8 = null;
for (Class9282<T> var10 : var6) {
T var11 = var10.method35005();
if (var11.method14094().method37227(var7) && var2.test(var11)) {
if (var8 == null) {
var8 = Lists.newArrayList();
}
var8.add(var10);
}
}
if (var8 != null) {
for (Class9282 var13 : var8) {
var13.method35006(var5);
}
}
}
}
}
| 412 | 0.710449 | 1 | 0.710449 | game-dev | MEDIA | 0.666793 | game-dev | 0.82006 | 1 | 0.82006 |
linuxdeepin/dde-file-manager | 1,152 | src/plugins/common/dfmplugin-menu/menuscene/newcreatemenuscene.h | // SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef NEWCREATEMENUSCENE_H
#define NEWCREATEMENUSCENE_H
#include "dfmplugin_menu_global.h"
#include <dfm-base/interfaces/abstractmenuscene.h>
#include <dfm-base/interfaces/abstractscenecreator.h>
namespace dfmplugin_menu {
class NewCreateMenuCreator : public DFMBASE_NAMESPACE::AbstractSceneCreator
{
public:
static QString name()
{
return "NewCreateMenu";
}
DFMBASE_NAMESPACE::AbstractMenuScene *create() override;
};
class NewCreateMenuScenePrivate;
class NewCreateMenuScene : public DFMBASE_NAMESPACE::AbstractMenuScene
{
Q_OBJECT
public:
explicit NewCreateMenuScene(QObject *parent = nullptr);
QString name() const override;
bool initialize(const QVariantHash ¶ms) override;
AbstractMenuScene *scene(QAction *action) const override;
bool create(QMenu *parent) override;
void updateState(QMenu *parent) override;
bool triggered(QAction *action) override;
private:
NewCreateMenuScenePrivate *const d = nullptr;
};
}
#endif // NEWCREATEMENUSCENE_H
| 412 | 0.909578 | 1 | 0.909578 | game-dev | MEDIA | 0.608222 | game-dev | 0.615592 | 1 | 0.615592 |
erayzesen/godot-quarkphysics | 3,470 | src/qareabody_node.cpp | #include "qareabody_node.h"
#include "qworld_node.h"
void QAreaBodyNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_gravity_free_enabled"), &QAreaBodyNode::get_gravity_free_enabled );
ClassDB::bind_method(D_METHOD("get_linear_force_to_apply"), &QAreaBodyNode::get_linear_force_to_apply );
ClassDB::bind_method(D_METHOD("get_bodies"), &QAreaBodyNode::get_bodies );
ClassDB::bind_method(D_METHOD("has_body","body_node"), &QAreaBodyNode::has_body );
ClassDB::bind_method(D_METHOD("set_gravity_free_enabled","value"), &QAreaBodyNode::set_gravity_free_enabled );
ClassDB::bind_method(D_METHOD("set_linear_force_to_apply","value"), &QAreaBodyNode::set_linear_force_to_apply );
ADD_PROPERTY( PropertyInfo(Variant::BOOL,"gravity_free"), "set_gravity_free_enabled","get_gravity_free_enabled" );
ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"linear_force_to_apply"), "set_linear_force_to_apply","get_linear_force_to_apply" );
ADD_SIGNAL(MethodInfo("collision_enter",PropertyInfo(Variant::OBJECT,"area_body_node"),PropertyInfo(Variant::OBJECT,"collided_body_node") ) );
ADD_SIGNAL(MethodInfo("collision_exit",PropertyInfo(Variant::OBJECT,"area_body_node"),PropertyInfo(Variant::OBJECT,"collided_body_node") ) );
GDVIRTUAL_BIND(_compute_linear_force, "body_node");
}
QVector QAreaBodyNode::compute_linear_force_call_back(QBody *body)
{
Vector2 force=linearForceToApply;
GDVIRTUAL_CALL(_compute_linear_force,worldNode->get_body_node_with_object(body) ,force);
return QVector(force.x,force.y) ;
}
void QAreaBodyNode::collision_enter_call_back(QAreaBody *areaBody, QBody *collidingBody)
{
QBodyNode *ab_node=worldNode->get_body_node_with_object(areaBody);
QBodyNode *cb_node=worldNode->get_body_node_with_object(collidingBody);
emit_signal("collision_enter",ab_node,cb_node);
}
void QAreaBodyNode::collision_exit_call_back(QAreaBody *areaBody, QBody *collidingBody) {
QBodyNode *ab_node=worldNode->get_body_node_with_object(areaBody);
QBodyNode *cb_node=worldNode->get_body_node_with_object(collidingBody);
emit_signal("collision_exit",ab_node,cb_node);
}
Vector2 QAreaBodyNode::_compute_linear_force(QBodyNode *bodyNode)
{
return linearForceToApply;
}
Array QAreaBodyNode::get_bodies()
{
Array res;
QAreaBody *areaObject=static_cast<QAreaBody*>(bodyObject);
vector<QBody*> bodyList=areaObject->GetBodies();
for(int i=0;i<bodyList.size();++i){
res.push_back( worldNode->get_body_node_with_object(bodyList[i]) );
}
return res;
}
bool QAreaBodyNode::has_body(QBodyNode *bodyNode)
{
QAreaBody *areaObject=static_cast<QAreaBody*>(bodyObject);
return areaObject->HasBody( bodyNode->bodyObject );
}
void QAreaBodyNode::set_gravity_free_enabled(bool value)
{
enableGravityFree=value;
if (Engine::get_singleton()->is_editor_hint()==false && bodyObject!=nullptr ){
QAreaBody *areaObject=static_cast<QAreaBody*>(bodyObject);
if(areaObject!=nullptr){
areaObject->SetGravityFreeEnabled(true);
}
}
}
void QAreaBodyNode::set_linear_force_to_apply(Vector2 value)
{
linearForceToApply=value;
if (Engine::get_singleton()->is_editor_hint()==false && bodyObject!=nullptr ){
QAreaBody *areaObject=static_cast<QAreaBody*>(bodyObject);
if(areaObject!=nullptr){
areaObject->SetLinearForceToApply(QVector(linearForceToApply.x,linearForceToApply.y) );
}
}
}
| 412 | 0.777836 | 1 | 0.777836 | game-dev | MEDIA | 0.793847 | game-dev | 0.696482 | 1 | 0.696482 |
lynx-family/lynx | 3,859 | core/animation/basic_animation/basic_animation.h | // Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
#ifndef CORE_ANIMATION_BASIC_ANIMATION_BASIC_ANIMATION_H_
#define CORE_ANIMATION_BASIC_ANIMATION_BASIC_ANIMATION_H_
#include <memory>
#include <string>
#include <utility>
#include "base/include/fml/time/time_delta.h"
#include "core/animation/basic_animation/animation_effect.h"
#include "core/animation/basic_animation/animation_frame_callback.h"
#include "core/animation/basic_animation/animation_timeline.h"
#include "core/animation/basic_animation/basic_keyframe_effect.h"
namespace lynx {
namespace animation {
namespace basic {
class AnimationFrameCallbackProvider;
class AnimationEventListener;
class Animation : public AnimationFrameCallback {
public:
enum class State { kIdle = 0, kPlay, kPause, kStop };
enum PlayState { PAUSED, RUNNING };
enum EventType { Start, End, Cancel, Iteration };
const std::string& animation_name() const { return data_.animation_name(); }
fml::TimeDelta current_time() const { return data_.current_time(); }
double playback_rate() const { return data_.playback_rate(); }
PlayState play_state() const { return data_.play_state(); }
void set_play_state(PlayState play_state) {
data_.set_play_state(play_state);
}
public:
class Data {
public:
Data() = default;
Data(const std::string& animation_name, const fml::TimeDelta& start_time,
const fml::TimeDelta& current_time, PlayState play_state)
: animation_name_(animation_name),
current_time_(current_time),
play_state_(play_state) {}
const std::string& animation_name() const { return animation_name_; }
fml::TimeDelta current_time() const { return current_time_; }
double playback_rate() const { return playback_rate_; }
PlayState play_state() const { return play_state_; }
void set_play_state(PlayState play_state) { play_state_ = play_state; }
private:
std::string animation_name_;
fml::TimeDelta current_time_;
double playback_rate_ = 1.0;
PlayState play_state_;
};
public:
Animation(std::unique_ptr<KeyframeEffect> effect,
std::unique_ptr<AnimationTimeLine> timeline)
: effect_(std::move(effect)), timeline_(std::move(timeline)) {
effect_->BindHostAnimation(this);
};
explicit Animation(std::unique_ptr<KeyframeEffect> effect)
: effect_(std::move(effect)) {
effect_->BindHostAnimation(this);
};
void AddEventListener(
const std::shared_ptr<AnimationEventListener>& listener) {
listener_ = std::weak_ptr<AnimationEventListener>(listener);
}
void RegisterAnimationFrameCallbackProvider(
const std::weak_ptr<AnimationFrameCallbackProvider>& provider) {
animation_frame_callback_provider_ = provider;
}
public:
void Play();
void Pause();
void Stop();
void Destroy(bool need_clear_effect = true);
void DoAnimationFrame(const fml::TimePoint& frame_time) override;
void Tick(const fml::TimePoint& time);
State GetState() { return state_; }
const AnimationEffect& GetEffect() { return *effect_; }
static fml::TimePoint& GetAnimationDummyStartTime();
void RequestNextFrame();
bool HasFinishAll(const fml::TimePoint& time);
void SendAnimationEvent(EventType type);
protected:
Data data_;
fml::TimePoint start_time_{fml::TimePoint::Min()};
private:
State state_{State::kIdle};
std::unique_ptr<AnimationEffect> effect_;
std::unique_ptr<AnimationTimeLine> timeline_;
std::weak_ptr<AnimationEventListener> listener_;
std::weak_ptr<AnimationFrameCallbackProvider>
animation_frame_callback_provider_;
};
} // namespace basic
} // namespace animation
} // namespace lynx
#endif // CORE_ANIMATION_BASIC_ANIMATION_BASIC_ANIMATION_H_
| 412 | 0.943207 | 1 | 0.943207 | game-dev | MEDIA | 0.828823 | game-dev | 0.786975 | 1 | 0.786975 |
Tschipp/CarryOn | 7,063 | Common/src/main/java/tschipp/carryon/common/carry/CarryOnData.java | /*
* GNU Lesser General Public License v3
* Copyright (C) 2024 Tschipp
* mrtschipp@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package tschipp.carryon.common.carry;
import com.mojang.serialization.DataResult;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.AreaEffectCloud;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import tschipp.carryon.Constants;
import tschipp.carryon.common.scripting.CarryOnScript;
import javax.annotation.Nullable;
import java.util.Optional;
public class CarryOnData {
private CarryType type;
private CompoundTag nbt;
private boolean keyPressed = false;
private CarryOnScript activeScript;
private int selectedSlot = 0;
public CarryOnData(CompoundTag data)
{
if(data.contains("type"))
this.type = CarryType.valueOf(data.getStringOr("type", "INVALID"));
else
this.type = CarryType.INVALID;
this.nbt = data;
this.keyPressed = data.getBooleanOr("keyPressed", false);
if(data.contains("activeScript"))
{
DataResult<CarryOnScript> res = CarryOnScript.CODEC.parse(NbtOps.INSTANCE, data.get("activeScript"));
this.activeScript = res.getOrThrow((s) -> {throw new RuntimeException("Failed to decode activeScript during CarryOnData serialization: " + s);});
}
this.selectedSlot = data.getIntOr("selected", 0);
}
public CompoundTag getNbt()
{
nbt.putString("type", type.toString());
nbt.putBoolean("keyPressed", keyPressed);
if(activeScript != null)
{
DataResult<Tag> res = CarryOnScript.CODEC.encodeStart(NbtOps.INSTANCE, activeScript);
Tag tag = res.getOrThrow((s) -> {throw new RuntimeException("Failed to encode activeScript during CarryOnData serialization: " + s);});
nbt.put("activeScript", tag);
}
nbt.putInt("selected", this.selectedSlot);
return nbt;
}
public CompoundTag getContentNbt()
{
if(type == CarryType.BLOCK && nbt.contains("block"))
return nbt.getCompoundOrEmpty("block");
else if(type == CarryType.ENTITY && nbt.contains("entity"))
return nbt.getCompoundOrEmpty("entity");
return null;
}
public void setBlock(BlockState state, @Nullable BlockEntity tile, ServerPlayer player, BlockPos pos)
{
this.type = CarryType.BLOCK;
if(state.hasProperty(BlockStateProperties.WATERLOGGED))
state = state.setValue(BlockStateProperties.WATERLOGGED, false);
CompoundTag stateData = NbtUtils.writeBlockState(state);
nbt.put("block", stateData);
if(tile != null)
{
CompoundTag tileData = tile.saveWithId(tile.getLevel().registryAccess());
nbt.put("tile", tileData);
}
}
public BlockState getBlock()
{
if(this.type != CarryType.BLOCK)
throw new IllegalStateException("Called getBlock on data that contained " + this.type);
return NbtUtils.readBlockState(BuiltInRegistries.BLOCK, nbt.getCompoundOrEmpty("block"));
}
@Nullable
public BlockEntity getBlockEntity(BlockPos pos, HolderLookup.Provider lookup)
{
if(this.type != CarryType.BLOCK)
throw new IllegalStateException("Called getBlockEntity on data that contained " + this.type);
if(!nbt.contains("tile"))
return null;
return BlockEntity.loadStatic(pos, this.getBlock(), nbt.getCompoundOrEmpty("tile"), lookup);
}
public void setEntity(Entity entity)
{
this.type = CarryType.ENTITY;
CompoundTag entityData = new CompoundTag();
entity.save(entityData);
nbt.put("entity", entityData);
}
public Entity getEntity(Level level)
{
if(this.type != CarryType.ENTITY)
throw new IllegalStateException("Called getEntity on data that contained " + this.type);
var optionalEntity = EntityType.create(nbt.getCompoundOrEmpty("entity"), level, EntitySpawnReason.BUCKET);
if(optionalEntity.isPresent())
return optionalEntity.get();
Constants.LOG.error("Called EntityType#create even though no entity data was present. Data: " + nbt.toString());
this.clear();
return new AreaEffectCloud(level, 0, 0, 0);
}
public Optional<CarryOnScript> getActiveScript()
{
if(activeScript == null)
return Optional.empty();
return Optional.of(activeScript);
}
public void setActiveScript(CarryOnScript script)
{
this.activeScript = script;
}
public void setCarryingPlayer() {
this.type = CarryType.PLAYER;
}
public boolean isCarrying()
{
return this.type != CarryType.INVALID;
}
public boolean isCarrying(CarryType type)
{
return this.type == type;
}
public boolean isKeyPressed() {return this.keyPressed;}
public void setKeyPressed(boolean val) {
this.keyPressed = val;
this.nbt.putBoolean("keyPressed", val);
}
public void setSelected(int selectedSlot) {
this.selectedSlot = selectedSlot;
}
public int getSelected() {
return this.selectedSlot;
}
public void clear()
{
this.type = CarryType.INVALID;
this.nbt = new CompoundTag();
this.activeScript = null;
}
public CarryOnData clone() {
return new CarryOnData(nbt.copy());
}
public int getTick()
{
if(!this.nbt.contains("tick"))
return -1;
return this.nbt.getIntOr("tick", -1);
}
public enum CarryType {
BLOCK,
ENTITY,
PLAYER,
INVALID
}
}
| 412 | 0.901395 | 1 | 0.901395 | game-dev | MEDIA | 0.995002 | game-dev | 0.952006 | 1 | 0.952006 |
williewillus/Botania | 27,062 | src/main/java/vazkii/botania/common/entity/EntityManaBurst.java | /**
* This class was created by <Vazkii>. It's distributed as
* part of the Botania Mod. Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*
* File Created @ [Jan 26, 2014, 5:09:12 PM (GMT)]
*/
package vazkii.botania.common.entity;
import com.google.common.base.Optional;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBush;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import vazkii.botania.api.BotaniaAPI;
import vazkii.botania.api.internal.IManaBurst;
import vazkii.botania.api.internal.VanillaPacketDispatcher;
import vazkii.botania.api.mana.IClientManaHandler;
import vazkii.botania.api.mana.ILensEffect;
import vazkii.botania.api.mana.IManaCollector;
import vazkii.botania.api.mana.IManaCollisionGhost;
import vazkii.botania.api.mana.IManaReceiver;
import vazkii.botania.api.mana.IManaSpreader;
import vazkii.botania.api.mana.IManaTrigger;
import vazkii.botania.api.mana.IPingable;
import vazkii.botania.api.mana.IThrottledPacket;
import vazkii.botania.common.Botania;
import vazkii.botania.common.core.handler.ConfigHandler;
import vazkii.botania.common.core.helper.Vector3;
import vazkii.botania.common.item.equipment.bauble.ItemTinyPlanet;
import javax.annotation.Nonnull;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
public class EntityManaBurst extends EntityThrowable implements IManaBurst {
private static final String TAG_TICKS_EXISTED = "ticksExisted";
private static final String TAG_COLOR = "color";
private static final String TAG_MANA = "mana";
private static final String TAG_STARTING_MANA = "startingMana";
private static final String TAG_MIN_MANA_LOSS = "minManaLoss";
private static final String TAG_TICK_MANA_LOSS = "manaLossTick";
private static final String TAG_SPREADER_X = "spreaderX";
private static final String TAG_SPREADER_Y = "spreaderY";
private static final String TAG_SPREADER_Z = "spreaderZ";
private static final String TAG_GRAVITY = "gravity";
private static final String TAG_LENS_STACK = "lensStack";
private static final String TAG_LAST_MOTION_X = "lastMotionX";
private static final String TAG_LAST_MOTION_Y = "lastMotionY";
private static final String TAG_LAST_MOTION_Z = "lastMotionZ";
private static final String TAG_HAS_SHOOTER = "hasShooter";
private static final String TAG_SHOOTER_UUID_MOST = "shooterUUIDMost";
private static final String TAG_SHOOTER_UUID_LEAST = "shooterUUIDLeast";
private static final DataParameter<Integer> COLOR = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.VARINT);
private static final DataParameter<Integer> MANA = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.VARINT);
private static final DataParameter<Integer> START_MANA = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.VARINT);
private static final DataParameter<Integer> MIN_MANA_LOSS = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.VARINT);
private static final DataParameter<Float> MANA_LOSS_PER_TICK = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.FLOAT);
private static final DataParameter<Float> GRAVITY = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.FLOAT);
private static final DataParameter<BlockPos> SOURCE_COORDS = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.BLOCK_POS);
private static final DataParameter<Optional<ItemStack>> SOURCE_LENS = EntityDataManager.createKey(EntityManaBurst.class, DataSerializers.OPTIONAL_ITEM_STACK);
float accumulatedManaLoss = 0;
boolean fake = false;
final Set<BlockPos> alreadyCollidedAt = new HashSet<>();
boolean fullManaLastTick = true;
UUID shooterIdentity = null;
int _ticksExisted = 0;
boolean scanBeam = false;
public final List<PositionProperties> propsList = new ArrayList<>();
public EntityManaBurst(World world) {
super(world);
setSize(0F, 0F);
}
@Override
protected void entityInit() {
super.entityInit();
dataManager.register(COLOR, 0);
dataManager.register(MANA, 0);
dataManager.register(START_MANA, 0);
dataManager.register(MIN_MANA_LOSS, 0);
dataManager.register(MANA_LOSS_PER_TICK, 0F);
dataManager.register(GRAVITY, 0F);
dataManager.register(SOURCE_COORDS, BlockPos.ORIGIN);
dataManager.register(SOURCE_LENS, Optional.absent());
}
public EntityManaBurst(IManaSpreader spreader, boolean fake) {
this(((TileEntity)spreader).getWorld());
TileEntity tile = (TileEntity) spreader;
this.fake = fake;
setBurstSourceCoords(tile.getPos());
setLocationAndAngles(tile.getPos().getX() + 0.5, tile.getPos().getY() + 0.5, tile.getPos().getZ() + 0.5, 0, 0);
rotationYaw = -(spreader.getRotationX() + 90F);
rotationPitch = spreader.getRotationY();
float f = 0.4F;
double mx = MathHelper.sin(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * f / 2D;
double mz = -(MathHelper.cos(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * f) / 2D;
double my = MathHelper.sin((rotationPitch) / 180.0F * (float) Math.PI) * f / 2D;
setMotion(mx, my, mz);
}
public EntityManaBurst(EntityPlayer player) {
this(player.worldObj);
setBurstSourceCoords(new BlockPos(0, -1, 0));
setLocationAndAngles(player.posX, player.posY + player.getEyeHeight(), player.posZ, player.rotationYaw + 180, -player.rotationPitch);
posX -= MathHelper.cos((rotationYaw + 180) / 180.0F * (float) Math.PI) * 0.16F;
posY -= 0.10000000149011612D;
posZ -= MathHelper.sin((rotationYaw + 180) / 180.0F * (float) Math.PI) * 0.16F;
setPosition(posX, posY, posZ);
float f = 0.4F;
double mx = MathHelper.sin(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * f / 2D;
double mz = -(MathHelper.cos(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * f) / 2D;
double my = MathHelper.sin((rotationPitch) / 180.0F * (float) Math.PI) * f / 2D;
setMotion(mx, my, mz);
}
// Copy of EntityThrowable.onUpdate. Relevant edits indicated.
private void superUpdate() {
this.lastTickPosX = this.posX;
this.lastTickPosY = this.posY;
this.lastTickPosZ = this.posZ;
// super.onUpdate(); Botania - inline supersuperclass's onUpdate
{
if (!this.worldObj.isRemote)
{
this.setFlag(6, this.isGlowing());
}
this.onEntityUpdate();
}
if (this.throwableShake > 0)
{
--this.throwableShake;
}
// Botania - remove inGround check and its else branch. Bursts are never inGround.
Vec3d vec3d = new Vec3d(this.posX, this.posY, this.posZ);
Vec3d vec3d1 = new Vec3d(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
RayTraceResult raytraceresult = this.worldObj.rayTraceBlocks(vec3d, vec3d1);
vec3d = new Vec3d(this.posX, this.posY, this.posZ);
vec3d1 = new Vec3d(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if (raytraceresult != null)
{
vec3d1 = new Vec3d(raytraceresult.hitVec.xCoord, raytraceresult.hitVec.yCoord, raytraceresult.hitVec.zCoord);
}
if(!worldObj.isRemote) { // Botania - only do entity colliding on server
Entity entity = null;
List<Entity> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expandXyz(1.0D));
double d0 = 0.0D;
boolean flag = false;
for (int i = 0; i < list.size(); ++i)
{
Entity entity1 = (Entity)list.get(i);
if (entity1.canBeCollidedWith())
{
if (entity1 == this.ignoreEntity)
{
flag = true;
}
else if (this.ticksExisted < 2 && this.ignoreEntity == null)
{
this.ignoreEntity = entity1;
flag = true;
}
else
{
flag = false;
AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expandXyz(0.30000001192092896D);
RayTraceResult raytraceresult1 = axisalignedbb.calculateIntercept(vec3d, vec3d1);
if (raytraceresult1 != null)
{
double d1 = vec3d.squareDistanceTo(raytraceresult1.hitVec);
if (d1 < d0 || d0 == 0.0D)
{
entity = entity1;
d0 = d1;
}
}
}
}
}
if (this.ignoreEntity != null)
{
/*if (flag)
{
this.ignoreTime = 2;
}
else if (this.ignoreTime-- <= 0)
{
this.ignoreEntity = null;
}*/
}
if (entity != null)
{
raytraceresult = new RayTraceResult(entity);
}
} // End wrap - only do entity colliding on server
if (raytraceresult != null)
{
if (raytraceresult.typeOfHit == RayTraceResult.Type.BLOCK && this.worldObj.getBlockState(raytraceresult.getBlockPos()).getBlock() == Blocks.PORTAL)
{
this.setPortal(raytraceresult.getBlockPos());
}
else
{
this.onImpact(raytraceresult);
}
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(MathHelper.atan2(this.motionX, this.motionZ) * (180D / Math.PI));
for (this.rotationPitch = (float)(MathHelper.atan2(this.motionY, (double)f) * (180D / Math.PI)); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float f1 = 0.99F;
float f2 = this.getGravityVelocity();
if (this.isInWater())
{
for (int j = 0; j < 4; ++j)
{
float f3 = 0.25F;
this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX - this.motionX * (double)f3, this.posY - this.motionY * (double)f3, this.posZ - this.motionZ * (double)f3, this.motionX, this.motionY, this.motionZ, new int[0]);
}
f1 = 0.8F;
}
// Botania - don't apply drag
// this.motionX *= (double)f1;
// this.motionY *= (double)f1;
// this.motionZ *= (double)f1;
this.motionY -= (double)f2;
this.setPosition(this.posX, this.posY, this.posZ);
}
@Override
public void onUpdate() {
setTicksExisted(getTicksExisted() + 1);
superUpdate();
if(!fake && !isDead)
ping();
ILensEffect lens = getLensInstance();
if(lens != null)
lens.updateBurst(this, getSourceLens());
int mana = getMana();
if(getTicksExisted() >= getMinManaLoss()) {
accumulatedManaLoss += getManaLossPerTick();
int loss = (int) accumulatedManaLoss;
setMana(mana - loss);
accumulatedManaLoss -= loss;
if(getMana() <= 0)
setDead();
}
particles();
setMotion(motionX, motionY, motionZ);
fullManaLastTick = getMana() == getStartingMana();
if(scanBeam) {
PositionProperties props = new PositionProperties(this);
if(propsList.isEmpty())
propsList.add(props);
else {
PositionProperties lastProps = propsList.get(propsList.size() - 1);
if(!props.coordsEqual(lastProps))
propsList.add(props);
}
}
}
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotationDirect(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean teleport) {
setPosition(x, y, z);
setRotation(yaw, pitch);
}
@Override
public boolean handleWaterMovement() {
return false;
}
private TileEntity collidedTile = null;
private boolean noParticles = false;
public TileEntity getCollidedTile(boolean noParticles) {
this.noParticles = noParticles;
while(!isDead)
onUpdate();
if(fake)
incrementFakeParticleTick();
return collidedTile;
}
@Override
public void writeEntityToNBT(NBTTagCompound par1nbtTagCompound) {
super.writeEntityToNBT(par1nbtTagCompound);
par1nbtTagCompound.setInteger(TAG_TICKS_EXISTED, getTicksExisted());
par1nbtTagCompound.setInteger(TAG_COLOR, getColor());
par1nbtTagCompound.setInteger(TAG_MANA, getMana());
par1nbtTagCompound.setInteger(TAG_STARTING_MANA, getStartingMana());
par1nbtTagCompound.setInteger(TAG_MIN_MANA_LOSS, getMinManaLoss());
par1nbtTagCompound.setFloat(TAG_TICK_MANA_LOSS, getManaLossPerTick());
par1nbtTagCompound.setFloat(TAG_GRAVITY, getGravity());
ItemStack stack = getSourceLens();
NBTTagCompound lensCmp = new NBTTagCompound();
if(stack != null)
stack.writeToNBT(lensCmp);
par1nbtTagCompound.setTag(TAG_LENS_STACK, lensCmp);
BlockPos coords = getBurstSourceBlockPos();
par1nbtTagCompound.setInteger(TAG_SPREADER_X, coords.getX());
par1nbtTagCompound.setInteger(TAG_SPREADER_Y, coords.getY());
par1nbtTagCompound.setInteger(TAG_SPREADER_Z, coords.getZ());
par1nbtTagCompound.setDouble(TAG_LAST_MOTION_X, motionX);
par1nbtTagCompound.setDouble(TAG_LAST_MOTION_Y, motionY);
par1nbtTagCompound.setDouble(TAG_LAST_MOTION_Z, motionZ);
UUID identity = getShooterUUID();
boolean hasShooter = identity != null;
par1nbtTagCompound.setBoolean(TAG_HAS_SHOOTER, hasShooter);
if(hasShooter) {
par1nbtTagCompound.setLong(TAG_SHOOTER_UUID_MOST, identity.getMostSignificantBits());
par1nbtTagCompound.setLong(TAG_SHOOTER_UUID_LEAST, identity.getLeastSignificantBits());
}
}
@Override
public void readEntityFromNBT(NBTTagCompound par1nbtTagCompound) {
super.readEntityFromNBT(par1nbtTagCompound);
setTicksExisted(par1nbtTagCompound.getInteger(TAG_TICKS_EXISTED));
setColor(par1nbtTagCompound.getInteger(TAG_COLOR));
setMana(par1nbtTagCompound.getInteger(TAG_MANA));
setStartingMana(par1nbtTagCompound.getInteger(TAG_STARTING_MANA));
setMinManaLoss(par1nbtTagCompound.getInteger(TAG_MIN_MANA_LOSS));
setManaLossPerTick(par1nbtTagCompound.getFloat(TAG_TICK_MANA_LOSS));
setGravity(par1nbtTagCompound.getFloat(TAG_GRAVITY));
NBTTagCompound lensCmp = par1nbtTagCompound.getCompoundTag(TAG_LENS_STACK);
ItemStack stack = ItemStack.loadItemStackFromNBT(lensCmp);
if(stack != null)
setSourceLens(stack);
else setSourceLens(new ItemStack(Blocks.STONE, 0, 0));
int x = par1nbtTagCompound.getInteger(TAG_SPREADER_X);
int y = par1nbtTagCompound.getInteger(TAG_SPREADER_Y);
int z = par1nbtTagCompound.getInteger(TAG_SPREADER_Z);
setBurstSourceCoords(new BlockPos(x, y, z));
double lastMotionX = par1nbtTagCompound.getDouble(TAG_LAST_MOTION_X);
double lastMotionY = par1nbtTagCompound.getDouble(TAG_LAST_MOTION_Y);
double lastMotionZ = par1nbtTagCompound.getDouble(TAG_LAST_MOTION_Z);
setMotion(lastMotionX, lastMotionY, lastMotionZ);
boolean hasShooter = par1nbtTagCompound.getBoolean(TAG_HAS_SHOOTER);
if(hasShooter) {
long most = par1nbtTagCompound.getLong(TAG_SHOOTER_UUID_MOST);
long least = par1nbtTagCompound.getLong(TAG_SHOOTER_UUID_LEAST);
UUID identity = getShooterUUID();
if(identity == null || most != identity.getMostSignificantBits() || least != identity.getLeastSignificantBits())
shooterIdentity = new UUID(most, least);
}
}
public void particles() {
if(isDead || !worldObj.isRemote)
return;
ILensEffect lens = getLensInstance();
if(lens != null && !lens.doParticles(this, getSourceLens()))
return;
Color color = new Color(getColor());
float r = color.getRed() / 255F;
float g = color.getGreen() / 255F;
float b = color.getBlue() / 255F;
int mana = getMana();
int maxMana = getStartingMana();
float osize = (float) mana / (float) maxMana;
float size = osize;
if(fake) {
if(getMana() == getStartingMana())
size = 2F;
else if(fullManaLastTick)
size = 4F;
if(!noParticles && shouldDoFakeParticles())
Botania.proxy.sparkleFX(posX, posY, posZ, r, g, b, 0.4F * size, 1, true);
} else {
boolean monocle = Botania.proxy.isClientPlayerWearingMonocle();
if(monocle)
Botania.proxy.setWispFXDepthTest(false);
if(ConfigHandler.subtlePowerSystem)
Botania.proxy.wispFX(posX, posY, posZ, r, g, b, 0.1F * size, (float) (Math.random() - 0.5F) * 0.02F, (float) (Math.random() - 0.5F) * 0.02F, (float) (Math.random() - 0.5F) * 0.01F);
else {
float or = r;
float og = g;
float ob = b;
double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b; // Standard relative luminance calculation
double savedPosX = posX;
double savedPosY = posY;
double savedPosZ = posZ;
Vector3 currentPos = Vector3.fromEntity(this);
Vector3 oldPos = new Vector3(prevPosX, prevPosY, prevPosZ);
Vector3 diffVec = oldPos.subtract(currentPos);
Vector3 diffVecNorm = diffVec.normalize();
double distance = 0.095;
do {
if (luminance < 0.1) {
r = or + (float) Math.random() * 0.125F;
g = og + (float) Math.random() * 0.125F;
b = ob + (float) Math.random() * 0.125F;
}
size = osize + ((float) Math.random() - 0.5F) * 0.065F + (float) Math.sin(new Random(entityUniqueID.getMostSignificantBits()).nextInt(9001)) * 0.4F;
Botania.proxy.wispFX(posX, posY, posZ, r, g, b, 0.2F * size, (float) -motionX * 0.01F, (float) -motionY * 0.01F, (float) -motionZ * 0.01F);
posX += diffVecNorm.x * distance;
posY += diffVecNorm.y * distance;
posZ += diffVecNorm.z * distance;
currentPos = Vector3.fromEntity(this);
diffVec = oldPos.subtract(currentPos);
if(getEntityData().hasKey(ItemTinyPlanet.TAG_ORBIT))
break;
} while(Math.abs(diffVec.mag()) > distance);
Botania.proxy.wispFX(posX, posY, posZ, or, og, ob, 0.1F * size, (float) (Math.random() - 0.5F) * 0.06F, (float) (Math.random() - 0.5F) * 0.06F, (float) (Math.random() - 0.5F) * 0.06F);
posX = savedPosX;
posY = savedPosY;
posZ = savedPosZ;
}
if(monocle)
Botania.proxy.setWispFXDepthTest(true);
}
}
@Override
protected void onImpact(@Nonnull RayTraceResult rtr) {
boolean collided = false;
boolean dead = false;
if(rtr.entityHit == null) {
TileEntity tile = worldObj.getTileEntity(rtr.getBlockPos());
IBlockState state = worldObj.getBlockState(rtr.getBlockPos());
Block block = state.getBlock();
if(block instanceof IManaCollisionGhost && ((IManaCollisionGhost) block).isGhost(state, worldObj, rtr.getBlockPos()) && !(block instanceof IManaTrigger) || block instanceof BlockBush || block instanceof BlockLeaves)
return;
if(BotaniaAPI.internalHandler.isBuildcraftPipe(tile))
return;
BlockPos coords = getBurstSourceBlockPos();
if(tile != null && !tile.getPos().equals(coords))
collidedTile = tile;
if(tile == null || !tile.getPos().equals(coords)) {
if(!fake && !noParticles && (!worldObj.isRemote || tile instanceof IClientManaHandler) && tile != null && tile instanceof IManaReceiver && ((IManaReceiver) tile).canRecieveManaFromBursts())
onRecieverImpact((IManaReceiver) tile, tile.getPos());
if(block instanceof IManaTrigger)
((IManaTrigger) block).onBurstCollision(this, worldObj, rtr.getBlockPos());
boolean ghost = block instanceof IManaCollisionGhost;
dead = !ghost;
if(ghost)
return;
}
collided = true;
}
ILensEffect lens = getLensInstance();
if(lens != null)
dead = lens.collideBurst(this, rtr, collidedTile != null && collidedTile instanceof IManaReceiver && ((IManaReceiver) collidedTile).canRecieveManaFromBursts(), dead, getSourceLens());
if(collided && !hasAlreadyCollidedAt(rtr.getBlockPos()))
alreadyCollidedAt.add(rtr.getBlockPos());
if(dead && !isDead) {
if(!fake) {
Color color = new Color(getColor());
float r = color.getRed() / 255F;
float g = color.getGreen() / 255F;
float b = color.getBlue() / 255F;
int mana = getMana();
int maxMana = getStartingMana();
float size = (float) mana / (float) maxMana;
if(!ConfigHandler.subtlePowerSystem)
for(int i = 0; i < 4; i++)
Botania.proxy.wispFX(posX, posY, posZ, r, g, b, 0.15F * size, (float) (Math.random() - 0.5F) * 0.04F, (float) (Math.random() - 0.5F) * 0.04F, (float) (Math.random() - 0.5F) * 0.04F);
Botania.proxy.sparkleFX((float) posX, (float) posY, (float) posZ, r, g, b, 4, 2);
}
setDead();
}
}
private void onRecieverImpact(IManaReceiver tile, BlockPos pos) {
int mana = getMana();
if(tile instanceof IManaCollector)
mana *= ((IManaCollector) tile).getManaYieldMultiplier(this);
tile.recieveMana(mana);
if(tile instanceof IThrottledPacket)
((IThrottledPacket) tile).markDispatchable();
else VanillaPacketDispatcher.dispatchTEToNearbyPlayers(worldObj, pos);
}
@Override
public void setDead() {
super.setDead();
if(!fake) {
TileEntity tile = getShooter();
if(tile != null && tile instanceof IManaSpreader)
((IManaSpreader) tile).setCanShoot(true);
} else setDeathTicksForFakeParticle();
}
private TileEntity getShooter() {
return worldObj.getTileEntity(getBurstSourceBlockPos());
}
@Override
protected float getGravityVelocity() {
return getGravity();
}
@Override
public boolean isFake() {
return fake;
}
@Override
public void setFake(boolean fake) {
this.fake = fake;
}
public void setScanBeam() {
scanBeam = true;
}
@Override
public int getColor() {
return dataManager.get(COLOR);
}
@Override
public void setColor(int color) {
dataManager.set(COLOR, color);
}
@Override
public int getMana() {
return dataManager.get(MANA);
}
@Override
public void setMana(int mana) {
dataManager.set(MANA, mana);
}
@Override
public int getStartingMana() {
return dataManager.get(START_MANA);
}
@Override
public void setStartingMana(int mana) {
dataManager.set(START_MANA, mana);
}
@Override
public int getMinManaLoss() {
return dataManager.get(MIN_MANA_LOSS);
}
@Override
public void setMinManaLoss(int minManaLoss) {
dataManager.set(MIN_MANA_LOSS, minManaLoss);
}
@Override
public float getManaLossPerTick() {
return dataManager.get(MANA_LOSS_PER_TICK);
}
@Override
public void setManaLossPerTick(float mana) {
dataManager.set(MANA_LOSS_PER_TICK, mana);
}
@Override
public float getGravity() {
return dataManager.get(GRAVITY);
}
@Override
public void setGravity(float gravity) {
dataManager.set(GRAVITY, gravity);
}
@Override
public BlockPos getBurstSourceBlockPos() {
return dataManager.get(SOURCE_COORDS);
}
@Override
public void setBurstSourceCoords(BlockPos pos) {
dataManager.set(SOURCE_COORDS, pos);
}
@Override
public ItemStack getSourceLens() {
Optional<ItemStack> stack = dataManager.get(SOURCE_LENS);
if(!stack.isPresent())
return new ItemStack(Blocks.STONE, 0, 0);
else return stack.get();
}
@Override
public void setSourceLens(ItemStack lens) {
dataManager.set(SOURCE_LENS, lens == null ? Optional.absent() : Optional.of(lens));
}
@Override
public int getTicksExisted() {
return _ticksExisted;
}
public void setTicksExisted(int ticks) {
_ticksExisted = ticks;
}
private ILensEffect getLensInstance() {
ItemStack lens = getSourceLens();
if(lens != null && lens.getItem() instanceof ILensEffect)
return (ILensEffect) lens.getItem();
return null;
}
@Override
public void setMotion(double x, double y, double z) {
motionX = x;
motionY = y;
motionZ = z;
}
@Override
public boolean hasAlreadyCollidedAt(BlockPos pos) {
return alreadyCollidedAt.contains(pos);
}
@Override
public void setCollidedAt(BlockPos pos) {
if(!hasAlreadyCollidedAt(pos))
alreadyCollidedAt.add(pos.toImmutable());
}
@Override
public void setShooterUUID(UUID uuid) {
shooterIdentity = uuid;
}
@Override
public UUID getShooterUUID() {
return shooterIdentity;
}
@Override
public void ping() {
TileEntity tile = getShooter();
if(tile != null && tile instanceof IPingable)
((IPingable) tile).pingback(this, getShooterUUID());
}
protected boolean shouldDoFakeParticles() {
if (ConfigHandler.staticWandBeam)
return true;
TileEntity tile = getShooter();
return tile != null
&& tile instanceof IManaSpreader
&& (getMana() != getStartingMana() && fullManaLastTick
|| Math.abs(((IManaSpreader) tile).getBurstParticleTick() - getTicksExisted()) < 4);
}
private void incrementFakeParticleTick() {
TileEntity tile = getShooter();
if(tile != null && tile instanceof IManaSpreader) {
IManaSpreader spreader = (IManaSpreader) tile;
spreader.setBurstParticleTick(spreader.getBurstParticleTick()+2);
if(spreader.getLastBurstDeathTick() != -1 && spreader.getBurstParticleTick() > spreader.getLastBurstDeathTick())
spreader.setBurstParticleTick(0);
}
}
private void setDeathTicksForFakeParticle() {
BlockPos coords = getBurstSourceBlockPos();
TileEntity tile = worldObj.getTileEntity(coords);
if(tile != null && tile instanceof IManaSpreader)
((IManaSpreader) tile).setLastBurstDeathTick(getTicksExisted());
}
public static class PositionProperties {
public final BlockPos coords;
public final IBlockState state;
public boolean invalid = false;
public PositionProperties(Entity entity) {
int x = MathHelper.floor_double(entity.posX);
int y = MathHelper.floor_double(entity.posY);
int z = MathHelper.floor_double(entity.posZ);
coords = new BlockPos(x, y, z);
state = entity.worldObj.getBlockState(coords);
}
public boolean coordsEqual(PositionProperties props) {
return coords.equals(props.coords);
}
public boolean contentsEqual(World world) {
if(!world.isBlockLoaded(coords)) {
invalid = true;
return false;
}
return world.getBlockState(coords) == this.state;
}
@Override
public int hashCode() {
return Objects.hash(coords, state);
}
@Override
public boolean equals(Object o) {
return o instanceof PositionProperties
&& ((PositionProperties) o).state == state
&& ((PositionProperties) o).coords.equals(coords);
}
}
}
| 412 | 0.892659 | 1 | 0.892659 | game-dev | MEDIA | 0.931555 | game-dev | 0.936387 | 1 | 0.936387 |
DescentDevelopers/Descent3 | 4,276 | editor/group.h | /*
* Descent 3
* Copyright (C) 2024 Parallax Software
*
* 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/>.
--- HISTORICAL COMMENTS FOLLOW ---
* $Logfile: /DescentIII/Main/editor/group.h $
* $Revision: 1.1.1.1 $
* $Date: 2003-08-26 03:57:38 $
* $Author: kevinb $
*
* Header for group.cpp
*
* $Log: not supported by cvs2svn $
*
* 8 9/15/99 1:56p Matt
* Added the option to allow rooms or groups placed on the terrain to
* either align with the terrain or with gravity.
*
* 7 5/08/99 1:39a Matt
* Added a function to delete all objects of a certain type, and support
* for placing and attaching groups to the terrain.
*
* 6 12/01/98 11:22p Matt
* Made copy/paste work with doors.
*
* 5 9/22/97 2:31p Matt
* Made group code copy & paste objects & triggers
*
* 4 9/04/97 4:43p Matt
* Removed include of room.h to reduce compile times
*
* 3 9/02/97 6:42p Matt
* Got paste & group save/load working
*
* 2 8/29/97 5:45p Matt
* Converted group code to work with rooms (unfinished)
*
* 4 6/13/97 11:52a Matt
* Deleted now-unused RotateWorld() function
*
* 3 5/05/97 3:57p Matt
* Added code to rotate the mine (& the objects in it) to join with the
* terrain.
*
* 2 3/12/97 3:25p Matt
* Added funcs for cut, copy, paste, & delete, and to save and load
* groups.
*
* 1 3/11/97 10:48p Matt
*
* $NoKeywords: $
*/
#ifndef _GROUP_H
#define _GROUP_H
// Define room, so we don't have to include room.h
struct room;
struct object;
struct trigger;
// A group. Used for cut, paste, copy, etc.
struct group {
int nrooms; // number of rooms in this group
room *rooms; // pointer to list of rooms
int attachroom; // which room is attached when pasting
int attachface; // which face is attached when pasting
int nobjects; // how many objects
int ndoors; // how many doors
object *objects; // pointer to list of objects
int ntriggers; // how many triggers
trigger *triggers; // pointer to list of triggers
};
// Free a group.
// Parameters: g - the group to be freed
void FreeGroup(group *g);
// Copy the given list of rooms to a group
// Parameters: nrooms - the number of rooms in list
// roomnums - pointer to list of room numbers
// attachroom, attachface - where group attaches when pasted
// Returns: pointer to group
group *CopyGroup(int nrooms, int *roomnums, int attachroom, int attachface);
// Delete the given list of rooms
// Parameters: nrooms - the number of rooms in list
// roomnums - pointer to list of room numbers
void DeleteGroup(int nrooms, int *roomnums);
// Place the given group at the specified room face
// The function merely causes the group to be drawn in the editor, allowing the user to line it up
// before attaching it. The function AttachGroup() must be called to do the actual attachment.
// Parameters: destroomp, destside - where to place the group
// g - the group to place
void PlaceGroup(room *destroomp, int destface, group *g);
// Place the given group at the specified terrain cell
// The function merely causes the group to be drawn in the editor, allowing the user to line it up
// before attaching it. The function AttachGroup() must be called to do the actual attachment.
// Parameters: cellnum - where to place the group
// g - the group to place
void PlaceGroupTerrain(int cellnum, group *g, bool align_to_terrain);
// Attach the already-placed group
void AttachGroup();
// Saves a group to disk in the given filename
void SaveGroup(char *filename, group *g);
// Loads a group from disk
// Returns: pointer to the group loaded
group *LoadGroup(char *filename);
#endif // ifdef _GROUP_H
| 412 | 0.833389 | 1 | 0.833389 | game-dev | MEDIA | 0.194681 | game-dev | 0.527811 | 1 | 0.527811 |
SubnauticaNitrox/Nitrox | 4,502 | NitroxClient/GameLogic/Spawning/WorldEntities/SerializedWorldEntitySpawner.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NitroxModel.DataStructures;
using NitroxModel.DataStructures.GameLogic.Entities;
using NitroxModel.DataStructures.Unity;
using NitroxModel.DataStructures.Util;
using NitroxModel.Helper;
using NitroxModel_Subnautica.DataStructures;
using UnityEngine;
using UWE;
namespace NitroxClient.GameLogic.Spawning.WorldEntities;
public class SerializedWorldEntitySpawner : IWorldEntitySpawner, IWorldEntitySyncSpawner
{
/// <summary>
/// Contains the only types we allow the server to instantiate on clients (for security concerns)
/// </summary>
private readonly HashSet<Type> typesWhitelist = new()
{
typeof(Light), typeof(DisableBeforeExplosion), typeof(BoxCollider), typeof(SphereCollider)
};
public SerializedWorldEntitySpawner()
{
// Preloading a useful asset
if (!NitroxEnvironment.IsTesting && !ProtobufSerializer.emptyGameObjectPrefab)
{
ProtobufSerializer.emptyGameObjectPrefab = Resources.Load<GameObject>("SerializerEmptyGameObject");
}
}
public IEnumerator SpawnAsync(WorldEntity entity, Optional<GameObject> parent, EntityCell cellRoot, TaskResult<Optional<GameObject>> result)
{
SpawnSync(entity, parent, cellRoot, result);
yield break;
}
public bool SpawnsOwnChildren() => false;
public bool SpawnSync(WorldEntity entity, Optional<GameObject> parent, EntityCell cellRoot, TaskResult<Optional<GameObject>> result)
{
if (entity is not SerializedWorldEntity serializedWorldEntity)
{
return true;
}
using PooledObject<ProtobufSerializer> proxy = ProtobufSerializerPool.GetProxy();
ProtobufSerializer serializer = proxy.Value;
UniqueIdentifier uniqueIdentifier = serializer.CreateEmptyGameObject("SerializerEmptyGameObject");
GameObject gameObject = uniqueIdentifier.gameObject;
gameObject.SetActive(false);
gameObject.layer = serializedWorldEntity.Layer;
gameObject.tag = "Untagged"; // Same tag for all empty game objects
LargeWorldEntity largeWorldEntity = gameObject.AddComponent<LargeWorldEntity>();
largeWorldEntity.cellLevel = (LargeWorldEntity.CellLevel)serializedWorldEntity.Level;
Transform transform = gameObject.transform;
transform.SetParent(cellRoot.liveRoot.transform);
NitroxVector3 localPosition = serializedWorldEntity.Transform.LocalPosition - serializedWorldEntity.AbsoluteEntityCell.Position;
transform.localPosition = localPosition.ToUnity();
transform.localRotation = serializedWorldEntity.Transform.LocalRotation.ToUnity();
transform.localScale = serializedWorldEntity.Transform.LocalScale.ToUnity();
// Code inspired from ProtobufSerializer.DeserializeIntoGameObject
Dictionary<Type, int> dictionary = ProtobufSerializer.componentCountersPool.Get();
dictionary.Clear();
foreach (SerializedComponent serializedComponent in serializedWorldEntity.Components)
{
string typeName = serializedComponent.TypeName;
Type cachedType = ProtobufSerializer.GetCachedType(typeName);
if (!typesWhitelist.Contains(cachedType))
{
Log.ErrorOnce($"Server asked to instantiate a non-whitelisted type {typeName}.");
return true;
}
using MemoryStream stream = new(serializedComponent.Data);
int id = ProtobufSerializer.IncrementComponentCounter(dictionary, cachedType);
Component orAddComponent = ProtobufSerializer.GetOrAddComponent(gameObject, cachedType, typeName, id, true);
if (orAddComponent)
{
serializer.Deserialize(stream, orAddComponent, cachedType, false);
}
else
{
Log.ErrorOnce($"Deserializing component {typeName} into {gameObject} failed");
}
ProtobufSerializer.SetIsEnabled(orAddComponent, serializedComponent.IsEnabled);
}
foreach (IProtoEventListener listener in gameObject.GetComponents<IProtoEventListener>())
{
listener.OnProtoDeserialize(serializer);
}
dictionary.Clear();
ProtobufSerializer.componentCountersPool.Return(dictionary);
gameObject.SetActive(true);
result.Set(gameObject);
return true;
}
}
| 412 | 0.862702 | 1 | 0.862702 | game-dev | MEDIA | 0.886785 | game-dev | 0.920142 | 1 | 0.920142 |
alanwoolley/CorsixTH-Android | 7,658 | jni/SDL/src/joystick/SDL_steam_virtual_gamepad.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2024 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"
#include "SDL_hints.h"
#include "SDL_timer.h"
#include "SDL_joystick_c.h"
#include "SDL_steam_virtual_gamepad.h"
#ifdef __WIN32__
#include "../core/windows/SDL_windows.h"
#else
#include <sys/types.h>
#include <sys/stat.h>
#endif
#define SDL_HINT_STEAM_VIRTUAL_GAMEPAD_INFO_FILE "SteamVirtualGamepadInfo"
static char *SDL_steam_virtual_gamepad_info_file SDL_GUARDED_BY(SDL_joystick_lock) = NULL;
static Uint64 SDL_steam_virtual_gamepad_info_file_mtime SDL_GUARDED_BY(SDL_joystick_lock) = 0;
static Uint32 SDL_steam_virtual_gamepad_info_check_time SDL_GUARDED_BY(SDL_joystick_lock) = 0;
static SDL_SteamVirtualGamepadInfo **SDL_steam_virtual_gamepad_info SDL_GUARDED_BY(SDL_joystick_lock) = NULL;
static int SDL_steam_virtual_gamepad_info_count SDL_GUARDED_BY(SDL_joystick_lock) = 0;
static Uint64 GetFileModificationTime(const char *file)
{
Uint64 modification_time = 0;
#ifdef __WIN32__
WCHAR *wFile = WIN_UTF8ToStringW(file);
if (wFile) {
HANDLE hFile = CreateFileW(wFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
FILETIME last_write_time;
if (GetFileTime(hFile, NULL, NULL, &last_write_time)) {
modification_time = last_write_time.dwHighDateTime;
modification_time <<= 32;
modification_time |= last_write_time.dwLowDateTime;
}
CloseHandle(hFile);
}
SDL_free(wFile);
}
#else
struct stat sb;
if (stat(file, &sb) == 0) {
modification_time = (Uint64)sb.st_mtime;
}
#endif
return modification_time;
}
static void SDL_FreeSteamVirtualGamepadInfo(void)
{
int i;
SDL_AssertJoysticksLocked();
for (i = 0; i < SDL_steam_virtual_gamepad_info_count; ++i) {
SDL_SteamVirtualGamepadInfo *entry = SDL_steam_virtual_gamepad_info[i];
if (entry) {
SDL_free(entry->name);
SDL_free(entry);
}
}
SDL_free(SDL_steam_virtual_gamepad_info);
SDL_steam_virtual_gamepad_info = NULL;
SDL_steam_virtual_gamepad_info_count = 0;
}
static void AddVirtualGamepadInfo(int slot, SDL_SteamVirtualGamepadInfo *info)
{
SDL_SteamVirtualGamepadInfo *new_info;
SDL_AssertJoysticksLocked();
if (slot < 0) {
return;
}
if (slot >= SDL_steam_virtual_gamepad_info_count) {
SDL_SteamVirtualGamepadInfo **slots = (SDL_SteamVirtualGamepadInfo **)SDL_realloc(SDL_steam_virtual_gamepad_info, (slot + 1)*sizeof(*SDL_steam_virtual_gamepad_info));
if (!slots) {
return;
}
while (SDL_steam_virtual_gamepad_info_count <= slot) {
slots[SDL_steam_virtual_gamepad_info_count++] = NULL;
}
SDL_steam_virtual_gamepad_info = slots;
}
if (SDL_steam_virtual_gamepad_info[slot]) {
/* We already have this slot info */
return;
}
new_info = (SDL_SteamVirtualGamepadInfo *)SDL_malloc(sizeof(*new_info));
if (!new_info) {
return;
}
SDL_copyp(new_info, info);
SDL_steam_virtual_gamepad_info[slot] = new_info;
SDL_zerop(info);
}
void SDL_InitSteamVirtualGamepadInfo(void)
{
const char *file;
SDL_AssertJoysticksLocked();
file = SDL_GetHint(SDL_HINT_STEAM_VIRTUAL_GAMEPAD_INFO_FILE);
if (file && *file) {
SDL_steam_virtual_gamepad_info_file = SDL_strdup(file);
}
SDL_UpdateSteamVirtualGamepadInfo();
}
SDL_bool SDL_SteamVirtualGamepadEnabled(void)
{
SDL_AssertJoysticksLocked();
return (SDL_steam_virtual_gamepad_info != NULL);
}
SDL_bool SDL_UpdateSteamVirtualGamepadInfo(void)
{
const int UPDATE_CHECK_INTERVAL_MS = 3000;
Uint32 now;
Uint64 mtime;
char *data, *end, *next, *line, *value;
size_t size;
int slot, new_slot;
SDL_SteamVirtualGamepadInfo info;
SDL_AssertJoysticksLocked();
if (!SDL_steam_virtual_gamepad_info_file) {
return SDL_FALSE;
}
now = SDL_GetTicks();
if (SDL_steam_virtual_gamepad_info_check_time &&
!SDL_TICKS_PASSED(now, (SDL_steam_virtual_gamepad_info_check_time + UPDATE_CHECK_INTERVAL_MS))) {
return SDL_FALSE;
}
SDL_steam_virtual_gamepad_info_check_time = now;
mtime = GetFileModificationTime(SDL_steam_virtual_gamepad_info_file);
if (mtime == 0 || mtime == SDL_steam_virtual_gamepad_info_file_mtime) {
return SDL_FALSE;
}
data = (char *)SDL_LoadFile(SDL_steam_virtual_gamepad_info_file, &size);
if (!data) {
return SDL_FALSE;
}
SDL_FreeSteamVirtualGamepadInfo();
slot = -1;
SDL_zero(info);
for (next = data, end = data + size; next < end; ) {
while (next < end && (*next == '\0' || *next == '\r' || *next == '\n')) {
++next;
}
line = next;
while (next < end && (*next != '\r' && *next != '\n')) {
++next;
}
*next = '\0';
if (SDL_sscanf(line, "[slot %d]", &new_slot) == 1) {
if (slot >= 0) {
AddVirtualGamepadInfo(slot, &info);
}
slot = new_slot;
} else {
value = SDL_strchr(line, '=');
if (value) {
*value++ = '\0';
if (SDL_strcmp(line, "name") == 0) {
SDL_free(info.name);
info.name = SDL_strdup(value);
} else if (SDL_strcmp(line, "VID") == 0) {
info.vendor_id = (Uint16)SDL_strtoul(value, NULL, 0);
} else if (SDL_strcmp(line, "PID") == 0) {
info.product_id = (Uint16)SDL_strtoul(value, NULL, 0);
} else if (SDL_strcmp(line, "type") == 0) {
info.type = SDL_GetGameControllerTypeFromString(value);
} else if (SDL_strcmp(line, "handle") == 0) {
info.handle = SDL_strtoull(value, NULL, 0);
}
}
}
}
if (slot >= 0) {
AddVirtualGamepadInfo(slot, &info);
}
SDL_free(info.name);
SDL_free(data);
SDL_steam_virtual_gamepad_info_file_mtime = mtime;
return SDL_TRUE;
}
const SDL_SteamVirtualGamepadInfo *SDL_GetSteamVirtualGamepadInfo(int slot)
{
SDL_AssertJoysticksLocked();
if (slot < 0 || slot >= SDL_steam_virtual_gamepad_info_count) {
return NULL;
}
return SDL_steam_virtual_gamepad_info[slot];
}
void SDL_QuitSteamVirtualGamepadInfo(void)
{
SDL_AssertJoysticksLocked();
if (SDL_steam_virtual_gamepad_info_file) {
SDL_FreeSteamVirtualGamepadInfo();
SDL_free(SDL_steam_virtual_gamepad_info_file);
SDL_steam_virtual_gamepad_info_file = NULL;
}
}
| 412 | 0.888817 | 1 | 0.888817 | game-dev | MEDIA | 0.677624 | game-dev | 0.708913 | 1 | 0.708913 |
stgatilov/darkmod_src | 6,022 | game/ai/Tasks/PathSitTask.cpp | /*****************************************************************************
The Dark Mod GPL Source Code
This file is part of the The Dark Mod Source Code, originally based
on the Doom 3 GPL Source Code as published in 2011.
The Dark Mod Source Code is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version. For details, see LICENSE.TXT.
Project: The Dark Mod (http://www.thedarkmod.com/)
******************************************************************************/
#include "precompiled.h"
#pragma hdrstop
#include "../Memory.h"
#include "PathSitTask.h"
#include "PathTurnTask.h"
#include "../Library.h"
#define WARNING_DELAY 10000 // grayman #5164 - ms delay between "unreachable" WARNINGs
namespace ai
{
PathSitTask::PathSitTask() :
PathTask()
{}
PathSitTask::PathSitTask(idPathCorner* path) :
PathTask(path)
{
_path = path;
}
// Get the name of this task
const idStr& PathSitTask::GetName() const
{
static idStr _name(TASK_PATH_SIT);
return _name;
}
void PathSitTask::Init(idAI* owner, Subsystem& subsystem)
{
PathTask::Init(owner, subsystem);
idPathCorner* path = _path.GetEntity();
// grayman #5164 - Am I too far away to sit?
idPathCorner* lastPath = owner->GetMemory().lastPath.GetEntity(); // path_corner preceding path_sit
if ( lastPath )
{
idVec3 aiOrigin = owner->GetPhysics()->GetOrigin();
idVec3 sitLocation = lastPath->GetPhysics()->GetOrigin();
sitLocation.z = aiOrigin.z; // remove z vector
float dist = (sitLocation - aiOrigin).LengthFast();
// if dist is too far, terminate the sit.
float accuracy = 16; // default
if ( dist > idMath::Sqrt(2 * accuracy*accuracy) ) // grayman #5265 extend the required distance
{
if ( gameLocal.time >= owner->m_nextWarningTime )
{
gameLocal.Warning("%s (%s) can't sit: too far from sitting location %s (%s)\n", owner->GetName(), aiOrigin.ToString(), lastPath->GetName(), lastPath->GetPhysics()->GetOrigin().ToString());
owner->m_nextWarningTime = gameLocal.time + WARNING_DELAY;
}
subsystem.FinishTask();
return;
}
}
// Parse animation spawnargs here
float waittime = path->spawnArgs.GetFloat("wait","0");
float waitmax = path->spawnArgs.GetFloat("wait_max", "0");
if (waitmax > 0)
{
waittime += (waitmax - waittime) * gameLocal.random.RandomFloat();
}
if (waittime > 0)
{
_waitEndTime = gameLocal.time + SEC2MS(waittime);
}
else
{
_waitEndTime = -1;
}
// angua: check whether the AI should turn to a specific angle after sitting down
if (path->spawnArgs.FindKey("sit_down_angle") != NULL)
{
owner->AI_SIT_DOWN_ANGLE = path->spawnArgs.GetFloat("sit_down_angle", "0");
}
else
{
owner->AI_SIT_DOWN_ANGLE = owner->GetCurrentYaw();
}
owner->AI_SIT_UP_ANGLE = owner->GetCurrentYaw(); // the anim script uses AI_SIT_UP_ANGLE
owner->AI_SIT_DOWN_ANGLE = idMath::AngleNormalize180(owner->AI_SIT_DOWN_ANGLE); // the anim script uses AI_SIT_DOWN_ANGLE
_sittingState = EStateSitStart;
}
bool PathSitTask::Perform(Subsystem& subsystem)
{
DM_LOG(LC_AI, LT_INFO)LOGSTRING("PathSitTask performing.\r");
idAI* owner = _owner.GetEntity();
// This task may not be performed with an empty owner pointer
assert(owner != NULL);
idStr waitState(owner->WaitState()); // grayman #3670
moveType_t moveType = owner->GetMoveType();
// grayman #4113 - if we find ourself getting up from sitting because we've been
// alerted, we have to kill this task, regardless of which state
// we're in
if ((moveType == MOVETYPE_GET_UP) && (owner->AI_AlertIndex >= ESearching))
{
return true;
}
// grayman #4054 - rewrite to use machine states
switch (_sittingState)
{
case EStateSitStart:
if (moveType == MOVETYPE_SIT)
{
// sitting. check sitting angle next
_sittingState = EStateTurning;
}
else if (moveType != MOVETYPE_SIT_DOWN)
{
// sit down
owner->SitDown();
// we can't move to a separate state to check for
// the waitState to change from "sit_down" because
// SitDown() might have failed. we have to come
// back through here to give it another try.
}
break;
case EStateTurning:
// sitting. check sitting angle
if ( owner->AI_SIT_DOWN_ANGLE == owner->GetCurrentYaw() )
{
// sitting and at sitting angle, so fire the targets
idPathCorner* path = _path.GetEntity(); // grayman #3670
// This task may not be performed with an empty path pointer
assert(path != NULL);
path->ActivateTargets(owner);
if ( _waitEndTime < 0 )
{
// no end time set, so we're free to leave and not come back
return true;
}
_sittingState = EStateWaiting;
}
break;
case EStateWaiting:
// there's an end time, let's see if we're there yet
if ( gameLocal.time >= _waitEndTime )
{
// yes, we're past the end time, so let's get up
owner->GetUp();
_sittingState = EStateGetUp;
}
break;
case EStateGetUp:
// The get up script clears the "get_up" waitState
// when the get up portion of the anim is finished.
if (waitState != "get_up")
{
// Exit when the waitstate is not "get_up" anymore
return true;
}
break;
};
return false;
}
// Save/Restore methods
void PathSitTask::Save(idSaveGame* savefile) const
{
PathTask::Save(savefile);
savefile->WriteInt(_waitEndTime);
savefile->WriteInt(static_cast<int>(_sittingState)); // grayman #4054
}
void PathSitTask::Restore(idRestoreGame* savefile)
{
PathTask::Restore(savefile);
savefile->ReadInt(_waitEndTime);
// grayman #4054
int temp;
savefile->ReadInt(temp);
_sittingState = static_cast<ESitState>(temp);
}
PathSitTaskPtr PathSitTask::CreateInstance()
{
return PathSitTaskPtr(new PathSitTask);
}
// Register this task with the TaskLibrary
TaskLibrary::Registrar pathSitTaskRegistrar(
TASK_PATH_SIT, // Task Name
TaskLibrary::CreateInstanceFunc(&PathSitTask::CreateInstance) // Instance creation callback
);
} // namespace ai
| 412 | 0.97671 | 1 | 0.97671 | game-dev | MEDIA | 0.962166 | game-dev | 0.986881 | 1 | 0.986881 |
OGSR/OGSR-Engine | 2,449 | ogsr_engine/xrGame/ai/monsters/states/monster_state_panic_inline.h | #pragma once
#include "state_data.h"
#include "state_move_to_point.h"
#include "state_custom_action.h"
#include "state_look_unprotected_area.h"
#include "monster_state_panic_run.h"
#include "monster_state_home_point_attack.h"
#define TEMPLATE_SPECIALIZATION template <typename _Object>
#define CStateMonsterPanicAbstract CStateMonsterPanic<_Object>
TEMPLATE_SPECIALIZATION
CStateMonsterPanicAbstract::CStateMonsterPanic(_Object* obj) : inherited(obj)
{
add_state(eStatePanic_Run, xr_new<CStateMonsterPanicRun<_Object>>(obj));
add_state(eStatePanic_FaceUnprotectedArea, xr_new<CStateMonsterLookToUnprotectedArea<_Object>>(obj));
add_state(eStatePanic_MoveToHomePoint, xr_new<CStateMonsterAttackMoveToHomePoint<_Object>>(obj));
}
TEMPLATE_SPECIALIZATION
CStateMonsterPanicAbstract::~CStateMonsterPanic() {}
TEMPLATE_SPECIALIZATION
void CStateMonsterPanicAbstract::initialize() { inherited::initialize(); }
TEMPLATE_SPECIALIZATION
void CStateMonsterPanicAbstract::reselect_state()
{
if (get_state(eStatePanic_MoveToHomePoint)->check_start_conditions())
{
select_state(eStatePanic_MoveToHomePoint);
return;
}
if (prev_substate == eStatePanic_Run)
select_state(eStatePanic_FaceUnprotectedArea);
else
select_state(eStatePanic_Run);
}
TEMPLATE_SPECIALIZATION
void CStateMonsterPanicAbstract::setup_substates()
{
state_ptr state = get_state_current();
if (current_substate == eStatePanic_FaceUnprotectedArea)
{
SStateDataAction data;
data.action = ACT_STAND_IDLE;
data.spec_params = ASP_STAND_SCARED;
data.time_out = 3000;
data.sound_type = MonsterSound::eMonsterSoundPanic;
data.sound_delay = object->db().m_dwAttackSndDelay;
state->fill_data_with(&data, sizeof(SStateDataAction));
return;
}
}
TEMPLATE_SPECIALIZATION
void CStateMonsterPanicAbstract::check_force_state()
{
if ((current_substate == eStatePanic_FaceUnprotectedArea))
{
// если видит врага
if (object->EnemyMan.get_enemy_time_last_seen() == Device.dwTimeGlobal)
{
select_state(eStatePanic_Run);
return;
}
// если получил hit
if (object->HitMemory.get_last_hit_time() + 5000 > Device.dwTimeGlobal)
{
select_state(eStatePanic_Run);
return;
}
}
}
#undef TEMPLATE_SPECIALIZATION
#undef CStateMonsterPanicAbstract
| 412 | 0.94672 | 1 | 0.94672 | game-dev | MEDIA | 0.972079 | game-dev | 0.931364 | 1 | 0.931364 |
CrazyVince/Hacking | 2,218 | Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Editor/TMP_ResourcesLoader.cs | using UnityEditor;
using UnityEngine;
using System.Collections;
namespace TMPro.EditorUtilities
{
//[InitializeOnLoad]
class TMP_ResourcesLoader
{
/// <summary>
/// Function to pre-load the TMP Resources
/// </summary>
public static void LoadTextMeshProResources()
{
//TMP_Settings.LoadDefaultSettings();
//TMP_StyleSheet.LoadDefaultStyleSheet();
}
static TMP_ResourcesLoader()
{
//Debug.Log("Loading TMP Resources...");
// Get current targetted platform
//string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
//TMPro.TMP_Settings.LoadDefaultSettings();
//TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
}
//[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
//static void OnBeforeSceneLoaded()
//{
//Debug.Log("Before scene is loaded.");
// //TMPro.TMP_Settings.LoadDefaultSettings();
// //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
// //ShaderVariantCollection collection = new ShaderVariantCollection();
// //Shader s0 = Shader.Find("TextMeshPro/Mobile/Distance Field");
// //ShaderVariantCollection.ShaderVariant tmp_Variant = new ShaderVariantCollection.ShaderVariant(s0, UnityEngine.Rendering.PassType.Normal, string.Empty);
// //collection.Add(tmp_Variant);
// //collection.WarmUp();
//}
}
//static class TMP_ProjectSettings
//{
// [InitializeOnLoadMethod]
// static void SetProjectDefineSymbols()
// {
// string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
// //Check for and inject TMP_INSTALLED
// if (!currentBuildSettings.Contains("TMP_PRESENT"))
// {
// PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT");
// }
// }
//}
}
| 412 | 0.601373 | 1 | 0.601373 | game-dev | MEDIA | 0.739323 | game-dev | 0.766908 | 1 | 0.766908 |
NcStudios/NcEngine | 6,867 | source/ncengine/physics/jolt/ShapeFactory.cpp | #include "ShapeFactory.h"
#include "Conversion.h"
#include "ncengine/asset/AssetData.h"
#include "ncjolt/ShapeUtility.h"
#include "Jolt/Physics/Collision/Shape/BoxShape.h"
#include "Jolt/Physics/Collision/Shape/CapsuleShape.h"
#include "Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h"
#include "Jolt/Physics/Collision/Shape/ScaledShape.h"
#include "Jolt/Physics/Collision/Shape/SphereShape.h"
#include <ranges>
namespace
{
template<class T, class... Args>
auto MakeRef(Args&&... args) -> JPH::Ref<JPH::Shape>
{
return JPH::Ref<JPH::Shape>{new T(std::forward<Args>(args)...)};
}
} // anonymous namespace
namespace nc::physics
{
auto ShapeFactory::MakeDecoratedShape(const JPH::Shape* shape,
const JPH::Vec3& localPosition,
const JPH::Quat& localRotation) -> JPH::Ref<JPH::Shape>
{
return MakeRef<JPH::RotatedTranslatedShape>(localPosition, localRotation, shape);
}
auto ShapeFactory::MakeDecoratedShape(const JPH::Shape* shape,
const JPH::Vec3& scale) -> JPH::Ref<JPH::Shape>
{
return MakeRef<JPH::ScaledShape>(shape, scale);
}
ShapeFactory::ShapeFactory(Signal<const asset::ConvexHullUpdateEventData&>& onConvexHullUpdate,
Signal<const asset::MeshColliderUpdateEventData&>& onMeshColliderUpdate)
: m_convexHullUpdateConnection{onConvexHullUpdate.Connect(this, &ShapeFactory::OnConvexHullUpdate)},
m_meshColliderUpdateConnection{onMeshColliderUpdate.Connect(this, &ShapeFactory::OnMeshColliderUpdate)}
{
s_instance = this;
}
auto ShapeFactory::MakeShape(const Shape& shape,
const JPH::Vec3& additionalScaling) -> JPH::Ref<JPH::Shape>
{
const auto type = shape.GetType();
const auto localScale = ToJoltVec3(shape.GetLocalScale());
const auto worldScale = localScale * additionalScaling;
switch (type)
{
case ShapeType::Box:
return MakeBox(worldScale * 0.5f);
case ShapeType::Sphere:
return MakeSphere(worldScale.GetX() * 0.5f);
case ShapeType::Capsule:
return MakeCapsule(worldScale.GetY(), worldScale.GetX() * 0.5f);
case ShapeType::ConvexHull:
return MakeConvexHull(shape.GetAssetId(), worldScale);
case ShapeType::Mesh:
return MakeMesh(shape.GetAssetId(), worldScale);
case ShapeType::Compound:
return MakeCompound(shape.GetAssetId(), worldScale);
default:
NC_ASSERT(false, fmt::format("Unhandled ShapeType '{}'", std::to_underlying(type)));
std::unreachable();
};
}
auto ShapeFactory::MakeShape(const Shape& shape,
const JPH::Vec3& position,
const JPH::Quat& rotation,
const JPH::Vec3& scale) -> JPH::Ref<JPH::Shape>
{
auto innerShape = MakeShape(shape, scale);
return ShapeFactory::MakeDecoratedShape(innerShape, position, rotation);
}
auto ShapeFactory::MakeBox(const JPH::Vec3& halfExtents) -> JPH::Ref<JPH::Shape>
{
return MakeRef<JPH::BoxShape>(halfExtents, boxConvexRadius);
}
auto ShapeFactory::MakeSphere(float radius) -> JPH::Ref<JPH::Shape>
{
return MakeRef<JPH::SphereShape>(radius);
}
auto ShapeFactory::MakeCapsule(float halfHeight, float radius) -> JPH::Ref<JPH::Shape>
{
const auto cylinderHalfHeight = std::max(halfHeight - radius, capsuleMinHalfHeight);
return MakeRef<JPH::CapsuleShape>(cylinderHalfHeight, radius);
}
auto ShapeFactory::MakeConvexHull(asset::AssetId id, const JPH::Vec3& scale) -> JPH::Ref<JPH::Shape>
{
return MakeDecoratedShape(GetConvexHull(id), scale);
}
auto ShapeFactory::MakeMesh(asset::AssetId id, const JPH::Vec3& scale) -> JPH::Ref<JPH::Shape>
{
return MakeDecoratedShape(GetMeshCollider(id), scale);
}
auto ShapeFactory::MakeCompound(asset::AssetId id, const JPH::Vec3& scale) -> JPH::Ref<JPH::Shape>
{
return MakeDecoratedShape(GetRuntimeAsset(id, ShapeType::Compound), scale);
}
auto ShapeFactory::GetConvexHull(asset::AssetId id) -> JPH::Shape*
{
NC_ASSERT(m_convexHulls.contains(id), "ConvexHull not loaded");
return m_convexHulls.at(id).GetPtr();
}
auto ShapeFactory::GetMeshCollider(asset::AssetId id) -> JPH::Shape*
{
NC_ASSERT(m_meshColliders.contains(id), "MeshCollider not loaded");
return m_meshColliders.at(id).GetPtr();
}
auto ShapeFactory::GetRuntimeAsset(asset::AssetId id, [[maybe_unused]] ShapeType type) -> JPH::Shape*
{
NC_ASSERT(m_runtimeAssets.contains(id), fmt::format("Runtime asset '{}' is not loaded", id));
auto& ref = m_runtimeAssets.at(id);
NC_ASSERT(
ToShapeType(ref->GetSubType()) == type,
fmt::format(
"Runtime asset type '{}' does not match expected '{}'",
std::to_underlying(ToShapeType(ref->GetSubType())),
std::to_underlying(type)
)
);
return ref.GetPtr();
}
void ShapeFactory::AddRuntimeAsset(JPH::Ref<JPH::Shape> shape, asset::AssetId id)
{
NC_ASSERT(!m_runtimeAssets.contains(id), fmt::format("AssetId '{}' already assigned to a runtime asset", id));
m_runtimeAssets.emplace(id, std::move(shape));
}
void ShapeFactory::RemoveRuntimeAsset(asset::AssetId id)
{
m_runtimeAssets.erase(id);
}
void ShapeFactory::RemoveAllRuntimeAssets()
{
m_runtimeAssets.clear();
}
void ShapeFactory::OnConvexHullUpdate(const asset::ConvexHullUpdateEventData& event)
{
switch (event.updateAction)
{
case asset::UpdateAction::Load:
{
for (const auto [asset, id] : std::views::zip(event.convexHulls, event.ids))
{
m_convexHulls.emplace(id, jolt::DeserializeShape(asset.blob));
}
break;
}
case asset::UpdateAction::Unload:
{
for (const auto id : event.ids)
{
m_convexHulls.erase(id);
}
break;
}
case asset::UpdateAction::UnloadAll:
{
m_convexHulls.clear();
break;
}
}
}
void ShapeFactory::OnMeshColliderUpdate(const asset::MeshColliderUpdateEventData& event)
{
switch (event.updateAction)
{
case asset::UpdateAction::Load:
{
for (const auto [asset, id] : std::views::zip(event.colliders, event.ids))
{
m_meshColliders.emplace(id, jolt::DeserializeShape(asset.blob));
}
break;
}
case asset::UpdateAction::Unload:
{
for (const auto id : event.ids)
{
m_meshColliders.erase(id);
}
break;
}
case asset::UpdateAction::UnloadAll:
{
m_meshColliders.clear();
break;
}
}
}
} // namespace nc::physics
| 412 | 0.93078 | 1 | 0.93078 | game-dev | MEDIA | 0.761262 | game-dev,graphics-rendering | 0.979931 | 1 | 0.979931 |
holycake/mhsj | 43,776 | feature/vi.c | /* Program : /feature/me.c
* Author :Kenny@Eternal.Civilization (3/25/1998)
*port to chinese wizard group : /feature/vi.c by ken@chinesemud.net (99-3-15) */
#include <ansi.h> // 定义 ANSI/VT100 终端机的逸脱码
#define ECHO 0 // 读取输入时要显示字元
#define HIDE 1 // 读取输入时不显示字元
#define REFRESH 1 // 读取输入后要重绘画面
#define LOGFILE "nosave/VI" // 档案异动记录档
void start_edit(string filename); // 呼叫编辑器,开始编辑
private void _append(object pl); // 在游标後面加字
private void _append_line(object pl); // 在游标底下加一新行
private void _backspace(object pl); // 删除游标前的字
protected void _confirm_save(string str, object pl); // 离开编辑器前确认存档
private void _del_char(object pl, int bs); // 删除游标上的字
private void _del_line(object pl); // 删除整行
private int _dispatcher(object pl); // 分派指令到不同函式
private void _down(object pl); // 游标往下移一行
private void _end(object pl); // 将游标移到行尾
private void _esc(object pl); // 从输入模式回到命令模式
private void _file_end(object pl); // 将游标移到档尾
private void _file_head(object pl); // 将游标移到档头
private void _goto_line(object pl); // 跳到特定行去
protected void _goto_line_done(string str, object pl, int rein); // 取得行号
private void _help(object pl); // 辅助画面
private void _home(object pl); // 将游标移到行首
protected void _input(string str, object pl, int fresh); // 读得输入字串
private void _insert(object pl); // 在游标前面插字
private void _insert_line(object pl); // 在游标上方加一新行
private void _insert_exclam_mark(object pl); // 在游标前面插入一个「!」字元
private void _join(object pl); // 将下行文字移到此行後面
private void _keymap(object pl); // 定义新功能键
protected void _keymap_done(string str, object pl); // 取得定义功能键
private void _left(object pl); // 游标往左移一字
// 在状态列显示讯息
private varargs void _message(object pl, string str, string callback, int hide,
mixed arg);
protected void _message_done(string str, object pl); // 结束讯息的显示
private void _next_match(object pl); // 搜寻/替换下个符合字串
private void _page_down(object pl); // 往下卷一页(22 行)
private void _page_up(object pl); // 往上卷一页(22 行)
private void _process(object pl); // 处理输入模式的字串输入
protected void _quit(mixed unused, mixed pl); // 离开编辑器
private void _refresh(object pl); // 更新画面
private void _refresh_cursor(object pl); // 更新游标位置
// 重绘画面
private void _refresh_screen(object pl, int s_row, int e_row, int s_col);
private void _refresh_status(object pl); // 更新状态列
private void _replace(object pl); // 字串替换
protected void _replace_done(string str, object pl); // 取得替换字串
private void _right(object pl, int col, int extra); // 游标往右移一字
private void _search(object pl); // 字串搜寻
protected void _search_done(string str, object pl); // 取得搜寻字串
private void _tab(object pl); // 命令模式下 TAB 键的定位
private void _undef_key(object pl); // 取消某功能键定义
protected void _undef_key_done(string str, object pl); // 取得指定功能键
private void _up(object pl); // 游标往上移一行
private void _write(object pl); // 取得储存档案名称
protected void _write_done(string str, object pl, int quit); // 储存档案
private mapping EditedFiles=([ ]); // 编辑中的档案
/*
int iS_Row, iE_Row, // 可见视窗的始末行号
iS_Col, iE_Col, // 可见视窗的始未栏位
iRow, iCol, // 游标位置
is_Command_Mode, is_NewFile, is_Modify, // 档案状况旗标
is_Substituted; // 代换内码旗标
string *sText, // 档案内容
sChar, sOldChar, // 输入字串(命令)
sCount, // 命令计数
sFileName, // 编辑档名
sSearch, sReplace; // 搜寻/替换字串
mapping keymap; // 功能键定义对照表
*/
void start_edit(string file) // 呼叫编辑器,开始编辑
{
int i;
mapping me;
if (objectp(EditedFiles[file]))
{
write(sprintf("%s 正在编辑这个档案,请稍候再编辑。\n",
capitalize(EditedFiles[file]->query("id"))));
return;
} // if
this_player()->set_temp("me", ([ ]));
me = this_player()->query_temp("me");
me["sFileName"] = file;
if (file_size(file) <= 0)
{ // 档案长度小於 1
me["sText"] = ({ "" });
if (file_size(file) < 0)
{ // 新档
me["is_Command_Mode"] = 0;
me["is_NewFile"] = 1;
}
}
else
{
string content=read_file(file), tabs=" ";
// 档案长度大於 0
me["is_Command_Mode"] = 1;
me["is_NewFile"] = 0;
if (stringp(content))
{
me["sText"] = explode(read_file(file), "\n");
// 将 TAB,以 8 个空白代替,以方便游标位置的计算
for (i=sizeof(me["sText"])-1; i>=0; i--)
{
int len=sizeof(me["sText"][i]);
reset_eval_cost();
for (int j=0; j<len; j++)
if (me["sText"][i][j] == '\t')
me["sText"][i] = replace_string(
me["sText"][i], "\t", tabs[0..7-j%8]);
}
}
else me["sText"] = ({ "" });
} // old file
me["sCount"] = "";
me["sSearch"] = me["sReplace"] = me["is_Modify"] = 0;
me["iE_Row"] = 23;
me["iS_Row"] = me["iS_Col"] = me["iRow"] = me["iCol"] = 1;
EditedFiles += ([ file: this_player()->link() ]);
// 取得/设定功能键定义对照表
if (!mapp(me["keymap"] = this_player()->query("me_keymap")))
me["keymap"] = ([ ]);
if (this_player()->query("me_no_help") ||
this_player()->query_temp("no_me_help"))
{ // 非第一次使用编辑器,直接进入编辑器
_refresh_screen(this_player(), 1, 23, 1);
get_char("_input", HIDE, this_player());
}
else
{ // 第一次使用编辑器,先看功能说明
this_player()->set_temp("no_me_help", 1);
_help(this_player());
}
} // start_edit()
private void _refresh_cursor(object pl) // 更新游标位置
{
mapping me=pl->query_temp("me");
printf(ESC "[%d;%df", me["iRow"]+1, me["iCol"]);
} // _refresh_cursor()
private void _refresh_status(object pl) // 更新状态列
{
mapping me=pl->query_temp("me");
// 移动游标到 (1,1),用反相字元显示状态列
printf(HOME + NOR + REV + "列:%4d 行:%3d %-43s %10s [命令模式]" + NOR,
me["iS_Row"]+me["iRow"]-1, me["iS_Col"]+me["iCol"]-1,
sprintf("%s %s", me["sFileName"], (me["is_Modify"]? "(已修改)":
(me["is_NewFile"]? "(新档)": "")))[0..42],
(me["is_Command_Mode"]? "?:辅助画面": "[输入模式]"));
_refresh_cursor(pl);
} // _refresh_status()
// 重绘画面
private void _refresh_screen(object pl, int s_row, int e_row, int s_col)
{
int i, temp;
mapping me=pl->query_temp("me");
if (e_row < s_row) // 检查始末行号的先後次序
{
temp = e_row;
e_row = s_row;
s_row = temp;
}
if (s_row < 1) s_row = 1;
if (s_col < 1) s_col = 1;
if (e_row > sizeof(me["sText"])) // 不能超过档尾
e_row = sizeof(me["sText"]);
if (e_row-s_row > 22) e_row = s_row+22;
me["iS_Row"] = s_row; me["iE_Row"] = e_row;
me["iS_Col"] = s_col; me["iE_Col"] = s_col+79;
printf(REF+NOR); // 清除画面,移动游标到 (1,1)
for (i=me["iS_Row"]-1; i<me["iE_Row"]; i++)
printf("\r\n%s", me["sText"][i][me["iS_Col"]-1..me["iE_Col"]-1]);
for (i=me["iS_Row"]+22-me["iE_Row"]; i>0; i--)
printf("\r\n~"); // 不足行号用 ~ 表示
_refresh_status(pl);
} // _refresh_screen()
protected void _input(string str, object pl, int fresh) // 读得输入字串
{
int i, size, bs=0;
string *chars;
mapping me=pl->query_temp("me");
if (fresh)
{ // 重绘画面
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
get_char("_input", HIDE, pl);
return;
}
me["is_Substituted"] = 1; // 先设定代换内码旗标
if (str == "") // 代换掉 Backspace/Ctrl-Backspace
{
str = "BACKSPACE";
bs = 1;
}
if (str[0] == 27)
{
chars = explode(str, ESC); // 逸脱码的字串,以 ESC 断开
for (i=sizeof(chars)-1; i>=0; i--)
chars[i] = ESC + chars[i]; // 加回 ESC
if (sizeof(chars) == 0) // 若只是单一字元 ESC
chars = ({ ESC });
}
else chars = ({ str });
size = sizeof(chars);
for (i=0; i<size; i++)
{ // 转换逸脱码为编辑器内码
switch (chars[i])
{
case "\t": me["sChar"] = "TAB"; break;
case "\r": me["sChar"] = "ENTER"; break;
case ESC: me["sChar"] = "ESC"; break;
case ESC "OA":
case ESC "[A": me["sChar"] = "UP"; break;
case ESC "OB":
case ESC "[B": me["sChar"] = "DOWN"; break;
case ESC "OC":
case ESC "[C": me["sChar"] = "RIGHT"; break;
case ESC "OD":
case ESC "[D": me["sChar"] = "LEFT"; break;
case ESC "OH":
case ESC "[H":
case ESC "1~":
case ESC "[1~": me["sChar"] = "HOME"; break;
case ESC "[2~": me["sChar"] = "INSERT";break;
case ESC "[3~": me["sChar"] = "DELETE";break;
case ESC "4~": me["sChar"] = "END"; break;
case ESC "[4~": me["sChar"] = "END"; break;
case ESC "[5~": me["sChar"] = "PAGEUP";break;
case ESC "[6~": me["sChar"] = "PAGEDOWN";break;
case ESC "OP": me["sChar"] = "F1"; break;
case ESC "OQ": me["sChar"] = "F2"; break;
case ESC "OR": me["sChar"] = "F3"; break;
case ESC "OS": me["sChar"] = "F4"; break;
case ESC "m": me["sChar"] = "F5"; break;
case ESC "[17~": me["sChar"] = "F6"; break;
case ESC "[18~": me["sChar"] = "F7"; break;
case ESC "[19~": me["sChar"] = "F8"; break;
case ESC "[20~": me["sChar"] = "F9"; break;
case ESC "[21~": me["sChar"] = "F10"; break;
case ESC "[23~": me["sChar"] = "F11"; break;
case ESC "[24~": me["sChar"] = "F12"; break;
default:
if (sizeof(chars[i])==1 &&
0<chars[i][0] && chars[i][0]<27)
switch (chars[i][0])
{ // 代换内码,使在输入模式也能使用指令
case 1: me["sChar"]="Ctrl-A"; break;
case 2: me["sChar"]="Ctrl-B"; break;
case 4: me["sChar"]="Ctrl-D"; break;
case 6: me["sChar"]="Ctrl-F"; break;
case 7: me["sChar"]="Ctrl-G"; break;
case 10: me["sChar"]="Ctrl-J"; break;
case 11: me["sChar"]="Ctrl-K"; break;
case 12: me["sChar"]="Ctrl-L"; break;
case 14: me["sChar"]="Ctrl-N"; break;
case 15: me["sChar"]="Ctrl-O"; break;
case 16: me["sChar"]="Ctrl-P"; break;
case 17: me["sChar"]="Ctrl-Q"; break;
case 18: me["sChar"]="Ctrl-R"; break;
case 19: me["sChar"]="Ctrl-S"; break;
case 20: me["sChar"]="Ctrl-T"; break;
case 21: me["sChar"]="Ctrl-U"; break;
case 22: me["sChar"]="Ctrl-V"; break;
case 23: me["sChar"]="Ctrl-W"; break;
case 24: me["sChar"]="Ctrl-X"; break;
case 25: me["sChar"]="Ctrl-Y"; break;
case 26: me["sChar"]="Ctrl-Z"; break;
} // switch
else
{
me["sChar"] = chars[i]; // 此为普通字串
if (!bs) me["is_Substituted"] = 0; // 清除代换内
} // else
} // switch
// 将转换後的字串送到分派指令函式处理,并等待读取下个输入
if (_dispatcher(pl) && i==size-1) get_char("_input", HIDE, pl);
} // for
} // input()
private int _dispatcher(object pl) // 分派指令到不同函式
{
int i, count=1;
mapping me=pl->query_temp("me");
if ( me["is_Command_Mode"] ||
(me["is_Substituted"] && // 让输入模式也能使用某些指令
// 这二个指令不在这处理
me["sChar"]!="ENTER" && me["sChar"]!="TAB") )
{ // 现在是命令模式
if (sizeof(me["sChar"])!=1 && !me["is_Substituted"])
return 1;
// 检查功能键定义对照表,重新定义命令
if (!undefinedp(me["keymap"][me["sChar"]]))
me["sChar"] =
me["keymap"][me["sChar"]];
if (!stringp(me["sChar"])) return 1; // Type checking...
// 检查是数字的话,就是附加到命令计数里
if ('0'<=me["sChar"][0] && me["sChar"][0]<='9')
me["sCount"] += me["sChar"];
else
{
sscanf(me["sCount"], "%d", count);
me["sCount"] = ""; // 计数器归零
// 重覆上个指令
if (me["sChar"] == ".")
me["sChar"] = me["sOldChar"];
else // 记录这次的指令
me["sOldChar"] = me["sChar"];
}
for (i=0; i<count; i++)
switch (me["sChar"]) // 分派指令到不同函式
{
case "a":_append(pl); break;
case "d":
case "Ctrl-D": _del_line(pl); break;
case "f":
case "Ctrl-Z": _refresh(pl); break;
case "g":
case "Ctrl-G": _goto_line(pl); break;
case "h":
case "LEFT":
case "Ctrl-J": _left(pl); break;
case "i": _insert(pl); break;
case "j":
case "DOWN":
case "Ctrl-K": _down(pl); break;
case "k":
case "UP":
case "Ctrl-O": _up(pl); break;
case "l":
case "RIGHT":
case "Ctrl-L": _right(pl, 1,
(me["is_Command_Mode"]?0:1));
break;
case "m": _keymap(pl); break;
case "n":
case "Ctrl-N": _next_match(pl); break;
case "o": _append_line(pl); break;
case "q": // 表示不再读取新输入,结束编辑
case "F4":
case "Ctrl-Q": _quit(0, pl); return 0;
case "r":
case "Ctrl-R": _replace(pl); break;
case "s":
case "Ctrl-S": _search(pl); break;
case "u": _undef_key(pl); break;
case "w":
case "F2":
case "Ctrl-W": _write(pl); break;
case "x":
case "DELETE":
case "Ctrl-X": _del_char(pl, 0); break;
case "A":
case "HOME":
case "Ctrl-A": _home(pl); break;
case "B":
case "PAGEUP":
case "Ctrl-B": _page_up(pl); break;
case "E":
case "END":
case "Ctrl-E": _end(pl); break;
case "F":
case "PAGEDOWN":
case "Ctrl-F": _page_down(pl); break;
case "J":
case "Ctrl-P": _join(pl); break;
case "O": _insert_line(pl); break;
case "U":
case "Ctrl-U": _file_head(pl); break;
case "V":
case "Ctrl-V": _file_end(pl); break;
case "?":
case "F1":
case "Ctrl-Y": _help(pl); break;
case "~":
case "Ctrl-T": _insert_exclam_mark(pl); break;
case "BACKSPACE": _backspace(pl); break;
case "ESC": _esc(pl); break;
case "TAB": _tab(pl); break;
} // switch
} // if me["is_Command_Mode"]
else
_process(pl); // 处理输入模式的字串输入
return 1; // 表示继续读取新输入,继续编辑
} // dispatcher()
private void _append(object pl) // 在游标後面加字
{
mapping me=pl->query_temp("me");
if (sizeof(me["sText"]) == 0) return;
me["is_Command_Mode"] = 0;
_refresh_status(pl);
_right(pl, 1, 1);
} // _append()
private void _append_line(object pl) // 在游标底下加一新行
{
string *text;
mapping me=pl->query_temp("me");
me["is_Command_Mode"] = me["is_NewFile"] = 0;
me["is_Modify"] = 1;
text = me["sText"][0..me["iS_Row"]+me["iRow"]-2] + ({ "" }) +
me["sText"][me["iS_Row"]+me["iRow"]-1..<1];
me["sText"] = text;
_refresh_screen(pl, me["iS_Row"], sizeof(me["sText"]), 1);
me["iCol"] = 1;
_down(pl);
} // _append_line()
private void _backspace(object pl) // 删除游标前的字
{
mapping me=pl->query_temp("me");
if (me["iS_Col"] == me["iCol"]) return;
_left(pl);
_del_char(pl, 1);
} // _backspace()
protected void _confirm_save(string str, object pl) // 离开编辑器前确认存档
{
mapping me=pl->query_temp("me");
if (str=="y" || str=="Y") return _write_done("", pl, 1);
me["is_Modify"] = 0; // 设定「未修改」旗标
_quit(0, pl);
} // _confirm_save()
private void _del_char(object pl, int bs) // 删除游标上的字
{
int go_left=0; // 是否在删除後要左移游标
string str;
mapping me=pl->query_temp("me");
if (sizeof(me["sText"])==0 ||
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])==0)
return;
if (me["is_NewFile"] || !me["is_Modify"])
{
me["is_NewFile"] = 0;
me["is_Modify"] = 1;
_refresh_status(pl);
}
if (me["iS_Col"]+me["iCol"]-2 >=
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]))
return;
str = me["sText"][me["iS_Row"]+me["iRow"]-2][0..me["iS_Col"]+
me["iCol"]-3];
// 检查是否需要附加剩下的内容
if (me["iS_Col"]+me["iCol"]-1 <
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]))
str += me["sText"][me["iS_Row"]+
me["iRow"]-2][me["iS_Col"]+me["iCol"]-1..<1];
else go_left = 1; // 因为是删除行尾的字,所以要左
me["sText"][me["iS_Row"]+me["iRow"]-2] = str;
printf(ESC "[%d;1f%-80s", me["iRow"]+1, me["sText"][me["iS_Row"]+
me["iRow"]-2][me["iS_Col"]-1..me["iE_Col"]-1]);
if (go_left && !bs) _left(pl);
else _refresh_cursor(pl);
} // _del_char()
private void _del_line(object pl) // 删除整行
{
string *text=({ });
mapping me=pl->query_temp("me");
me["is_NewFile"] = 0;
me["is_Modify"] = 1;
if (me["iS_Row"]+me["iRow"]-2 > 0)
text = me["sText"][0..me["iS_Row"]+me["iRow"]-3];
text += me["sText"][me["iS_Row"]+me["iRow"]-1..<1];
me["sText"] = text;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
if (me["iS_Row"]+me["iRow"]-1 > sizeof(me["sText"]))
_up(pl); // 若是删除最後一行,就要上移游标
// 若游标的新位置超过行尾,则移动游标到行尾
else if (me["iS_Col"]+me["iCol"]-1 >
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]))
_end(pl);
} // _del_line()
private void _down(object pl) // 游标往下移一行
{
int acc;
mapping me=pl->query_temp("me");
// 检查是否已在档尾
if (me["iS_Row"]+me["iRow"]-1 >= sizeof(me["sText"]))
// 若已显示档尾下一行,则不做事
if (me["iRow"] < 23) return;
else
{ // 多显视档尾下一行,以突显档尾的存在
me["iS_Row"]++;
printf(ESC "[24;1f\r\n~");
me["iRow"] = 22;
}
else if (++me["iRow"] > 23)
{ // 画面上卷,显示下一行
me["iS_Row"]++; me["iE_Row"]++;
printf(ESC "[24;1f\r\n%s", me["sText"][me["iE_Row"]-1]
[me["iS_Col"]-1..me["iE_Col"]-1]);
me["iRow"] = 23;
}
// 若游标的新位置超过行尾,则移动游标到行尾
if (me["iS_Col"]+me["iCol"]-1 >
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]))
me["iCol"] = sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iS_Col"]+(me["is_Command_Mode"]?1:2);
// 若此行无字,则定位在第一栏
if (me["iCol"]==0 && me["iS_Col"]==1) me["iCol"] = 1;
if (me["iCol"] > 0)_refresh_status(pl);
else
{ // 游标的新位置在原画面外,需要重绘画面
acc = me["iCol"]; me["iCol"] = 1;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"],
me["iS_Col"]+acc-1);
}
} // _down()
private void _end(object pl) // 将游标移到行尾
{
mapping me=pl->query_temp("me");
if (sizeof(me["sText"]) == 0) return;
// 计算行尾的位置
me["iCol"] = sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iS_Col"]+(me["is_Command_Mode"]?1:2);
if (me["iCol"] == 0) me["iCol"] = 1; // 若此行无字,则定位在第一栏
if (sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]) < me["iE_Col"])
_refresh_status(pl);
else
{ // 游标的新位置在原画面外,需要重绘画面
me["iCol"] = 79;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]+
(sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iE_Col"]+1));
}
} // _end()
private void _esc(object pl) // 从输入模式回到命令模式
{
mapping me=pl->query_temp("me");
me["is_Command_Mode"] = 1;
_left(pl);
} // _esc()
private void _file_end(object pl) // 将游标移到档尾
{
mapping me=pl->query_temp("me");
if (sizeof(me["sText"]) == 0) return;
_goto_line_done(sprintf("%d", sizeof(me["sText"])), pl, 0);
} // _file_end()
private void _file_head(object pl) // 将游标移到档头
{
mapping me=pl->query_temp("me");
if (sizeof(me["sText"]) == 0) return;
_goto_line_done("1", pl, 0);
} // _file_head()
private void _goto_line(object pl) // 跳到特定行去
{
mapping me=pl->query_temp("me");
_message(pl, sprintf("请输入行号(直接按 ENTER 取消,1~%d):",
sizeof(me["sText"])), "_goto_line_done", ECHO, 1);
} // _goto_line()
protected void _goto_line_done(string str, object pl, int rein) // 取得行号
{
int no;
mapping me=pl->query_temp("me");
if (str == "") return _message_done("", pl);
if (sscanf(str, "%d", no)!=1 || no<1 || no>sizeof(me["sText"]))
return _message(pl, "错误的行号!", "_message_done", HIDE);
me["iCol"] = 1;
if (me["iS_Row"]<=no && no<=me["iE_Row"])
{ // 指定行号在原可视范围中
me["iRow"] = no-me["iS_Row"]+1;
_refresh_status(pl);
}
else
{ // 指定行号不在原可视范围中,需要重绘画面
me["iS_Row"] = no-11;
if (me["iS_Row"] < 1) me["iS_Row"] = 1;
if (me["iE_Row"] < no+11) me["iE_Row"] = no+11;
me["iRow"] = no-me["iS_Row"]+1;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], 1);
}
if (rein) get_char("_input", HIDE, pl); // 检查是否需要读取下次输入
} // _goto_line_done()
private void _help(object pl) // 辅助画面
{
printf(REF +
"【 LPMud 全萤幕编辑器 】1.3 版 3/25/1998 by 谢崇祥(Kenny Hsieh), 版权所有.\r
\r
a 在游标後面加字 d Ctrl-D 删除整行\r
f Ctrl-Z 更新画面 g Ctrl-G 跳到特定行去\r
h Ctrl-J 游标往左移一字 i 在游标前面插字\r
j Ctrl-K 游标往下移一行 k Ctrl-O 游标往上移一行\r
l Ctrl-L 游标往右移一字 m 定义新功\能键\r
n Ctrl-N 搜寻/替换下个符合字串 o 在游标底下加一新行\r
q Ctrl-Q 离开编辑器 r Ctrl-R 字串替换\r
s Ctrl-S 字串搜寻 u 取消某功\能键定义\r
w Ctrl-W 储存档案 x Ctrl-X 删除游标上的字\r
A Ctrl-A 将游标移到行首 B Ctrl-B 往上卷一页(22 行)\r
E Ctrl-E 将游标移到行尾 F Ctrl-F 往下卷一页(22 行)\r
J Ctrl-P 将下行文字接到此行後面 O 在游标上方加一新行\r
U Ctrl-U 将游标移到档头 V Ctrl-V 将游标移到档尾\r\n");
printf(
". 重覆上个指令 ? Ctrl-Y 辅助画面(此画面)\r
~ Ctrl-T 在游标前面插入一个「!」字元\r\n
合法的定义键是可印字母和 ESC、F1~F12、BACKSPACE、TAB、ENTER、INSERT、DELETE、\r
HOME、END、PAGEUP、PAGEDOWN、UP、DOWN、LEFT、RIGHT、Ctrl-A~Ctrl-Z。\r
\r
欢迎传播此编辑器,但请保留版权宣告,有任何问题和建议请联络我:\r
kenny@cindy.cis.nctu.edu.tw。\r
[按任意键回到编辑器]"
);
get_char("_input", HIDE, pl, REFRESH); // 读取按键以重绘画面
} // _help()
private void _home(object pl) // 将游标移到行首
{
mapping me=pl->query_temp("me");
me["iCol"] = 1;
if (me["iS_Col"] == 1)_refresh_status(pl);
else _refresh_screen(pl, me["iS_Row"], me["iE_Row"], 1);
} // _home()
private void _insert(object pl) // 在游标前面插字
{
mapping me=pl->query_temp("me");
if (sizeof(me["sText"]) == 0) return;
me["is_Command_Mode"] = 0;
_refresh_status(pl);
} // _insert()
private void _insert_line(object pl) // 在游标上方加一新行
{
string *text=({ });
mapping me=pl->query_temp("me");
me["is_Command_Mode"] = me["is_NewFile"] = 0;
me["is_Modify"] = 1;
// 检查是否游标上方是否有内容
if (me["iS_Row"]+me["iRow"]-3 >= 0)
text = me["sText"][0..me["iS_Row"]+me["iRow"]-3];
text += ({ "" });
text += me["sText"][me["iS_Row"]+me["iRow"]-2..<1];
me["sText"] = text;
me["iCol"] = 1;
_refresh_screen(pl, me["iS_Row"], sizeof(me["sText"]), 1);
} // _insert_line()
private void _insert_exclam_mark(object pl) // 在游标前面插入一个「!」字元
{
mapping me=pl->query_temp("me");
// 因为无法正常输入「!」,所以特地加此函式以输入「!」。
if (sizeof(me["sText"]) == 0) return;
me["sChar"] = "!";
_process(pl);
} // _insert_!()
private void _join(object pl) // 将下行文字移到此行後面
{
string *text=({ });
mapping me=pl->query_temp("me");
if (me["iS_Row"]+me["iRow"]-1 >= sizeof(me["sText"])) return;
me["is_NewFile"] = 0;
me["is_Modify"] = 1;
_end(pl); // 先将游标移到行尾
text = me["sText"][0..me["iS_Row"]+me["iRow"]-2];
if (sizeof(me["sText"][me["iS_Row"]+me["iRow"]-1]))
{ // 若下行有内容附加上来
text[me["iS_Row"]+me["iRow"]-2] += (" "+
me["sText"][me["iS_Row"]+me["iRow"]-1]);
_right(pl, 1, 1);
}
text += me["sText"][me["iS_Row"]+me["iRow"]..<1];
me["sText"] = text;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
} // _join()
private void _keymap(object pl) // 定义新功能键
{
_message(pl, "请输入新定义键和原功\能键(直接按 ENTER 取消,以空白隔开)",
"_keymap_done", ECHO);
} // _keymap()
protected void _keymap_done(string str, object pl) // 取得定义功能键
{
string old, _new;
mapping me=pl->query_temp("me");
_refresh_status(pl);
if (str != "")
{ // 若有资料输入
if (sscanf(str, "%s %s", _new, old) != 2)
return _message(pl, "输入格式错误。", "_message_done",
HIDE);
me["keymap"][_new] = old;
_message(pl, sprintf("好了,从此以後新定义键「%s」就有原功\能键?
?s」的功\能了!",
_new, old), "_message_done", HIDE);
}
else get_char("_input", HIDE, pl); // 取消输入,继续读取下个输入
} // _keymap_done()
private void _left(object pl) // 游标往左移一字
{
mapping me=pl->query_temp("me");
if (me["iS_Col"]==1 && me["iCol"]==1) return _refresh_status(pl);
if (--me["iCol"] < 1)
{ // 游标的新位置在原画面外,需要重绘画面
// 若左移 8 栏太多的话,就只左移一栏
if (me["iS_Col"]-8 < 1)
me["iCol"] = me["iS_Col"]-1;
else me["iCol"] = 8; // 不然就设定游标在第 8 栏位置
_refresh_screen(pl, me["iS_Row"], me["iE_Row"],
me["iS_Col"]-me["iCol"]);
return;
}
_refresh_status(pl);
} // _left()
// 在状态列显示讯息
private varargs void _message(object pl, string str, string callback, int hide,
mixed arg)
{
printf(HOME + NOR + REV); // 移动游标到 (1,1),设定反相字元显示
// 清除原状态列的讯息
printf("
");
printf(HOME + str); // 移动游标到 (1,1),再显示讯息
input_to(callback, hide, pl, arg); // 读取输入资料
} // _message()
protected void _message_done(string str, object pl) // 结束讯息的显示
{
_refresh_status(pl);
get_char("_input", HIDE, pl); // 继续读取输入字串
} // _message_done()
private void _next_match(object pl) // 搜寻/替换下个符合字串
{
mapping me=pl->query_temp("me");
string str="";
// 设定起始搜寻位置为游标现在位置
int j=me["iS_Col"]+me["iCol"]-1,
i, ofs;
if (!stringp(me["sSearch"])) return; // 若没先设定搜寻字串,不做事
for (i=me["iS_Row"]+me["iRow"]-2; i<sizeof(me["sText"]); i++)
{
if ((ofs = strsrch(me["sText"][i][j-1..<1], me["sSearch"]))== -1)
j = 1; // 这行没找到的话,设定下行从第一栏开始找
else
{ // 找到指定字串了, 移动游标到目的行
_goto_line_done(sprintf("%d", i+1), pl, 0);
me["iCol"] = j+ofs; // 计算指定字串的绝对位置
// 若指定字串落在原画面外,则重绘画面
if (me["iCol"]<me["iS_Col"] ||
me["iCol"]+strlen(me["sSearch"])>me["iS_Col"]+79)
_refresh_screen(pl, me["iS_Row"], me["iE_Row"],
me["iCol"]);
if (stringp(me["sReplace"]))
{ // 需要替换字串
me["is_NewFile"] = 0;
me["is_Modify"] = 1;
// 附加游标前内容
str = me["sText"][i][0..me["iCol"]-2];
str += me["sReplace"];
str += (me["sText"][i][me["iCol"]+
strlen(me["sSearch"])-1..<1]);
me["sText"][i] = str;
// 若替换字串落在原画面外,则重绘画面
if (me["iCol"]<me["iS_Col"] ||
me["iCol"]+strlen(me["sReplace"])
> me["iS_Col"]+79)
_refresh_screen(pl, me["iS_Row"],
me["iE_Row"], me["iCol"]);
// 将游漂移到替换字串後面
me["iCol"] = me["iCol"]+strlen(me["sReplace"])-
me["iS_Col"]+1;
printf(ESC "[%d;1f%-80s", me["iRow"]+1,
me["sText"][me["iS_Row"]+
me["iRow"]-2][me["iS_Col"]-1
..me["iE_Col"]-1]);
}
// 将游漂移到搜寻字串後面
else
me["iCol"] = me["iCol"]+strlen(me["sSearch"])-me["iS_Col"]+1;
_refresh_status(pl);
break;
} // if found
} // for each row
if (i >= sizeof(me["sText"]))
_message(pl, "找不到指定字串!", "_message_done", HIDE);
else get_char("_input", HIDE, pl); // 读取下个输入字串
} // _next_match()
private void _page_down(object pl) // 往下卷一页(22 行)
{
mapping me=pl->query_temp("me");
if (me["iS_Row"]+22 > sizeof(me["sText"])) return; // 检查是否不能再卷了
me["iS_Row"] += 22; me["iE_Row"] += 22;
// 检查游标的新位置是否超过档尾
if (me["iS_Row"]+me["iRow"]-1 > sizeof(me["sText"]))
me["iRow"] = sizeof(me["sText"])-me["iS_Row"]+1;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
// 若游标的新位置超过行尾,则移动游标到行尾
if (me["iS_Col"]+me["iCol"]-1 > sizeof(me["sText"][me["iS_Row"]+
me["iRow"]-2]))
_end(pl);
} // _page_down()
private void _page_up(object pl) // 往上卷一页(22 行)
{
mapping me=pl->query_temp("me");
if (me["iS_Row"] <= 1) return; // 检查是否不能再卷了
me["iS_Row"] -= 22;
if (me["iS_Row"] < 1) me["iS_Row"] = 1; // 最多只能翻到第一列
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
// 若游标的新位置超过行尾,则移动游标到行尾
if (me["iS_Col"]+me["iCol"]-1 >
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2]))
_end(pl);
} // _page_up()
private void _process(object pl) // 处理输入模式的字串输入
{
int i, size;
string str, rest, *input;
mapping me=pl->query_temp("me");
if (me["is_Modify"]==0 || me["is_NewFile"]==1)
{
me["is_NewFile"] = 0;
me["is_Modify"] = 1;
_refresh_status(pl);
}
if (!me["is_Substituted"] && (strsrch(me["sChar"], "\r")!=-1 ||
strsrch(me["sChar"], "\n")!=-1))
me["is_Substituted"] = 1; // 设定内码代换旗标
me["sChar"] = replace_string(me["sChar"], "\t", " ");
me["sChar"] = replace_string(me["sChar"], "\r", "\rENTER\r");
me["sChar"] = replace_string(me["sChar"], "\n", "\rENTER\r");
input = explode(me["sChar"], "\r");
size = sizeof(input);
for (i=0; i<size; i++) // 一次处理一行输入
{
if (me["is_Substituted"] && input[i] == "ENTER")
{ // 当键入 ENTER 时,要将游标之後的内容移到下面的新行
rest = me["sText"][me["iS_Row"]+
me["iRow"]-2][me["iS_Col"]+me["iCol"]-2..<1];
me["sText"][me["iS_Row"]+me["iRow"]-2] =
me["sText"][me["iS_Row"]+
me["iRow"]-2][0..me["iS_Col"]+me["iCol"]-3];
_append_line(pl); // 在游标底下加一新行
// 新行的内容是原游标位置以後的内容
me["sText"][me["iS_Row"]+me["iRow"]-2] = rest;
continue;
}
// 输入字串不是 ENTER 时, 处理 TAB 的定位
if (me["is_Substituted"] && input[i] == "TAB")
input[i] = " "[0..7-(me["iCol"]-1)%8];
str = me["sText"][me["iS_Row"]+me["iRow"]-2][0..me["iS_Col"]+
me["iCol"]-3] + input[i] + me["sText"][me["iS_Row"] +
me["iRow"]-2][me["iS_Col"]+ me["iCol"]-2..<1];
me["sText"][me["iS_Row"]+me["iRow"]-2] = str;
_right(pl, sizeof(input[i]), 1);
} // for
printf(ESC "[%d;1f%s", me["iRow"]+1, me["sText"][me["iS_Row"]+
me["iRow"]-2][me["iS_Col"]-1..me["iE_Col"]-1]);
_refresh_cursor(pl);
} // _process()
protected void _quit(mixed unused, mixed pl) // 离开编辑器
{
mapping me;
seteuid(geteuid(pl));
me = pl->query_temp("me");
if (me["is_Modify"])
return _message(pl, "此档案已更改,请问需要存档吗(y/n)?[n]",
"_confirm_save", ECHO);
me["iRow"] = 23;
_refresh_cursor(pl); // 移动游标到最後一行
printf(NOR "\r\n");
// 若功能键定义对照表是空的,就清除玩家身上的记录,不然就记录在玩家身上
if (sizeof(me["keymap"]) == 0) pl->delete("me_keymap");
else pl->set("me_keymap", me["keymap"]);
map_delete(EditedFiles, pl->query_temp("me/sFileName"));
pl->delete_temp("me"); // 清除编辑器用到的暂时变数
} // _quit()
private void _refresh(object pl) // 更新画面
{
mapping me=pl->query_temp("me");
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
} // _refresh()
private void _replace(object pl) // 字串替换
{
_message(pl, "搜寻/替换字串(直接按ENTER取消,以空白隔开):",
"_replace_done", ECHO);
} // _replace()
protected void _replace_done(string str, object pl) // 取得替换字串
{
mapping me=pl->query_temp("me");
_refresh_status(pl);
if (str != "")
{ // 有输入资料时
if (sscanf(str, "%s %s", me["sSearch"], me["sReplace"]) != 2)
{ // 只有一个字串,就指定为搜寻字串,意即拿掉指定字串
me["sSearch"] = str;
me["sReplace"] = "";
}
_next_match(pl);
}
else get_char("_input", HIDE, pl); // 继续读取下个输入字串
} // _replace_done()
private void _right(object pl, int col, int extra) // 游标往右移一字
{
int acc;
mapping me=pl->query_temp("me");
if (sizeof(me["sText"])==0 || me["iS_Col"]+me["iCol"]-1>
sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-1+extra)
return;
me["iCol"] += col;
if (me["iS_Col"]+me["iCol"]-1 > sizeof(me["sText"][me["iS_Row"]+
me["iRow"]-2])+extra)
me["iCol"] = sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iS_Col"]+1+extra;
if (me["iCol"] > 80)
{ // 游标的新位置不在可见视窗内,需要往右移动视窗
// 若右移 8 栏太多的话,就只右移到行尾
if (me["iE_Col"]+8 > sizeof(me["sText"][me["iS_Row"]+
me["iRow"]-2])+1)
acc = sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iE_Col"]+1;
else acc = 8;
me["iCol"] = 80-acc+1; // 计算游标的新位置
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]+acc);
return;
}
_refresh_status(pl);
} // _right()
private void _search(object pl) // 字串搜寻
{
_message(pl, "请输入搜寻字串(直接按 ENTER 取消):", "_search_done",
ECHO);
} // _search()
protected void _search_done(string str, object pl) // 取得搜寻字串
{
mapping me=pl->query_temp("me");
_refresh_status(pl);
if (str != "")
{ // 有输入资料时
me["sSearch"] = str; me["sReplace"] = 0;
_next_match(pl);
}
else get_char("_input", HIDE, pl); // 继续读取下个输入字串
} // _search_done()
private void _tab(object pl) // 命令模式下 TAB 键的定位
{
mapping me=pl->query_temp("me");
_right(pl, 8-(me["iCol"]-1)%8, 0);
} // _tab()
private void _undef_key(object pl) // 取消某功能键定义
{
_message(pl, "请输入欲取消定义之功\能键(直接按 ENTER 取消):",
"_undef_key_done", ECHO);
} // undef_key()
protected void _undef_key_done(string str, object pl) // 取得指定功能键
{
mapping me=pl->query_temp("me");
if (str != "") map_delete(me["keymap"], str);
_message_done("", pl);
} // undef_key_done()
private void _up(object pl) // 游标往上移一行
{
int acc;
mapping me=pl->query_temp("me");
if (me["iRow"]==1 && me["iS_Row"]==1) return;
if (--me["iRow"] < 1)
{ // 游标新位置不在可见视窗内,就上移视窗
me["iS_Row"]--;
me["iE_Row"]=me["iS_Row"]+22;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"], me["iS_Col"]);
me["iRow"] = 1;
}
// 若游标新位置超过行尾,则移到行尾
if (me["iS_Col"]+me["iCol"]-1 > sizeof(me["sText"][me["iS_Row"]+
me["iRow"]-2]))
me["iCol"] = sizeof(me["sText"][me["iS_Row"]+me["iRow"]-2])-
me["iS_Col"]+(me["is_Command_Mode"]?1:2);
// 若此行无字,则定位在第一栏
if (me["iCol"]==0 && me["iS_Col"]==1) me["iCol"] = 1;
if (me["iCol"] > 0) _refresh_status(pl);
else
{ // 游标新位置不在可见视窗内,重绘画面
acc = me["iCol"]; me["iCol"] = 1;
_refresh_screen(pl, me["iS_Row"], me["iE_Row"],
me["iS_Col"]+acc-1);
}
} // _up()
private void _write(object pl) // 取得储存档案名称
{
_message(pl, "请输入新档名(直接按 ENTER 以使用旧档名):",
"_write_done", ECHO, 0);
} // _write()
protected void _write_done(string str, object pl, int quit) // 储存档案
{
string callback;
mapping me=pl->query_temp("me");
if (str == "") str = me["sFileName"];
else // 取得档名
str = resolve_path(pl->query("cwd"), str);
if (quit) callback = "_quit";
else callback = "_message_done";
if (write_file(str, implode(me["sText"], "\n")+"\n", 1))
{
if (me["is_Modify"])
log_file(LOGFILE, sprintf("[%s] %s %s %s\n",
ctime(time()), getuid(pl),
me["is_NewFile"]? "+": "*", str));
me["is_Modify"] = me["is_NewFile"] = 0;
me["sFileName"] = str;
_message(pl, "存档成功\。", callback, HIDE);
}
else
_message(pl, "存档失败。", callback, HIDE);
} // write_done()
| 412 | 0.667389 | 1 | 0.667389 | game-dev | MEDIA | 0.318428 | game-dev | 0.910436 | 1 | 0.910436 |
smogon/pokemon-showdown | 2,076 | data/mods/gen2stadium2/moves.ts | export const Moves: import('../../../sim/dex-moves').ModdedMoveDataTable = {
// Belly Drum no longer boosts attack by 2 stages if under 50% health.
bellydrum: {
inherit: true,
onHit(target) {
if (target.boosts.atk >= 6 || target.hp <= target.maxhp / 2) {
return false;
}
this.directDamage(target.maxhp / 2);
const originalStage = target.boosts.atk;
let currentStage = originalStage;
let boosts = 0;
let loopStage = 0;
while (currentStage < 6) {
loopStage = currentStage;
currentStage++;
if (currentStage < 6) currentStage++;
target.boosts.atk = loopStage;
if (target.getStat('atk', false, true) < 999) {
target.boosts.atk = currentStage;
continue;
}
target.boosts.atk = currentStage - 1;
break;
}
boosts = target.boosts.atk - originalStage;
target.boosts.atk = originalStage;
this.boost({ atk: boosts });
},
},
destinybond: {
inherit: true,
onPrepareHit(pokemon) {
if (pokemon.side.pokemonLeft === 1) {
this.hint("In Pokemon Stadium 2, Destiny Bond fails if it is being used by your last Pokemon.");
return false;
}
},
},
/**
* In Stadium 2, moves which affect the stat stages of a Pokemon, such as moves which boost ones own stats,
* lower the targets stats, or Haze, causes the afflicted stat to be re-calculated without factoring in
* status aliments, thus if a Pokemon is burned or paralyzed and either active Pokemon uses Haze, then their
* attack and speed are re-calculated while ignoring their status ailments, so their attack would go from 50% to normal
*/
haze: {
inherit: true,
onHitField() {
this.add('-clearallboost');
for (const pokemon of this.getAllActive()) {
pokemon.clearBoosts();
pokemon.removeVolatile('brnattackdrop');
pokemon.removeVolatile('parspeeddrop');
}
},
},
perishsong: {
inherit: true,
onPrepareHit(pokemon) {
if (pokemon.side.pokemonLeft === 1) {
this.hint("In Pokemon Stadium 2, Perish Song fails if it is being used by your last Pokemon.");
return false;
}
},
},
};
| 412 | 0.930664 | 1 | 0.930664 | game-dev | MEDIA | 0.886661 | game-dev | 0.794018 | 1 | 0.794018 |
KDE/kmail | 1,188 | src/job/savedraftjob.cpp | /*
SPDX-FileCopyrightText: 2014-2025 Laurent Montel <montel@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "savedraftjob.h"
#include "kmail_debug.h"
#include <Akonadi/Item>
#include <Akonadi/ItemCreateJob>
#include <Akonadi/MessageFlags>
#include <Akonadi/MessageStatus>
SaveDraftJob::SaveDraftJob(const KMime::Message::Ptr &msg, const Akonadi::Collection &col, QObject *parent)
: KJob(parent)
, mMsg(msg)
, mCollection(col)
{
}
SaveDraftJob::~SaveDraftJob() = default;
void SaveDraftJob::start()
{
Akonadi::Item item;
item.setPayload(mMsg);
item.setMimeType(KMime::Message::mimeType());
item.setFlag(Akonadi::MessageFlags::Seen);
Akonadi::MessageFlags::copyMessageFlags(*mMsg, item);
auto createJob = new Akonadi::ItemCreateJob(item, mCollection);
connect(createJob, &Akonadi::ItemCreateJob::result, this, &SaveDraftJob::slotStoreDone);
}
void SaveDraftJob::slotStoreDone(KJob *job)
{
if (job->error()) {
qCDebug(KMAIL_LOG) << " job->errorString() : " << job->errorString();
setError(job->error());
setErrorText(job->errorText());
}
emitResult();
}
#include "moc_savedraftjob.cpp"
| 412 | 0.771181 | 1 | 0.771181 | game-dev | MEDIA | 0.273722 | game-dev | 0.782039 | 1 | 0.782039 |
ServUO/ServUO | 1,957 | Scripts/Mobiles/NPCs/Artist.cs | using System;
using Server.Items;
namespace Server.Mobiles
{
public class Artist : BaseCreature
{
[Constructable]
public Artist()
: base(AIType.AI_Animal, FightMode.None, 10, 1, 0.2, 0.4)
{
this.InitStats(31, 41, 51);
this.SetSkill(SkillName.Healing, 36, 68);
this.SpeechHue = Utility.RandomDyedHue();
this.Title = "the artist";
this.Hue = Utility.RandomSkinHue();
if (this.Female = Utility.RandomBool())
{
this.Body = 0x191;
this.Name = NameList.RandomName("female");
}
else
{
this.Body = 0x190;
this.Name = NameList.RandomName("male");
}
this.AddItem(new Doublet(Utility.RandomDyedHue()));
this.AddItem(new Sandals(Utility.RandomNeutralHue()));
this.AddItem(new ShortPants(Utility.RandomNeutralHue()));
this.AddItem(new HalfApron(Utility.RandomDyedHue()));
Utility.AssignRandomHair(this);
Container pack = new Backpack();
pack.DropItem(new Gold(250, 300));
pack.Movable = false;
this.AddItem(pack);
}
public Artist(Serial serial)
: base(serial)
{
}
public override bool CanTeach
{
get
{
return true;
}
}
public override bool ClickTitle
{
get
{
return false;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 412 | 0.716922 | 1 | 0.716922 | game-dev | MEDIA | 0.940584 | game-dev | 0.899485 | 1 | 0.899485 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 4,602 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/GameLog.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2022 Evan Debenham
*
* Summoning Pixel Dungeon
* Copyright (C) 2019-2022 TrashboxBobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.ui;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.ui.Component;
import com.watabou.utils.Signal;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class GameLog extends Component implements Signal.Listener<String> {
private static final int MAX_LINES = 3;
private static final Pattern PUNCTUATION = Pattern.compile( ".*[.,;?! ]$" );
private RenderedTextBlock lastEntry;
private int lastColor;
private static ArrayList<Entry> entries = new ArrayList<>();
public GameLog() {
super();
GLog.update.replace( this );
recreateLines();
}
private static ArrayList<String> textsToAdd = new ArrayList<>();
@Override
public synchronized void update() {
for (String text : textsToAdd){
if (length != entries.size()){
clear();
recreateLines();
}
if (text.equals( GLog.NEW_LINE )){
lastEntry = null;
continue;
}
int color = CharSprite.DEFAULT;
if (text.startsWith( GLog.POSITIVE )) {
text = text.substring( GLog.POSITIVE.length() );
color = CharSprite.POSITIVE;
} else
if (text.startsWith( GLog.NEGATIVE )) {
text = text.substring( GLog.NEGATIVE.length() );
color = CharSprite.NEGATIVE;
} else
if (text.startsWith( GLog.WARNING )) {
text = text.substring( GLog.WARNING.length() );
color = CharSprite.WARNING;
} else
if (text.startsWith( GLog.HIGHLIGHT )) {
text = text.substring( GLog.HIGHLIGHT.length() );
color = CharSprite.NEUTRAL;
}
if (lastEntry != null && color == lastColor && lastEntry.nLines < MAX_LINES) {
String lastMessage = lastEntry.text();
lastEntry.text( lastMessage.length() == 0 ? text : lastMessage + " " + text );
entries.get( entries.size() - 1 ).text = lastEntry.text();
} else {
lastEntry = PixelScene.renderTextBlock( text, 6 );
lastEntry.setHightlighting( false );
lastEntry.hardlight( color );
lastColor = color;
add( lastEntry );
entries.add( new Entry( text, color ) );
}
if (length > 0) {
int nLines;
do {
nLines = 0;
for (int i = 0; i < length-1; i++) {
nLines += ((RenderedTextBlock) members.get(i)).nLines;
}
if (nLines > MAX_LINES) {
RenderedTextBlock r = ((RenderedTextBlock) members.get(0));
remove(r);
r.destroy();
entries.remove( 0 );
}
} while (nLines > MAX_LINES);
if (entries.isEmpty()) {
lastEntry = null;
}
}
}
if (!textsToAdd.isEmpty()){
layout();
textsToAdd.clear();
}
super.update();
}
private synchronized void recreateLines() {
for (Entry entry : entries) {
lastEntry = PixelScene.renderTextBlock( entry.text, 6 );
lastEntry.hardlight( lastColor = entry.color );
add( lastEntry );
}
}
public synchronized void newLine() {
lastEntry = null;
}
@Override
public synchronized boolean onSignal( String text ) {
textsToAdd.add(text);
return false;
}
@Override
protected void layout() {
float pos = y;
for (int i=length-1; i >= 0; i--) {
RenderedTextBlock entry = (RenderedTextBlock)members.get( i );
entry.maxWidth((int)width);
entry.setPos(x, pos-entry.height());
pos -= entry.height()+2;
}
}
@Override
public void destroy() {
GLog.update.remove( this );
super.destroy();
}
private static class Entry {
public String text;
public int color;
public Entry( String text, int color ) {
this.text = text;
this.color = color;
}
}
public static void wipe() {
entries.clear();
}
}
| 412 | 0.909983 | 1 | 0.909983 | game-dev | MEDIA | 0.650401 | game-dev | 0.983299 | 1 | 0.983299 |
folgerwang/UnrealEngine | 7,410 | Engine/Source/Editor/UnrealEd/Classes/Commandlets/ResavePackagesCommandlet.h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "Commandlets/Commandlet.h"
#include "Engine/EngineTypes.h"
#include "ResavePackagesCommandlet.generated.h"
// Log category should be accessible by derived classes
UNREALED_API DECLARE_LOG_CATEGORY_EXTERN(LogContentCommandlet, Log, All);
UCLASS()
// Added UNREALED_API to expose this to the save packages test
class UNREALED_API UResavePackagesCommandlet : public UCommandlet
{
GENERATED_UCLASS_BODY()
protected:
enum EBrevity
{
VERY_VERBOSE,
INFORMATIVE,
ONLY_ERRORS
};
EBrevity Verbosity;
/** only packages that have this version or higher will be resaved; a value of IGNORE_PACKAGE_VERSION indicates that there is no minimum package version */
int32 MinResaveUE4Version;
/**
* Limits resaving to packages with this UE4 package version or lower.
* A value of IGNORE_PACKAGE_VERSION (default) removes this limitation.
*/
int32 MaxResaveUE4Version;
/**
* Limits resaving to packages with this licensee package version or lower.
* A value of IGNORE_PACKAGE_VERSION (default) removes this limitation.
*/
int32 MaxResaveLicenseeUE4Version;
/**
* Maximum number of packages to resave to avoid having a massive sync
* A value of -1 (default) removes this limitation.
*/
int32 MaxPackagesToResave;
/** allows users to save only packages with a particular class in them (useful for fixing content) */
TArray<FName> ResaveClasses;
// If non-empty, this substring has to be present in the package name for the commandlet to process it
FString PackageSubstring;
// strip editor only content
bool bStripEditorOnlyContent;
// skip the assert when a package can not be opened
bool bCanIgnoreFails;
/** load all packages, and display warnings for those packages which would have been resaved but were read-only */
bool bVerifyContent;
/** if we should only save dirty packages **/
bool bOnlySaveDirtyPackages;
/** if we should auto checkout packages that need to be saved**/
bool bAutoCheckOut;
/** if we should simply skip checked out files rather than error-ing out */
bool bSkipCheckedOutFiles;
/** if we should auto checkin packages that were checked out**/
bool bAutoCheckIn;
/** Should we build lighting for the packages we are saving? **/
bool bShouldBuildLighting;
/** Should we build reflection captures for the packages we are saving? **/
bool bShouldBuildReflectionCaptures;
/** Should we build texture streaming for the packages we are saving? **/
bool bShouldBuildTextureStreaming;
/** Similar to above, but applies to all packages rather than just maps **/
bool bShouldBuildTextureStreamingForAll;
/** only process packages containing materials **/
bool bOnlyMaterials;
/** Only save packages with a changelist of zero **/
bool bOnlyUnversioned;
/** Ignore package version changelist **/
bool bIgnoreChangelist;
/** Filter packages based on a collection **/
TSet<FName> CollectionFilter;
/** Should we generated HLOD proxy meshes */
bool bShouldBuildHLOD;
bool bGenerateClusters;
bool bGenerateMeshProxies;
bool bForceClusterGeneration;
bool bForceProxyGeneration;
bool bForceEnableHLODForLevel;
bool bForceSingleClusterForLevel;
FString ForceHLODSetupAsset;
FString HLODSkipToMap;
bool bForceUATEnvironmentVariableSet;
/** Running count of packages that got modified and will need to be resaved */
int32 PackagesRequiringResave;
/** Only collect garbage after N packages */
int32 GarbageCollectionFrequency;
/** Lighting Build Quality(default: Production) */
ELightingBuildQuality LightingBuildQuality;
/** List of files to submit */
TArray<FString> FilesToSubmit;
/** The list of switches that were passed on the commandline */
TArray<FString> Switches;
/** List of redirector packages that should be fixed up at the end */
TArray<FString> RedirectorsToFixup;
/**
* Evaluates the command-line to determine which maps to check. By default all maps are checked
* Provides child classes with a chance to initialize any variables, parse the command line, etc.
*
* @param Tokens the list of tokens that were passed to the commandlet
* @param MapPathNames receives the list of path names for the maps that will be checked.
*
* @return 0 to indicate that the commandlet should continue; otherwise, the error code that should be returned by Main()
*/
virtual int32 InitializeResaveParameters( const TArray<FString>& Tokens, TArray<FString>& MapPathNames );
/** Loads and saves a single package */
virtual void LoadAndSaveOnePackage(const FString& Filename);
/** Checks to see if a package should be skipped */
virtual bool ShouldSkipPackage(const FString& Filename);
/** Deletes a single package */
virtual void DeleteOnePackage(const FString& Filename);
/**
* Allow the commandlet to perform any operations on the export/import table of the package before all objects in the package are loaded.
*
* @param PackageLinker the linker for the package about to be loaded
* @param bSavePackage [in] indicates whether the package is currently going to be saved
* [out] set to true to resave the package
*/
virtual void PerformPreloadOperations( FLinkerLoad* PackageLinker, bool& bSavePackage );
/**
* Allows the commandlet to perform any additional operations on the object before it is resaved.
*
* @param Object the object in the current package that is currently being processed
* @param bSavePackage [in] indicates whether the package is currently going to be saved
* [out] set to true to resave the package
*/
virtual void PerformAdditionalOperations( class UObject* Object, bool& bSavePackage );
/**
* Allows the commandlet to perform any additional operations on the package before it is resaved.
*
* @param Package the package that is currently being processed
* @param bSavePackage [in] indicates whether the package is currently going to be saved
* [out] set to true to resave the package
*/
virtual void PerformAdditionalOperations( class UPackage* Package, bool& bSavePackage );
/**
* Allows the commandlet to perform any additional operations on the world before it is resaved.
*
* @param World the world that is currently being processed
* @param bSavePackage [in] indicates whether the package is currently going to be saved
* [out] set to true to resave the package
*/
virtual void PerformAdditionalOperations(class UWorld* World, bool& bSavePackage);
/**
* Removes any UClass exports from packages which aren't script packages.
*
* @param Package the package that is currently being processed
*
* @return true to resave the package
*/
bool CleanClassesFromContentPackages( class UPackage* Package );
// Get the changelist description to use if automatically checking packages out
virtual FText GetChangelistDescription() const;
bool CheckoutFile(const FString& Filename, bool bAddFile = false, bool bIgnoreAlreadyCheckedOut = false);
bool RevertFile(const FString& Filename);
bool CanCheckoutFile(const FString& Filename, FString& CheckedOutUser);
// Print out a message only if running in very verbose mode
void VerboseMessage(const FString& Message);
public:
//~ Begin UCommandlet Interface
virtual int32 Main(const FString& Params) override;
//~ End UCommandlet Interface
};
| 412 | 0.887432 | 1 | 0.887432 | game-dev | MEDIA | 0.289221 | game-dev | 0.75573 | 1 | 0.75573 |
magefree/mage | 1,629 | Mage.Sets/src/mage/cards/k/KamiOfTerribleSecrets.java | package mage.cards.k;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.condition.common.ControlArtifactAndEnchantmentCondition;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.GainLifeEffect;
import mage.abilities.hint.common.ControlArtifactAndEnchantmentHint;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class KamiOfTerribleSecrets extends CardImpl {
public KamiOfTerribleSecrets(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{B}");
this.subtype.add(SubType.SPIRIT);
this.power = new MageInt(3);
this.toughness = new MageInt(4);
// When Kami of Terrible Secrets enters the battlefield, if you control an artifact and an enchantment, you draw a card and you gain 1 life.
Ability ability = new EntersBattlefieldTriggeredAbility(new DrawCardSourceControllerEffect(1, true))
.withInterveningIf(ControlArtifactAndEnchantmentCondition.instance);
ability.addEffect(new GainLifeEffect(1).concatBy("and"));
this.addAbility(ability.addHint(ControlArtifactAndEnchantmentHint.instance));
}
private KamiOfTerribleSecrets(final KamiOfTerribleSecrets card) {
super(card);
}
@Override
public KamiOfTerribleSecrets copy() {
return new KamiOfTerribleSecrets(this);
}
}
| 412 | 0.927715 | 1 | 0.927715 | game-dev | MEDIA | 0.95392 | game-dev | 0.991064 | 1 | 0.991064 |
qq2213216806/esp32-ai-chat | 13,007 | my_ai_chat_raw/managed_components/espressif__nghttp/nghttp2/third-party/mruby/mrbgems/mruby-data/src/data.c | /*
** data.c - Data class
**
** See Copyright Notice in mruby.h
*/
#include <string.h>
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/string.h>
#include <mruby/class.h>
#include <mruby/variable.h>
#include <mruby/hash.h>
#include <mruby/proc.h>
#include <mruby/internal.h>
#include <mruby/presym.h>
#define RDATA_LEN(st) RARRAY_LEN(st)
#define RDATA_PTR(st) RARRAY_PTR(st)
#define data_p(o) (mrb_type(o) == MRB_TT_STRUCT)
static struct RClass *
data_class(mrb_state *mrb)
{
return mrb_class_get_id(mrb, MRB_SYM(Data));
}
static void
data_corrupted(mrb_state *mrb)
{
mrb_raise(mrb, E_TYPE_ERROR, "corrupted data");
}
static mrb_value
data_s_members(mrb_state *mrb, struct RClass *c)
{
struct RClass* sclass = data_class(mrb);
mrb_value mem;
for (;;) {
mem = mrb_iv_get(mrb, mrb_obj_value(c), MRB_SYM(__members__));
if (!mrb_nil_p(mem)) {
if (!mrb_array_p(mem)) {
data_corrupted(mrb);
}
return mem;
}
c = c->super;
if (c == sclass || c == 0) {
mrb_raise(mrb, E_TYPE_ERROR, "uninitialized data");
}
}
}
static mrb_value
data_members(mrb_state *mrb, mrb_value obj)
{
if (!data_p(obj) || RDATA_LEN(obj) == 0) {
data_corrupted(mrb);
}
mrb_value members = data_s_members(mrb, mrb_obj_class(mrb, obj));
if (RDATA_LEN(obj) != RARRAY_LEN(members)) {
mrb_raisef(mrb, E_TYPE_ERROR,
"data size differs (%i required %i given)",
RARRAY_LEN(members), RDATA_LEN(obj));
}
return members;
}
static mrb_value
mrb_data_s_members(mrb_state *mrb, mrb_value klass)
{
mrb_value members = data_s_members(mrb, mrb_class_ptr(klass));
return mrb_ary_new_from_values(mrb, RARRAY_LEN(members), RARRAY_PTR(members));
}
/*
* call-seq:
* data.members -> array
*
* Returns an array of strings representing the names of the instance
* variables.
*
* Customer = Data.define(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* joe.members #=> [:name, :address, :zip]
*/
static mrb_value
mrb_data_members(mrb_state *mrb, mrb_value obj)
{
return mrb_data_s_members(mrb, mrb_obj_value(mrb_obj_class(mrb, obj)));
}
static mrb_value
mrb_data_ref(mrb_state *mrb, mrb_value obj)
{
mrb_int i = mrb_integer(mrb_proc_cfunc_env_get(mrb, 0));
mrb_value *ptr = RDATA_PTR(obj);
if (!ptr) return mrb_nil_value();
return ptr[i];
}
static void
make_data_define_accessors(mrb_state *mrb, mrb_value members, struct RClass *c)
{
const mrb_value *ptr_members = RARRAY_PTR(members);
mrb_int len = RARRAY_LEN(members);
int ai = mrb_gc_arena_save(mrb);
for (mrb_int i=0; i<len; i++) {
mrb_sym id = mrb_symbol(ptr_members[i]);
mrb_method_t m;
mrb_value at = mrb_fixnum_value(i);
struct RProc *aref = mrb_proc_new_cfunc_with_env(mrb, mrb_data_ref, 1, &at);
MRB_METHOD_FROM_PROC(m, aref);
mrb_define_method_raw(mrb, c, id, m);
mrb_gc_arena_restore(mrb, ai);
}
}
static mrb_value mrb_data_initialize(mrb_state *mrb, mrb_value self);
static mrb_value
mrb_data_new(mrb_state *mrb, mrb_value self)
{
struct RClass *c = mrb_class_ptr(self);
mrb_value members = data_s_members(mrb, c);
mrb_value *vals;
mrb_int n = RARRAY_LEN(members);
mrb_value *mems = RARRAY_PTR(members);
if (mrb->c->ci->nk > 0) {
mrb_value tmp = mrb_str_new(mrb, NULL, sizeof(mrb_sym)*n);
mrb_sym *knames = (mrb_sym*)RSTRING_PTR(tmp);
mrb_value m = mrb_ary_new_capa(mrb, n);
vals = RARRAY_PTR(m);
for (mrb_int i=0; i<n; i++) {
knames[i] = mrb_symbol(mems[i]);
}
const mrb_kwargs kw = {n, n, knames, vals, NULL};
mrb_get_args(mrb, ":", &kw);
}
else {
mrb_int argc;
mrb_get_args(mrb, "*!", &vals, &argc);
if (n != argc) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
}
}
struct RArray* p = MRB_OBJ_ALLOC(mrb, MRB_TT_STRUCT, c);
mrb_value data = mrb_obj_value(p);
if (!mrb_func_basic_p(mrb, data, MRB_SYM(initialize), mrb_data_initialize)) {
/* overridden initialize - create hash and call initialize explicitly */
mrb_value hash = mrb_hash_new_capa(mrb, n);
for (mrb_int i=0; i<n; i++) {
mrb_hash_set(mrb, hash, mems[i], vals[i]);
}
mrb_funcall_argv(mrb, data, MRB_SYM(initialize), 1, &hash);
}
else {
/* default initialize - skip calling initialize */
mrb_ary_resize(mrb, data, n);
for (mrb_int i = 0; i < n; i++) {
mrb_ary_set(mrb, data, i, vals[i]);
}
mrb_obj_freeze(mrb, data);
}
return data;
}
static mrb_value
make_data_class(mrb_state *mrb, mrb_value members, struct RClass *klass)
{
struct RClass *c = mrb_class_new(mrb, klass);
MRB_SET_INSTANCE_TT(c, MRB_TT_STRUCT);
mrb_value data = mrb_obj_value(c);
mrb_iv_set(mrb, data, MRB_SYM(__members__), members);
mrb_undef_class_method(mrb, c, "define");
mrb_define_class_method_id(mrb, c, MRB_SYM(new), mrb_data_new, MRB_ARGS_ANY());
mrb_define_class_method_id(mrb, c, MRB_SYM(members), mrb_data_s_members, MRB_ARGS_NONE());
/* RSTRUCT(data)->basic.c->super = c->c; */
make_data_define_accessors(mrb, members, c);
return data;
}
/*
* call-seq:
* DataClass.new(arg, ...) -> obj
*
* <code>Data::define</code> returns a new <code>Class</code> object,
* which can then be used to create specific instances of the new
* data structure. The number of actual parameters must be
* equal to the number of attributes defined for this class.
* Passing too many or too less parameters will raise an
* <code>ArgumentError</code>.
*
* The remaining methods listed in this section (class and instance)
* are defined for this generated class.
*
* # Create a structure named by its constant
* Customer = Data.define(:name, :address) #=> Customer
* Customer.new("Dave", "123 Main") #=> #<data name="Dave", address="123 Main">
*/
static mrb_value
mrb_data_s_def(mrb_state *mrb, mrb_value klass)
{
mrb_value rest;
mrb_value b, data;
mrb_sym id;
const mrb_value *argv;
mrb_int argc;
mrb_get_args(mrb, "*&", &argv, &argc, &b);
if (argc == 0) { /* special case to avoid crash */
mrb_argnum_error(mrb, argc, 1, -1);
}
else {
rest = mrb_ary_new_from_values(mrb, argc, argv);
for (mrb_int i=0; i<argc; i++) {
id = mrb_obj_to_sym(mrb, RARRAY_PTR(rest)[i]);
mrb_ary_set(mrb, rest, i, mrb_symbol_value(id));
}
data = make_data_class(mrb, rest, mrb_class_ptr(klass));
if (!mrb_nil_p(b)) {
mrb_yield_with_class(mrb, b, 1, &data, data, mrb_class_ptr(data));
}
return data;
}
/* not reached */
return mrb_nil_value();
}
static mrb_value
mrb_data_initialize(mrb_state *mrb, mrb_value self)
{
struct RClass *klass = mrb_obj_class(mrb, self);
mrb_value members = data_s_members(mrb, klass);
mrb_int n = RARRAY_LEN(members);
mrb_value hash;
mrb_get_args(mrb, "H", &hash);
if (mrb_hash_size(mrb, hash) != n) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
}
mrb_ary_resize(mrb, self, n);
mrb_value *mems = RARRAY_PTR(members);
for (mrb_int i = 0; i < n; i++) {
if (!mrb_hash_key_p(mrb, hash, mems[i])) {
mrb_raisef(mrb, E_ARGUMENT_ERROR, "undefined data member %v", mems[i]);
}
mrb_ary_set(mrb, self, i, mrb_hash_get(mrb, hash, mems[i]));
}
mrb_obj_freeze(mrb, self);
return self;
}
static mrb_value
mrb_data_init_copy(mrb_state *mrb, mrb_value copy)
{
mrb_value s = mrb_get_arg1(mrb);
if (mrb_obj_equal(mrb, copy, s)) return copy;
if (!mrb_obj_is_instance_of(mrb, s, mrb_obj_class(mrb, copy))) {
mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
}
if (!data_p(s)) {
data_corrupted(mrb);
}
mrb_ary_replace(mrb, copy, s);
mrb_obj_freeze(mrb, copy);
return copy;
}
/*
* call-seq:
* data == other_data -> true or false
*
* Equality---Returns <code>true</code> if <i>other_data</i> is
* equal to this one: they must be of the same class as generated by
* <code>Data::define</code>, and all values of must be equal
* (according to <code>Object#==</code>).
*
* Customer = Data.define(:name, :address, :zip)
* joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* joe2 = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
* jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
* joe == joe2 #=> true
* joe == jane #=> false
*/
static mrb_value
mrb_data_equal(mrb_state *mrb, mrb_value s)
{
mrb_value s2 = mrb_get_arg1(mrb);
mrb_value *ptr, *ptr2;
mrb_int len;
if (mrb_obj_equal(mrb, s, s2)) {
return mrb_true_value();
}
if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
return mrb_false_value();
}
if (RDATA_LEN(s) != RDATA_LEN(s2)) {
return mrb_false_value();
}
ptr = RDATA_PTR(s);
ptr2 = RDATA_PTR(s2);
len = RDATA_LEN(s);
for (mrb_int i=0; i<len; i++) {
if (!mrb_equal(mrb, ptr[i], ptr2[i])) {
return mrb_false_value();
}
}
return mrb_true_value();
}
/*
* call-seq:
* data.eql?(other) -> true or false
*
* Two structures are equal if they are the same object, or if all their
* fields are equal (using <code>Object#eql?</code>).
*/
static mrb_value
mrb_data_eql(mrb_state *mrb, mrb_value s)
{
mrb_value s2 = mrb_get_arg1(mrb);
mrb_value *ptr, *ptr2;
mrb_int len;
if (mrb_obj_equal(mrb, s, s2)) {
return mrb_true_value();
}
if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
return mrb_false_value();
}
if (RDATA_LEN(s) != RDATA_LEN(s2)) {
return mrb_false_value();
}
ptr = RDATA_PTR(s);
ptr2 = RDATA_PTR(s2);
len = RDATA_LEN(s);
for (mrb_int i=0; i<len; i++) {
if (!mrb_eql(mrb, ptr[i], ptr2[i])) {
return mrb_false_value();
}
}
return mrb_true_value();
}
/*
* call-seq:
* data.to_h -> hash
*
* Create a hash from member names and values.
*/
static mrb_value
mrb_data_to_h(mrb_state *mrb, mrb_value self)
{
mrb_value members, ret;
mrb_value *mems, *vals;
members = data_members(mrb, self);
mems = RARRAY_PTR(members);
vals = RDATA_PTR(self);
ret = mrb_hash_new_capa(mrb, RARRAY_LEN(members));
mrb_int len = RARRAY_LEN(members);
for (mrb_int i=0; i<len; i++) {
mrb_hash_set(mrb, ret, mems[i], vals[i]);
}
return ret;
}
/*
* call-seq:
* data.to_s -> string
* data.inspect -> string
*
* Returns a string representation of Data
*/
static mrb_value
mrb_data_to_s(mrb_state *mrb, mrb_value self)
{
mrb_value members, ret, cname;
mrb_value *mems, *vals;
mrb_int mlen;
members = data_members(mrb, self);
mlen = RARRAY_LEN(members);
mems = RARRAY_PTR(members);
vals = RDATA_PTR(self);
ret = mrb_str_new_lit(mrb, "#<data ");
int ai = mrb_gc_arena_save(mrb);
cname = mrb_class_path(mrb, mrb_class_real(mrb_class(mrb, self)));
if (!mrb_nil_p(cname)) {
mrb_str_cat_str(mrb, ret, cname);
mrb_str_cat_lit(mrb, ret, " ");
}
for (mrb_int i=0; i<mlen; i++) {
mrb_int len;
const char *name = mrb_sym_name_len(mrb, mrb_symbol(mems[i]), &len);
if (i>0) mrb_str_cat_lit(mrb, ret, ", ");
mrb_str_cat(mrb, ret, name, len);
mrb_str_cat_lit(mrb, ret, "=");
mrb_str_cat_str(mrb, ret, mrb_inspect(mrb, vals[i]));
mrb_gc_arena_restore(mrb, ai);
}
mrb_str_cat_lit(mrb, ret, ">");
return ret;
}
/*
* A <code>Data</code> is a convenient way to bundle a number of
* attributes together, using accessor methods, without having to write
* an explicit class.
*
* The <code>Data</code> class is a generator of specific classes,
* each one of which is defined to hold a set of variables and their
* accessors. In these examples, we'll call the generated class
* "<i>Customer</i>Class," and we'll show an example instance of that
* class as "<i>Customer</i>Inst."
*
* In the descriptions that follow, the parameter <i>symbol</i> refers
* to a symbol (such as <code>:name</code>).
*/
void
mrb_mruby_data_gem_init(mrb_state* mrb)
{
struct RClass *d;
d = mrb_define_class(mrb, "Data", mrb->object_class);
MRB_SET_INSTANCE_TT(d, MRB_TT_STRUCT);
mrb_undef_class_method(mrb, d, "new");
mrb_define_class_method(mrb, d, "define", mrb_data_s_def, MRB_ARGS_ANY());
mrb_define_method(mrb, d, "==", mrb_data_equal, MRB_ARGS_REQ(1));
mrb_define_method(mrb, d, "members", mrb_data_members, MRB_ARGS_NONE());
mrb_define_method(mrb, d, "initialize", mrb_data_initialize, MRB_ARGS_ANY());
mrb_define_method(mrb, d, "initialize_copy", mrb_data_init_copy, MRB_ARGS_ANY());
mrb_define_method(mrb, d, "eql?", mrb_data_eql, MRB_ARGS_REQ(1));
mrb_define_method(mrb, d, "to_h", mrb_data_to_h, MRB_ARGS_NONE());
mrb_define_method(mrb, d, "to_s", mrb_data_to_s, MRB_ARGS_NONE());
mrb_define_method(mrb, d, "inspect", mrb_data_to_s, MRB_ARGS_NONE());
}
void
mrb_mruby_data_gem_final(mrb_state* mrb)
{
}
| 412 | 0.765114 | 1 | 0.765114 | game-dev | MEDIA | 0.296159 | game-dev | 0.754632 | 1 | 0.754632 |
micdoodle8/Galacticraft | 11,361 | src/main/java/micdoodle8/mods/galacticraft/core/inventory/ContainerCircuitFabricator.java | package micdoodle8.mods.galacticraft.core.inventory;
import micdoodle8.mods.galacticraft.api.item.IItemElectric;
import micdoodle8.mods.galacticraft.api.recipe.CircuitFabricatorRecipes;
import micdoodle8.mods.galacticraft.core.energy.EnergyUtil;
import micdoodle8.mods.galacticraft.core.tile.TileEntityCircuitFabricator;
import micdoodle8.mods.galacticraft.core.util.GCLog;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotFurnaceOutput;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ContainerCircuitFabricator extends Container
{
private TileEntityCircuitFabricator tileEntity;
public ContainerCircuitFabricator(InventoryPlayer playerInv, TileEntityCircuitFabricator tileEntity)
{
this.tileEntity = tileEntity;
// Energy slot
this.addSlotToContainer(new SlotSpecific(tileEntity, 0, 6, 69, IItemElectric.class));
// Diamond
ArrayList<ItemStack> slotContentsList = CircuitFabricatorRecipes.slotValidItems.get(0);
this.addSlotToContainer(new SlotSpecific(tileEntity, 1, 15, 17, slotContentsList.toArray(new ItemStack[slotContentsList.size()])));
// Silicon
slotContentsList = CircuitFabricatorRecipes.slotValidItems.get(1);
this.addSlotToContainer(new SlotSpecific(tileEntity, 2, 74, 46, slotContentsList.toArray(new ItemStack[slotContentsList.size()])));
slotContentsList = CircuitFabricatorRecipes.slotValidItems.get(2);
this.addSlotToContainer(new SlotSpecific(tileEntity, 3, 74, 64, slotContentsList.toArray(new ItemStack[slotContentsList.size()])));
// Redstone
slotContentsList = CircuitFabricatorRecipes.slotValidItems.get(3);
this.addSlotToContainer(new SlotSpecific(tileEntity, 4, 122, 46, slotContentsList.toArray(new ItemStack[slotContentsList.size()])));
// Optional
slotContentsList = CircuitFabricatorRecipes.slotValidItems.get(4);
this.addSlotToContainer(new SlotSpecific(tileEntity, 5, 145, 20, slotContentsList.toArray(new ItemStack[slotContentsList.size()])));
// Smelting result
this.addSlotToContainer(new SlotFurnaceOutput(playerInv.player, tileEntity, 6, 152, 86));
int slot;
for (slot = 0; slot < 3; ++slot)
{
for (int var4 = 0; var4 < 9; ++var4)
{
this.addSlotToContainer(new Slot(playerInv, var4 + slot * 9 + 9, 8 + var4 * 18, 110 + slot * 18));
}
}
for (slot = 0; slot < 9; ++slot)
{
this.addSlotToContainer(new Slot(playerInv, slot, 8 + slot * 18, 168));
}
}
@Override
public boolean canInteractWith(EntityPlayer par1EntityPlayer)
{
return this.tileEntity.isUsableByPlayer(par1EntityPlayer);
}
@Override
public void onCraftMatrixChanged(IInventory par1IInventory)
{
super.onCraftMatrixChanged(par1IInventory);
}
/**
* Called to transfer a stack from one inventory to the other eg. when shift
* clicking.
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par1)
{
ItemStack var2 = ItemStack.EMPTY;
Slot slot = this.inventorySlots.get(par1);
final int b = this.inventorySlots.size();
if (slot != null && slot.getHasStack())
{
ItemStack var4 = slot.getStack();
var2 = var4.copy();
if (par1 < b - 36)
{
if (!this.mergeItemStack(var4, b - 36, b, true))
{
return ItemStack.EMPTY;
}
if (par1 == 6)
{
slot.onSlotChange(var4, var2);
}
}
else
{
Item i = var4.getItem();
if (EnergyUtil.isElectricItem(i))
{
if (!this.mergeItemStack(var4, 0, 1, false))
{
return ItemStack.EMPTY;
}
}
else if (i == Items.DIAMOND)
{
if (!this.mergeItemStack(var4, 1, 2, false))
{
return ItemStack.EMPTY;
}
}
else if (this.isSilicon(var4))
{
if (!this.mergeEven(var4, 2, 4))
{
return ItemStack.EMPTY;
}
}
else if (i == Items.REDSTONE)
{
if (!this.mergeItemStack(var4, 4, 5, false))
{
return ItemStack.EMPTY;
}
}
else if (i == Items.REPEATER || i == new ItemStack(Blocks.REDSTONE_TORCH).getItem() || i == Items.DYE && i.getDamage(var4) == 4)
{
if (!this.mergeItemStack(var4, 5, 6, false))
{
return ItemStack.EMPTY;
}
}
else if (par1 < b - 9)
{
if (!this.mergeItemStack(var4, b - 9, b, false))
{
return ItemStack.EMPTY;
}
}
else if (!this.mergeItemStack(var4, b - 36, b - 9, false))
{
return ItemStack.EMPTY;
}
}
if (var4.getCount() == 0)
{
slot.putStack(ItemStack.EMPTY);
}
else
{
slot.onSlotChanged();
}
if (var4.getCount() == var2.getCount())
{
return ItemStack.EMPTY;
}
slot.onTake(par1EntityPlayer, var4);
}
return var2;
}
private boolean mergeEven(ItemStack stack, int a, int b)
{
List<Slot> acceptSlots = new LinkedList<>();
List<Integer> acceptQuantity = new LinkedList<>();
int minQuantity = 64;
int acceptTotal = 0;
for (int i = a; i < b; i++)
{
Slot slot = (Slot)this.inventorySlots.get(i);
if (slot != null)
{
ItemStack target = slot.getStack();
if (matchingStacks(stack, target))
{
acceptSlots.add(slot);
int availSpace = stack.getMaxStackSize() - target.getCount();
acceptQuantity.add(availSpace);
acceptTotal += availSpace;
if (availSpace < minQuantity) minQuantity = availSpace;
}
}
}
for (Slot slot : acceptSlots)
{
ItemStack target = slot.getStack();
if (target.isEmpty())
{
target = stack.copy();
target.setCount(1);
slot.putStack(target);
stack.shrink(1);
if (stack.isEmpty())
{
return false;
}
}
}
//The stack more than exceeds what the crafting inventory requires
if (stack.getCount() >= acceptTotal)
{
if (acceptTotal == 0)
return false;
for (Slot slot : acceptSlots)
{
ItemStack target = slot.getStack();
stack.shrink(target.getMaxStackSize() - target.getCount());
target.setCount(target.getMaxStackSize());
slot.onSlotChanged();
}
return true;
}
int uneven = 0;
for (int q : acceptQuantity)
{
uneven += q - minQuantity;
}
//Use the whole stack to try to even up the neediest slots
if (stack.getCount() <= uneven)
{
do
{
Slot neediest = null;
int smallestStack = 64;
for (Slot slot : acceptSlots)
{
ItemStack target = slot.getStack();
if (target.getCount() < smallestStack)
{
smallestStack = target.getCount();
neediest = slot;
}
}
neediest.getStack().grow(1);
stack.shrink(1);
}
while (!stack.isEmpty());
for (Slot slot : acceptSlots)
{
slot.onSlotChanged();
}
return true;
}
//Use some of the stack to even things up
if (uneven > 0)
{
int targetSize = stack.getMaxStackSize() - minQuantity;
for (Slot slot : acceptSlots)
{
ItemStack target = slot.getStack();
stack.shrink(targetSize - target.getCount());
acceptTotal -= targetSize - target.getCount();
target.setCount(targetSize);
slot.onSlotChanged();
}
}
//Spread the remaining stack over all slots evenly
int average = stack.getCount() / acceptSlots.size();
int modulus = stack.getCount() - average * acceptSlots.size();
for (Slot slot : acceptSlots)
{
if (slot != null)
{
ItemStack target = slot.getStack();
int transfer = average;
if (modulus > 0)
{
transfer++;
modulus--;
}
if (transfer > stack.getCount()) transfer = stack.getCount();
stack.shrink(transfer);
target.grow(transfer);
if (target.getCount() > target.getMaxStackSize())
{
GCLog.info("Shift clicking - slot " + slot.slotNumber + " wanted more than it could accept:" + target.getCount());
stack.grow(target.getCount() - target.getMaxStackSize());
target.setCount(target.getMaxStackSize());
}
slot.onSlotChanged();
if (stack.isEmpty())
break;
}
}
return true;
}
private boolean isSilicon(ItemStack test)
{
for (ItemStack stack : CircuitFabricatorRecipes.slotValidItems.get(1))
{
if (stack.isItemEqual(test)) return true;
}
return false;
}
private boolean matchingStacks(ItemStack stack, ItemStack target)
{
return target.isEmpty() || target.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getMetadata() == target.getMetadata()) && ItemStack.areItemStackTagsEqual(stack, target) && (target.isStackable() && target.getCount() < target.getMaxStackSize());
}
}
| 412 | 0.930382 | 1 | 0.930382 | game-dev | MEDIA | 0.98528 | game-dev | 0.968263 | 1 | 0.968263 |
Team-Immersive-Intelligence/ImmersiveIntelligence | 4,135 | src/main/java/pl/pabilo8/immersiveintelligence/common/block/metal_device/BlockIIMetalDevice1.java | package pl.pabilo8.immersiveintelligence.common.block.metal_device;
import blusunrize.immersiveengineering.api.IEProperties;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import pl.pabilo8.immersiveintelligence.common.block.metal_device.BlockIIMetalDevice1.IIBlockTypes_MetalDevice1;
import pl.pabilo8.immersiveintelligence.common.block.metal_device.tileentity.TileEntityCO2Filter;
import pl.pabilo8.immersiveintelligence.common.util.IIReference;
import pl.pabilo8.immersiveintelligence.common.util.block.BlockIITileProvider;
import pl.pabilo8.immersiveintelligence.common.util.block.IIBlockInterfaces.EnumTileProvider;
import pl.pabilo8.immersiveintelligence.common.util.block.IIBlockInterfaces.IIBlockProperties;
import pl.pabilo8.immersiveintelligence.common.util.block.IIBlockInterfaces.IITileProviderEnum;
import pl.pabilo8.immersiveintelligence.common.util.block.IIBlockInterfaces.TernaryValue;
import pl.pabilo8.immersiveintelligence.common.util.block.ItemBlockIIBase;
import pl.pabilo8.immersiveintelligence.common.util.item.IICategory;
/**
* @author Pabilo8 (pabilo@iiteam.net)
* @since 24.05.2021
*/
public class BlockIIMetalDevice1 extends BlockIITileProvider<IIBlockTypes_MetalDevice1>
{
public BlockIIMetalDevice1()
{
super("metal_device1", Material.IRON, PropertyEnum.create("type", IIBlockTypes_MetalDevice1.class), ItemBlockIIBase::new,
IEProperties.FACING_ALL, IEProperties.MULTIBLOCKSLAVE, IEProperties.BOOLEANS[0]);
setHardness(3.0F);
setResistance(15.0F);
setLightOpacity(0);
setToolTypes(IIReference.TOOL_HAMMER);
setBlockLayer(BlockRenderLayer.CUTOUT_MIPPED);
this.setMetaMobilityFlag(IIBlockTypes_MetalDevice1.CO2_FILTER, EnumPushReaction.BLOCK);
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos)
{
IBlockState actualState = super.getActualState(state, world, pos);
TileEntity tile = world.getTileEntity(pos);
if(tile instanceof TileEntityCO2Filter)
actualState = actualState.withProperty(IEProperties.BOOLEANS[0], ((TileEntityCO2Filter)tile).subBlockID==1);
if(tile instanceof TileEntityCO2Filter)
actualState = actualState.withProperty(IEProperties.MULTIBLOCKSLAVE, ((TileEntityCO2Filter)tile).isDummy());
return actualState;
}
@Override
public boolean canIEBlockBePlaced(World world, BlockPos pos, IBlockState newState, EnumFacing side, float hitX, float hitY, float hitZ, EntityPlayer player, ItemStack stack)
{
if(stack.getItemDamage()==IIBlockTypes_MetalDevice1.CO2_FILTER.getMeta())
{
for(int hh = 1; hh <= 2; hh++)
{
BlockPos pos2 = pos.add(0, hh, 0);
if(world.isOutsideBuildHeight(pos2)||!world.getBlockState(pos2).getBlock().isReplaceable(world, pos2))
return false;
}
}
return true;
}
public enum IIBlockTypes_MetalDevice1 implements IITileProviderEnum
{
@EnumTileProvider(tile = TileEntityCO2Filter.class)
@IIBlockProperties(needsCustomState = true, renderLayer = BlockRenderLayer.CUTOUT, category = IICategory.TOOLS)
CO2_FILTER,
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.ELECTRONICS)
NEWSPAPER_STAND,
//Scheduled for 0.4.0
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.LOGISTICS)
VENDING_MACHINE,
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.ELECTRONICS)
TYPEWRITER_TABLE,
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.LOGISTICS)
CASHIER_TABLE,
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.ELECTRONICS)
PLANNING_TABLE,
@IIBlockProperties(hidden = TernaryValue.TRUE, category = IICategory.ELECTRONICS)
REMOTE_CONTROL_TABLE,
}
}
| 412 | 0.836191 | 1 | 0.836191 | game-dev | MEDIA | 0.997104 | game-dev | 0.896451 | 1 | 0.896451 |
MehVahdJukaar/Moonlight | 2,505 | common/src/main/java/net/mehvahdjukaar/moonlight/core/misc/AntiRepostWarning.java | package net.mehvahdjukaar.moonlight.core.misc;
import net.mehvahdjukaar.moonlight.api.platform.PlatHelper;
import net.mehvahdjukaar.moonlight.core.Moonlight;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextColor;
import net.minecraft.world.entity.player.Player;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public class AntiRepostWarning {
private static final Set<String> MODS = new HashSet<>();
public static void addMod(String id) {
if (!Objects.equals(id, "minecraft")) {
MODS.add(id);
}
}
public static void run() {
if (PlatHelper.isDev()) return;
Player player = Minecraft.getInstance().player;
if (player == null) return;
Set<String> reposted = MODS.stream().filter(AntiRepostWarning::isFileNameSus).collect(Collectors.toSet());
try {
for (var m : reposted) {
String url = PlatHelper.getModPageUrl(m);
if (url == null) url ="https://curseforge.com/minecraft/mc-mods";
MutableComponent link = Component.translatable("message.moonlight.anti_repost_link");
String modName = PlatHelper.getModName(m);
MutableComponent name = Component.literal(modName).withStyle(ChatFormatting.BOLD);
ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
link.setStyle(link.getStyle().withClickEvent(click).withUnderlined(true)
.withColor(TextColor.fromLegacyFormat(ChatFormatting.GOLD)));
player.displayClientMessage(Component.translatable("message.moonlight.anti_repost", name, link), false);
}
} catch (Exception ignored) {
}
}
private static boolean isFileNameSus(String mod) {
var path = PlatHelper.getModFilePath(mod);
if (path == null || path.getFileName() == null) {
Moonlight.LOGGER.warn("Failed to get file path of mod {}: {}", mod, path);
} else {
String fileName = path.getFileName().toString();
if (fileName.contains(".jar")) {
return fileName.contains("-Mod-") || fileName.endsWith("-tw");
}
}
return false;
}
}
| 412 | 0.834351 | 1 | 0.834351 | game-dev | MEDIA | 0.960251 | game-dev | 0.89024 | 1 | 0.89024 |
iRevolutionDev/roblox-modloader | 21,433 | include/RobloxModLoader/roblox/bullet_physics/LinearMath/btScalar.h | /*
Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SCALAR_H
#define BT_SCALAR_H
#ifdef BT_MANAGED_CODE
//Aligned data types not supported in managed code
#pragma unmanaged
#endif
#include <math.h>
#include <stdlib.h>//size_t for MSVC 6.0
#include <float.h>
/* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
#define BT_BULLET_VERSION 282
inline int btGetVersion()
{
return BT_BULLET_VERSION;
}
#if defined(DEBUG) || defined (_DEBUG)
#define BT_DEBUG
#endif
#ifdef _WIN32
#if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300)
#define SIMD_FORCE_INLINE inline
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED64(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#else
//#define BT_HAS_ALIGNED_ALLOCATOR
#pragma warning(disable : 4324) // disable padding warning
// #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning.
// #pragma warning(disable:4996) //Turn off warnings about deprecated C routines
// #pragma warning(disable:4786) // Disable the "debug name too long" warning
#define SIMD_FORCE_INLINE __forceinline
#define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a
#define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a
#define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a
#ifdef _XBOX
#define BT_USE_VMX128
#include <ppcintrinsics.h>
#define BT_HAVE_NATIVE_FSEL
#define btFsel(a,b,c) __fsel((a),(b),(c))
#else
#if (defined (_WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined (BT_USE_DOUBLE_PRECISION))
#if _MSC_VER>1400
#define BT_USE_SIMD_VECTOR3
#endif
#define BT_USE_SSE
#ifdef BT_USE_SSE
//BT_USE_SSE_IN_API is disabled under Windows by default, because
//it makes it harder to integrate Bullet into your application under Windows
//(structured embedding Bullet structs/classes need to be 16-byte aligned)
//with relatively little performance gain
//If you are not embedded Bullet data in your classes, or make sure that you align those classes on 16-byte boundaries
//you can manually enable this line or set it in the build system for a bit of performance gain (a few percent, dependent on usage)
//#define BT_USE_SSE_IN_API
#endif //BT_USE_SSE
#include <emmintrin.h>
#endif
#endif//_XBOX
#endif //__MINGW32__
#ifdef BT_DEBUG
#ifdef _MSC_VER
#include <stdio.h>
#define btAssert(x) { if(!(x)){printf("Assert "__FILE__ ":%u ("#x")\n", __LINE__);__debugbreak(); }}
#else//_MSC_VER
#include <assert.h>
#define btAssert assert
#endif//_MSC_VER
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#if defined (__CELLOS_LV2__)
#define SIMD_FORCE_INLINE inline __attribute__((always_inline))
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#ifdef __SPU__
#include <spu_printf.h>
#define printf spu_printf
#define btAssert(x) {if(!(x)){printf("Assert "__FILE__ ":%u ("#x")\n", __LINE__);spu_hcmpeq(0,0);}}
#else
#define btAssert assert
#endif
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#ifdef USE_LIBSPE2
#define SIMD_FORCE_INLINE __inline
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) __builtin_expect((_c), 1)
#define btUnlikely(_c) __builtin_expect((_c), 0)
#else
//non-windows systems
#if (defined (__APPLE__) && (!defined (BT_USE_DOUBLE_PRECISION)))
#if defined (__i386__) || defined (__x86_64__)
#define BT_USE_SIMD_VECTOR3
#define BT_USE_SSE
//BT_USE_SSE_IN_API is enabled on Mac OSX by default, because memory is automatically aligned on 16-byte boundaries
//if apps run into issues, we will disable the next line
#define BT_USE_SSE_IN_API
#ifdef BT_USE_SSE
// include appropriate SSE level
#if defined (__SSE4_1__)
#include <smmintrin.h>
#elif defined (__SSSE3__)
#include <tmmintrin.h>
#elif defined (__SSE3__)
#include <pmmintrin.h>
#else
#include <emmintrin.h>
#endif
#endif //BT_USE_SSE
#elif defined( __ARM_NEON__ )
#ifdef __clang__
#define BT_USE_NEON 1
#define BT_USE_SIMD_VECTOR3
#if defined BT_USE_NEON && defined (__clang__)
#include <arm_neon.h>
#endif//BT_USE_NEON
#endif //__clang__
#endif//__arm__
#define SIMD_FORCE_INLINE inline __attribute__ ((always_inline))
///@todo: check out alignment methods for other platforms/compilers
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined (_DEBUG)
#if defined (__i386__) || defined (__x86_64__)
#include <stdio.h>
#define btAssert(x)\
{\
if(!(x))\
{\
printf("Assert %s in line %d, file %s\n",#x, __LINE__, __FILE__);\
asm volatile ("int3");\
}\
}
#else//defined (__i386__) || defined (__x86_64__)
#define btAssert assert
#endif//defined (__i386__) || defined (__x86_64__)
#else//defined(DEBUG) || defined (_DEBUG)
#define btAssert(x)
#endif//defined(DEBUG) || defined (_DEBUG)
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#define SIMD_FORCE_INLINE inline
///@todo: check out alignment methods for other platforms/compilers
///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED64(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined (_DEBUG)
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#endif //__APPLE__
#endif // LIBSPE2
#endif //__CELLOS_LV2__
#endif
///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
#if defined(BT_USE_DOUBLE_PRECISION)
typedef double btScalar;
//this number could be bigger in double precision
#define BT_LARGE_FLOAT 1e30
#else
typedef float btScalar;
//keep BT_LARGE_FLOAT*BT_LARGE_FLOAT < FLT_MAX
#define BT_LARGE_FLOAT 1e18f
#endif
#ifdef BT_USE_SSE
typedef __m128 btSimdFloat4;
#endif//BT_USE_SSE
#if defined (BT_USE_SSE)
//#if defined BT_USE_SSE_IN_API && defined (BT_USE_SSE)
#ifdef _WIN32
#ifndef BT_NAN
static int btNanMask = 0x7F800001;
#define BT_NAN (*(float*)&btNanMask)
#endif
#ifndef BT_INFINITY
static int btInfinityMask = 0x7F800000;
#define BT_INFINITY (*(float*)&btInfinityMask)
#endif
//use this, in case there are clashes (such as xnamath.h)
#ifndef BT_NO_SIMD_OPERATOR_OVERLOADS
inline __m128 operator + (const __m128 A, const __m128 B)
{
return _mm_add_ps(A, B);
}
inline __m128 operator - (const __m128 A, const __m128 B)
{
return _mm_sub_ps(A, B);
}
inline __m128 operator * (const __m128 A, const __m128 B)
{
return _mm_mul_ps(A, B);
}
#endif //BT_NO_SIMD_OPERATOR_OVERLOADS
#define btCastfTo128i(a) (_mm_castps_si128(a))
#define btCastfTo128d(a) (_mm_castps_pd(a))
#define btCastiTo128f(a) (_mm_castsi128_ps(a))
#define btCastdTo128f(a) (_mm_castpd_ps(a))
#define btCastdTo128i(a) (_mm_castpd_si128(a))
#define btAssign128(r0,r1,r2,r3) _mm_setr_ps(r0,r1,r2,r3)
#else//_WIN32
#define btCastfTo128i(a) ((__m128i)(a))
#define btCastfTo128d(a) ((__m128d)(a))
#define btCastiTo128f(a) ((__m128) (a))
#define btCastdTo128f(a) ((__m128) (a))
#define btCastdTo128i(a) ((__m128i)(a))
#define btAssign128(r0,r1,r2,r3) (__m128){r0,r1,r2,r3}
#define BT_INFINITY INFINITY
#define BT_NAN NAN
#endif//_WIN32
#else
#ifdef BT_USE_NEON
#include <arm_neon.h>
typedef float32x4_t btSimdFloat4;
#define BT_INFINITY INFINITY
#define BT_NAN NAN
#define btAssign128(r0,r1,r2,r3) (float32x4_t){r0,r1,r2,r3}
#else//BT_USE_NEON
#ifndef BT_INFINITY
static int btInfinityMask = 0x7F800000;
#define BT_INFINITY (*(float*)&btInfinityMask)
#endif
#endif//BT_USE_NEON
#endif //BT_USE_SSE
#ifdef BT_USE_NEON
#include <arm_neon.h>
typedef float32x4_t btSimdFloat4;
#define BT_INFINITY INFINITY
#define BT_NAN NAN
#define btAssign128(r0,r1,r2,r3) (float32x4_t){r0,r1,r2,r3}
#endif
#define BT_DECLARE_ALIGNED_ALLOCATOR() \
SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes,16); } \
SIMD_FORCE_INLINE void operator delete(void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete(void*, void*) { } \
SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes,16); } \
SIMD_FORCE_INLINE void operator delete[](void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete[](void*, void*) { } \
#if defined(BT_USE_DOUBLE_PRECISION) || defined(BT_FORCE_DOUBLE_FUNCTIONS)
SIMD_FORCE_INLINE btScalar btSqrt(btScalar x) { return sqrt(x); }
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabs(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cos(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sin(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tan(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { if (x<btScalar(-1)) x=btScalar(-1); if (x>btScalar(1)) x=btScalar(1); return acos(x); }
SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { if (x<btScalar(-1)) x=btScalar(-1); if (x>btScalar(1)) x=btScalar(1); return asin(x); }
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atan(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return exp(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return log(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return pow(x,y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmod(x,y); }
#else
SIMD_FORCE_INLINE btScalar btSqrt(btScalar y)
{
#ifdef USE_APPROXIMATION
double x, z, tempf;
unsigned long *tfptr = ((unsigned long *)&tempf) + 1;
tempf = y;
*tfptr = (0xbfcdd90a - *tfptr)>>1; /* estimate of 1/sqrt(y) */
x = tempf;
z = y*btScalar(0.5);
x = (btScalar(1.5)*x)-(x*x)*(x*z); /* iteration formula */
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
return x*y;
#else
return sqrtf(y);
#endif
}
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabsf(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x) {
if (x<btScalar(-1))
x=btScalar(-1);
if (x>btScalar(1))
x=btScalar(1);
return acosf(x);
}
SIMD_FORCE_INLINE btScalar btAsin(btScalar x) {
if (x<btScalar(-1))
x=btScalar(-1);
if (x>btScalar(1))
x=btScalar(1);
return asinf(x);
}
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return expf(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return logf(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return powf(x,y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmodf(x,y); }
#endif
#define SIMD_PI btScalar(3.1415926535897932384626433832795029)
#define SIMD_2_PI btScalar(2.0) * SIMD_PI
#define SIMD_HALF_PI (SIMD_PI * btScalar(0.5))
#define SIMD_RADS_PER_DEG (SIMD_2_PI / btScalar(360.0))
#define SIMD_DEGS_PER_RAD (btScalar(360.0) / SIMD_2_PI)
#define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
#define btRecipSqrt(x) ((btScalar)(btScalar(1.0)/btSqrt(btScalar(x)))) /* reciprocal square root */
#define btRecip(x) (btScalar(1.0)/btScalar(x))
#ifdef BT_USE_DOUBLE_PRECISION
#define SIMD_EPSILON DBL_EPSILON
#define SIMD_INFINITY DBL_MAX
#else
#define SIMD_EPSILON FLT_EPSILON
#define SIMD_INFINITY FLT_MAX
#endif
SIMD_FORCE_INLINE btScalar btAtan2Fast(btScalar y, btScalar x)
{
btScalar coeff_1 = SIMD_PI / 4.0f;
btScalar coeff_2 = 3.0f * coeff_1;
btScalar abs_y = btFabs(y);
btScalar angle;
if (x >= 0.0f) {
btScalar r = (x - abs_y) / (x + abs_y);
angle = coeff_1 - coeff_1 * r;
} else {
btScalar r = (x + abs_y) / (abs_y - x);
angle = coeff_2 - coeff_1 * r;
}
return (y < 0.0f) ? -angle : angle;
}
SIMD_FORCE_INLINE bool btFuzzyZero(btScalar x) { return btFabs(x) < SIMD_EPSILON; }
SIMD_FORCE_INLINE bool btEqual(btScalar a, btScalar eps) {
return (((a) <= eps) && !((a) < -eps));
}
SIMD_FORCE_INLINE bool btGreaterEqual (btScalar a, btScalar eps) {
return (!((a) <= eps));
}
SIMD_FORCE_INLINE int btIsNegative(btScalar x) {
return x < btScalar(0.0) ? 1 : 0;
}
SIMD_FORCE_INLINE btScalar btRadians(btScalar x) { return x * SIMD_RADS_PER_DEG; }
SIMD_FORCE_INLINE btScalar btDegrees(btScalar x) { return x * SIMD_DEGS_PER_RAD; }
#define BT_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name
#ifndef btFsel
SIMD_FORCE_INLINE btScalar btFsel(btScalar a, btScalar b, btScalar c)
{
return a >= 0 ? b : c;
}
#endif
#define btFsels(a,b,c) (btScalar)btFsel(a,b,c)
SIMD_FORCE_INLINE bool btMachineIsLittleEndian()
{
long int i = 1;
const char *p = (const char *) &i;
if (p[0] == 1) // Lowest address contains the least significant byte
return true;
else
return false;
}
///btSelect avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360
///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html
SIMD_FORCE_INLINE unsigned btSelect(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero)
{
// Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero
// Rely on positive value or'ed with its negative having sign bit on
// and zero value or'ed with its negative (which is still zero) having sign bit off
// Use arithmetic shift right, shifting the sign bit through all 32 bits
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE int btSelect(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero)
{
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return static_cast<int>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE float btSelect(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero)
{
#ifdef BT_HAVE_NATIVE_FSEL
return (float)btFsel((btScalar)condition - btScalar(1.0f), valueIfConditionNonZero, valueIfConditionZero);
#else
return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero;
#endif
}
template<typename T> SIMD_FORCE_INLINE void btSwap(T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
//PCK: endian swapping functions
SIMD_FORCE_INLINE unsigned btSwapEndian(unsigned val)
{
return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24));
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(unsigned short val)
{
return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8));
}
SIMD_FORCE_INLINE unsigned btSwapEndian(int val)
{
return btSwapEndian((unsigned)val);
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(short val)
{
return btSwapEndian((unsigned short) val);
}
///btSwapFloat uses using char pointers to swap the endianness
////btSwapFloat/btSwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values
///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754.
///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception.
///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you.
///so instead of returning a float/double, we return integer/long long integer
SIMD_FORCE_INLINE unsigned int btSwapEndianFloat(float d)
{
unsigned int a = 0;
unsigned char *dst = (unsigned char *)&a;
unsigned char *src = (unsigned char *)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return a;
}
// unswap using char pointers
SIMD_FORCE_INLINE float btUnswapEndianFloat(unsigned int a)
{
float d = 0.0f;
unsigned char *src = (unsigned char *)&a;
unsigned char *dst = (unsigned char *)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return d;
}
// swap using char pointers
SIMD_FORCE_INLINE void btSwapEndianDouble(double d, unsigned char* dst)
{
unsigned char *src = (unsigned char *)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
// unswap using char pointers
SIMD_FORCE_INLINE double btUnswapEndianDouble(const unsigned char *src)
{
double d = 0.0;
unsigned char *dst = (unsigned char *)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
return d;
}
template<typename T>
SIMD_FORCE_INLINE void btSetZero(T* a, int n)
{
T* acurr = a;
size_t ncurr = n;
while (ncurr > 0)
{
*(acurr++) = 0;
--ncurr;
}
}
SIMD_FORCE_INLINE btScalar btLargeDot(const btScalar *a, const btScalar *b, int n)
{
btScalar p0,q0,m0,p1,q1,m1,sum;
sum = 0;
n -= 2;
while (n >= 0) {
p0 = a[0]; q0 = b[0];
m0 = p0 * q0;
p1 = a[1]; q1 = b[1];
m1 = p1 * q1;
sum += m0;
sum += m1;
a += 2;
b += 2;
n -= 2;
}
n += 2;
while (n > 0) {
sum += (*a) * (*b);
a++;
b++;
n--;
}
return sum;
}
// returns normalized value in range [-SIMD_PI, SIMD_PI]
SIMD_FORCE_INLINE btScalar btNormalizeAngle(btScalar angleInRadians)
{
angleInRadians = btFmod(angleInRadians, SIMD_2_PI);
if(angleInRadians < -SIMD_PI)
{
return angleInRadians + SIMD_2_PI;
}
else if(angleInRadians > SIMD_PI)
{
return angleInRadians - SIMD_2_PI;
}
else
{
return angleInRadians;
}
}
///rudimentary class to provide type info
struct btTypedObject
{
btTypedObject(int objectType)
:m_objectType(objectType)
{
}
int m_objectType;
inline int getObjectType() const
{
return m_objectType;
}
};
///align a pointer to the provided alignment, upwards
template <typename T>T* btAlignPointer(T* unalignedPtr, size_t alignment)
{
struct btConvertPointerSizeT
{
union
{
T* ptr;
size_t integer;
};
};
btConvertPointerSizeT converter;
const size_t bit_mask = ~(alignment - 1);
converter.ptr = unalignedPtr;
converter.integer += alignment-1;
converter.integer &= bit_mask;
return converter.ptr;
}
#endif //BT_SCALAR_H
| 412 | 0.934771 | 1 | 0.934771 | game-dev | MEDIA | 0.282813 | game-dev | 0.533636 | 1 | 0.533636 |
SebLague/Tiny-Chess-Bot-Challenge-Results | 10,243 | Bots/Bot_157.cs | namespace auto_Bot_157;
// https://github.com/p-rivero/Turochamp-Chess-Challenge/blob/main/Chess-Challenge/src/My%20Bot/MyBot.cs
using ChessChallenge.API;
using System;
using System.Collections.Generic;
using System.Linq;
public class Bot_157 : IChessBot
{
private const PieceType
PAWN = PieceType.Pawn,
KNIGHT = PieceType.Knight,
BISHOP = PieceType.Bishop,
ROOK = PieceType.Rook,
QUEEN = PieceType.Queen;
private Board board;
private Move bestMoveUnconfirmed, bestMoveConfirmed;
private int bestScore, startDepth, timeToThink;
private Timer timer;
private int[,,] historyHeuristic;
public Move Think(Board boardIn, Timer timerIn)
{
board = boardIn;
timer = timerIn;
// With more than 20 seconds left, think for 1 second (~40 moves)
// Between 20 and 4 seconds, think for 0.5 seconds (~32 moves)
// For the last 4 seconds, think for 0.1 seconds (~40 moves)
timeToThink = timer.MillisecondsRemaining > 20_000 ? 1000 :
timer.MillisecondsRemaining > 4_000 ? 500 : 100;
try
{
for (startDepth = 1; ; startDepth++)
{
bestScore = -999_999;
historyHeuristic = new int[2, 64, 64];
int score = AlphaBetaSearch(startDepth, -999_999, 999_999);
bestMoveConfirmed = bestMoveUnconfirmed;
// Stop searching when checkmate is found
if (score > 90_000)
return bestMoveConfirmed;
}
}
catch (Exception)
{
// Timeout, return the previous best move
}
return bestMoveConfirmed;
}
private int AlphaBetaSearch(int depth, int alpha, int beta)
{
if (depth == 0)
return QuiescenceSearch(alpha, beta);
if (board.IsInCheckmate())
return startDepth - depth - 100_000;
if (board.IsDraw())
return 0;
// Check timeout
if (depth == 3 && timer.MillisecondsElapsedThisTurn > timeToThink)
throw new Exception();
foreach (Move move in OrderMoves(board.GetLegalMoves()))
{
board.MakeMove(move);
int score = -AlphaBetaSearch(depth - 1, -beta, -alpha),
castlingIncentives = depth == startDepth ? TurochampCastlingIncentives(move) : 0;
board.UndoMove(move);
if (score > alpha)
{
alpha = score;
if (score >= beta)
{
HistoryHeuristicRef(move) += depth * depth;
return beta;
}
score += castlingIncentives;
if (depth == startDepth && score > bestScore)
{
bestScore = score;
bestMoveUnconfirmed = move;
}
}
}
return alpha;
}
private int QuiescenceSearch(int alpha, int beta)
{
int standScore = TurochampEvaluate();
if (standScore >= beta)
return beta;
if (standScore > alpha)
alpha = standScore;
foreach (Move move in OrderMoves(board.GetLegalMoves(true)))
{
board.MakeMove(move);
int score = -QuiescenceSearch(-beta, -alpha);
board.UndoMove(move);
if (score >= beta)
return beta;
alpha = Math.Max(alpha, score);
}
return alpha;
}
private int TurochampEvaluate()
{
int MaterialScoreForColor(bool whiteColor)
{
var MaterialScoreForPiece = (PieceType pieceType) => board.GetPieceList(pieceType, whiteColor).Count * TurochampPieceMaterialValue(pieceType);
return MaterialScoreForPiece(PAWN)
+ MaterialScoreForPiece(KNIGHT)
+ MaterialScoreForPiece(BISHOP)
+ MaterialScoreForPiece(ROOK)
+ MaterialScoreForPiece(QUEEN);
}
int PositionalScoreForCurrentPlayer()
{
int positionalScore = 0;
var nonPawnDefenders = NumberOfNonPawnDefenders();
var pawnDefenders = NumberOfPawnDefenders();
// Mobility score (rules 1, 3): use the fact that moves are grouped by piece
int currentPieceIndex = -1,
currentMoveCount = 0;
var FlushMobilityScore = () => (int)Math.Sqrt(10_000 * currentMoveCount); // 100 * sqrt(numMoves)
foreach (Move move in board.GetLegalMoves())
{
if (move.MovePieceType == PAWN || move.IsCastles)
continue;
int fromIndex = move.StartSquare.Index;
if (fromIndex != currentPieceIndex && currentPieceIndex != -1)
{
positionalScore += FlushMobilityScore();
currentMoveCount = 0;
}
currentMoveCount += move.IsCapture ? 2 : 1;
currentPieceIndex = fromIndex;
}
positionalScore += FlushMobilityScore();
// Piece safety (rule 2)
void AddPieceSafetyScoreNonPawn(PieceType pieceType)
{
ForEachPieceOfPlayerToMove(pieceType, piece =>
{
int index = piece.Square.Index,
defenders = nonPawnDefenders[index] + pawnDefenders[index];
positionalScore += defenders > 1 ? 150 : defenders > 0 ? 100 : 0; // 1 point if defended, 1.5 points if defended 2+ times
});
}
AddPieceSafetyScoreNonPawn(ROOK);
AddPieceSafetyScoreNonPawn(BISHOP);
AddPieceSafetyScoreNonPawn(KNIGHT);
// King safety (rule 4)
currentMoveCount = BitboardHelper.GetNumberOfSetBits(BitboardHelper.GetSliderAttacks(QUEEN, board.GetKingSquare(IsWhiteToMove), board));
positionalScore -= FlushMobilityScore();
// Pawn credit (rule 6)
ForEachPieceOfPlayerToMove(PAWN, piece =>
{
Square square = piece.Square;
positionalScore += (IsWhiteToMove ? square.Rank - 1 : 6 - square.Rank) * 20 // 0.2 points for each rank advanced
+ (nonPawnDefenders[square.Index] > 0 ? 30 : 0); // 0.3 points if defended by a non-pawn
});
// Mates and checks (rule 7) is not implemented (see README.md)
return positionalScore;
}
int scoreCp = MaterialScoreForColor(IsWhiteToMove) - MaterialScoreForColor(!IsWhiteToMove) + PositionalScoreForCurrentPlayer();
board.ForceSkipTurn();
scoreCp -= PositionalScoreForCurrentPlayer();
board.UndoSkipTurn();
return scoreCp;
}
private int TurochampCastlingIncentives(Move move)
{
// Castling (rule 5)
// We don't need to play the move, this function is called from AlphaBetaSearch when the move has already been played
// Existing implementations do stack the modifiers. See README.md
if (move.IsCastles)
return 300;
bool playerOfMove = !IsWhiteToMove; // Currently it's the opponent's turn
if (!board.HasKingsideCastleRight(playerOfMove) && !board.HasKingsideCastleRight(playerOfMove))
// Since IsCastles = false, this move loses castling rights (and it must have been a king or rook move).
// If we had already lost castling rights, this function always returns 0 for all moves, so no move has priority.
return 0;
// We can castle. See if we can castle in the next turn
board.ForceSkipTurn();
foreach (Move nextMove in board.GetLegalMoves())
if (nextMove.IsCastles)
{
board.UndoSkipTurn();
return 200;
}
// We can castle, but not in the next turn.
board.UndoSkipTurn();
return 100;
}
private int TurochampPieceMaterialValue(PieceType pieceType) => pieceType switch
{
PAWN => 200,
KNIGHT => 600,
BISHOP => 700,
ROOK => 1000,
QUEEN => 2000,
_ => 0,
};
private void AddDefendersForPiece(PieceType pieceType, ref int[] defenders)
{
foreach (Piece piece in board.GetPieceList(pieceType, IsWhiteToMove))
{
ulong bitboard = BitboardHelper.GetPieceAttacks(pieceType, piece.Square, board, IsWhiteToMove);
while (bitboard != 0)
defenders[BitboardHelper.ClearAndGetIndexOfLSB(ref bitboard)]++;
}
}
private int[] NumberOfNonPawnDefenders()
{
var defenders = new int[64];
var AddDefenders = (PieceType pieceType) => AddDefendersForPiece(pieceType, ref defenders);
AddDefenders(KNIGHT);
AddDefenders(BISHOP);
AddDefenders(ROOK);
AddDefenders(QUEEN);
return defenders;
}
private int[] NumberOfPawnDefenders()
{
var defenders = new int[64];
AddDefendersForPiece(PAWN, ref defenders);
return defenders;
}
private void ForEachPieceOfPlayerToMove(PieceType pieceType, Action<Piece> callback)
{
foreach (Piece piece in board.GetPieceList(pieceType, IsWhiteToMove))
callback(piece);
}
private bool IsWhiteToMove => board.IsWhiteToMove;
private ref int HistoryHeuristicRef(Move move) => ref historyHeuristic[IsWhiteToMove ? 0 : 1, move.StartSquare.Index, move.TargetSquare.Index];
private IEnumerable<Move> OrderMoves(Move[] moves) =>
moves.Select(move =>
{
int score = HistoryHeuristicRef(move);
if (move.IsCapture)
score += 100_000 + TurochampPieceMaterialValue(move.CapturePieceType) * 4 - TurochampPieceMaterialValue(move.MovePieceType);
if (board.SquareIsAttackedByOpponent(move.TargetSquare))
score -= 50;
if (move.IsPromotion)
score += 10_000;
return (move, score);
})
.OrderByDescending(x => x.score)
.Select(x => x.move);
} | 412 | 0.984836 | 1 | 0.984836 | game-dev | MEDIA | 0.933258 | game-dev | 0.98676 | 1 | 0.98676 |
sabihoshi/GenshinLyreMidiPlayer | 7,438 | GenshinLyreMidiPlayer.WPF/ModernWPF/Animation/Transitions/SlideTransition.cs | using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace GenshinLyreMidiPlayer.WPF.ModernWPF.Animation.Transitions;
/// <summary>
/// Defines constants that describe the type of animation to play during a slide
/// transition.
/// </summary>
public enum Direction
{
/// <summary>
/// The exiting page fades out and the entering page enters from the bottom.
/// </summary>
FromBottom = 0,
/// <summary>
/// The exiting page leaves to the right of the panel and the entering page enters
/// from the left.
/// </summary>
FromLeft = 1,
/// <summary>
/// The exiting page leaves to the left of the panel and the entering page enters
/// from the right.
/// </summary>
FromRight = 2
}
/// <summary>
/// Provides the parameters for a slide navigation transition.
/// </summary>
public sealed class SlideTransition : Transition, ISlideNavigationTransitionInfo2
{
public SlideTransition(Direction effect) { Effect = effect; }
protected override Animation GetEnterAnimation(FrameworkElement element, bool movingBackwards)
{
var storyboard = new Storyboard();
var effect = Effect;
if (effect == Direction.FromBottom)
{
if (movingBackwards)
{
var opacityAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(0, TimeSpan.Zero),
new SplineDoubleKeyFrame(1, EnterDuration, DecelerateKeySpline)
}
};
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
}
else
{
var yAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(200, TimeSpan.Zero),
new SplineDoubleKeyFrame(0, EnterDuration, DecelerateKeySpline)
}
};
Storyboard.SetTargetProperty(yAnim, TranslateYPath);
storyboard.Children.Add(yAnim);
var opacityAnim = new DoubleAnimation(1, TimeSpan.Zero);
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
element.SetCurrentValue(UIElement.RenderTransformProperty, new TranslateTransform());
}
}
else
{
bool fromLeft;
if (effect == Direction.FromLeft)
fromLeft = !movingBackwards;
else
fromLeft = movingBackwards;
var xAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(fromLeft ? -200 : 200, TimeSpan.Zero),
new SplineDoubleKeyFrame(0, EnterDuration, DecelerateKeySpline)
}
};
Storyboard.SetTargetProperty(xAnim, TranslateXPath);
storyboard.Children.Add(xAnim);
var opacityAnim = new DoubleAnimation(1, TimeSpan.Zero);
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
element.SetCurrentValue(UIElement.RenderTransformProperty, new TranslateTransform());
}
return new(element, storyboard);
}
protected override Animation GetExitAnimation(FrameworkElement element, bool movingBackwards)
{
var storyboard = new Storyboard();
var effect = Effect;
if (effect == Direction.FromBottom)
{
if (movingBackwards)
{
var yAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(0, TimeSpan.Zero),
new SplineDoubleKeyFrame(200, ExitDuration, AccelerateKeySpline)
}
};
Storyboard.SetTargetProperty(yAnim, TranslateYPath);
storyboard.Children.Add(yAnim);
var opacityAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(1, TimeSpan.Zero),
new DiscreteDoubleKeyFrame(0, ExitDuration)
}
};
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
element.SetCurrentValue(UIElement.RenderTransformProperty, new TranslateTransform());
}
else
{
var opacityAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(1, TimeSpan.Zero),
new SplineDoubleKeyFrame(0, ExitDuration, AccelerateKeySpline)
}
};
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
}
}
else
{
bool toLeft;
if (effect == Direction.FromLeft)
toLeft = movingBackwards;
else
toLeft = !movingBackwards;
var xAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(0, TimeSpan.Zero),
new SplineDoubleKeyFrame(toLeft ? -200 : 200, ExitDuration, AccelerateKeySpline)
}
};
Storyboard.SetTargetProperty(xAnim, TranslateXPath);
storyboard.Children.Add(xAnim);
var opacityAnim = new DoubleAnimationUsingKeyFrames
{
KeyFrames =
{
new DiscreteDoubleKeyFrame(1, TimeSpan.Zero),
new DiscreteDoubleKeyFrame(0, ExitDuration)
}
};
Storyboard.SetTargetProperty(opacityAnim, OpacityPath);
storyboard.Children.Add(opacityAnim);
element.SetCurrentValue(UIElement.RenderTransformProperty, new TranslateTransform());
}
return new(element, storyboard);
}
#region Effect
/// <summary>
/// Identifies the Effect dependency property.
/// </summary>
public static readonly DependencyProperty EffectProperty =
DependencyProperty.Register(
nameof(Effect),
typeof(Direction),
typeof(SlideTransition),
null);
/// <summary>
/// Gets or sets the type of animation effect to play during the slide transition.
/// </summary>
/// <returns>
/// The type of animation effect to play during the slide transition.
/// </returns>
public Direction Effect
{
get => (Direction) GetValue(EffectProperty);
set => SetValue(EffectProperty, value);
}
#endregion
}
internal interface ISlideNavigationTransitionInfo2
{
Direction Effect { get; set; }
} | 412 | 0.84731 | 1 | 0.84731 | game-dev | MEDIA | 0.458235 | game-dev,desktop-app | 0.956049 | 1 | 0.956049 |
abagames/crisp-game-lib | 3,581 | docs/orbitman/main.js | title = "ORBIT MAN";
description = `
[Tap] Launch
`;
characters = [];
options = {
theme: "dark",
isPlayingBgm: true,
isReplayEnabled: true,
seed: 600,
};
/** @type {{pos: Vector, radius: number, isDestroyed: boolean}[]} */
let planets;
let nextPlanetDist;
/** @type {{planet: any, angle: number, av: number, pos: Vector, target: Vector}} */
let man;
let flyingTicks;
let multiplier;
/** @type {{pos: Vector, vy: number}[]} */
let stars;
function update() {
if (!ticks) {
planets = [{ pos: vec(50, 0), radius: 5, isDestroyed: false }];
nextPlanetDist = 20;
man = {
planet: planets[0],
angle: PI / 2,
av: 1,
pos: vec(50, 0),
target: vec(50, 0),
};
flyingTicks = 0;
multiplier = 1;
stars = times(20, () => {
return { pos: vec(rnd(99), rnd(99)), vy: rnd(3, 6) };
});
}
let scr = sqrt(difficulty) * 0.05;
flyingTicks = clamp(flyingTicks - difficulty, 1, 99);
if (man.planet.pos.y < 80) {
scr += (80 - man.planet.pos.y) * (0.1 / flyingTicks);
}
color("light_black");
stars.forEach((s) => {
s.pos.y += scr / s.vy;
if (s.pos.y > 99) {
s.pos.set(rnd(99), 0);
s.vy = rnd(3, 6);
}
rect(s.pos, 1, 1);
});
nextPlanetDist -= scr;
while (nextPlanetDist < 0) {
const radius = rnd(4, 9);
planets.push({
pos: vec(rnd(10 + radius, 90 - radius), nextPlanetDist - 30),
radius,
isDestroyed: false,
});
nextPlanetDist += radius * rnd(1, 2);
}
man.angle += difficulty * 0.03 * man.av;
color("light_blue");
bar(man.planet.pos, 99, 4, man.angle, -man.planet.radius * 0.015);
color("black");
let nextPlanet;
let maxDist = 0;
let piercedPlanets = [man.planet];
remove(planets, (p) => {
if (p.isDestroyed) {
particle(p.pos, ceil(p.radius * 4), sqrt(p.radius) * 0.5);
return true;
}
p.pos.y += scr;
const c = arc(p.pos, p.radius).isColliding.rect;
if (p !== man.planet && c.black) {
return true;
}
if (p !== man.planet && p.pos.y > -p.radius - 4 && c.light_blue) {
piercedPlanets.push(p);
const d = p.pos.distanceTo(man.planet.pos);
if (d > maxDist) {
nextPlanet = p;
maxDist = d;
}
}
return p.pos.y > 100 + p.radius * 2;
});
if (input.isJustPressed) {
if (nextPlanet == null) {
play("explosion");
for (let i = 0; i < 99; i++) {
man.pos.addWithAngle(man.angle, 3);
if (!man.pos.isInRect(5, 5, 95, 95)) {
break;
}
}
end();
} else {
play("powerUp");
if (multiplier > 1) {
multiplier--;
}
if (piercedPlanets.length > 2) {
play("hit");
}
piercedPlanets.forEach((p) => {
if (p !== nextPlanet) {
p.isDestroyed = true;
addScore(multiplier, p.pos);
multiplier++;
}
});
man.planet = nextPlanet;
man.angle += PI;
man.av *= -1;
flyingTicks = 20;
}
}
const a = man.angle;
man.target.set(man.planet.pos).addWithAngle(a, man.planet.radius);
man.pos.add(vec(man.target).sub(man.pos).mul(0.1));
color("cyan");
const p1 = vec(man.pos).addWithAngle(a, 4);
const p2 = vec(p1).addWithAngle(a + PI * 0.75, 3);
line(p1, p2, 2);
p2.set(p1).addWithAngle(a - PI * 0.75, 3);
line(p1, p2, 2);
p2.set(p1).addWithAngle(a, 4);
line(p1, p2, 2);
p2.set(p1).addWithAngle(a - PI * 0.3, 3);
p1.addWithAngle(a + PI * 0.3, 3);
line(p1, p2, 2);
if (man.planet.pos.y - man.planet.radius > 99) {
play("explosion");
end();
}
}
| 412 | 0.839361 | 1 | 0.839361 | game-dev | MEDIA | 0.747322 | game-dev | 0.894978 | 1 | 0.894978 |
RCInet/LastEpoch_Mods | 2,533 | AssetBundleExport/Library/PackageCache/com.unity.timeline@c58b4ee65782/Runtime/Extensions/TrackExtensions.cs | using System;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
namespace UnityEngine.Timeline
{
/// <summary>
/// Extension methods for TrackAssets
/// </summary>
public static class TrackAssetExtensions
{
/// <summary>
/// Gets the GroupTrack this track belongs to.
/// </summary>
/// <param name="asset">The track asset to find the group of</param>
/// <returns>The parent GroupTrack or null if the Track is an override track, or root track.</returns>
public static GroupTrack GetGroup(this TrackAsset asset)
{
if (asset == null)
return null;
return asset.parent as GroupTrack;
}
/// <summary>
/// Assigns the track to the specified group track.
/// </summary>
/// <param name="asset">The track to assign.</param>
/// <param name="group">The GroupTrack to assign the track to.</param>
/// <remarks>
/// Does not support assigning to a group in a different timeline.
/// </remarks>
public static void SetGroup(this TrackAsset asset, GroupTrack group)
{
const string undoString = "Reparent";
if (asset == null || asset == group || asset.parent == group)
return;
if (group != null && asset.timelineAsset != group.timelineAsset)
throw new InvalidOperationException("Cannot assign to a group in a different timeline");
TimelineUndo.PushUndo(asset, undoString);
var timeline = asset.timelineAsset;
var parentTrack = asset.parent as TrackAsset;
var parentTimeline = asset.parent as TimelineAsset;
if (parentTrack != null || parentTimeline != null)
{
TimelineUndo.PushUndo(asset.parent, undoString);
if (parentTimeline != null)
{
parentTimeline.RemoveTrack(asset);
}
else
{
parentTrack.RemoveSubTrack(asset);
}
}
if (group == null)
{
TimelineUndo.PushUndo(timeline, undoString);
asset.parent = asset.timelineAsset;
timeline.AddTrackInternal(asset);
}
else
{
TimelineUndo.PushUndo(group, undoString);
group.AddChild(asset);
}
}
}
}
| 412 | 0.980379 | 1 | 0.980379 | game-dev | MEDIA | 0.654408 | game-dev | 0.905551 | 1 | 0.905551 |
FoxdieTeam/mgs_reversing | 18,928 | source/game/gamed.c | #define __GAMED_SBSS__
#include "game.h"
#include <stdio.h>
#include <sys/types.h>
#include <libgte.h>
#include <libgpu.h>
#include <libapi.h>
#include <libcd.h>
#include <libpad.h>
#include <libspu.h>
#include "common.h"
#include "mts/mts.h"
#include "libgv/libgv.h"
#include "libdg/libdg.h"
#include "libfs/libfs.h"
#include "libgcl/libgcl.h"
#include "memcard/memcard.h"
#include "linkvar.h"
#include "game/loader.h"
#include "game/over.h"
#include "menu/menuman.h"
/*---------------------------------------------------------------------------*/
//both below are defined in gvd.c
extern char *GM_StageName;
char *GM_StageName;
extern GV_PAD *GM_CurrentPadData;
GV_PAD *SECTION(".sbss") GM_CurrentPadData;
int GM_GameStatus = 0;
int GM_LoadRequest = 0;
int GM_GameOverTimer = 0;
SVECTOR *GM_lpsvectWind = NULL;
TPlayerActFunction GM_lpfnPlayerActControl = NULL;
TPlayerActFunction GM_lpfnPlayerActObject2 = NULL;
short GM_uBombHoming = 0;
short GM_uTenageMotion = -1;
TBombFunction GM_lpfnBombHoming = NULL;
TBombFunction2 GM_lpfnBombBound = NULL;
TBombFunction3 GM_lpfnBombExplosion = NULL;
int GM_PadResetDisable = FALSE;
int SECTION(".sbss") dword_800AB9CC;
int SECTION(".sbss") reset_timer;
int SECTION(".sbss") dword_800AB9D4;
short SECTION(".sbss") GM_WeaponChanged;
short SECTION(".sbss") word_800AB9DA;
int SECTION(".sbss") GM_ClaymoreMap;
int SECTION(".sbss") GM_AlertMax;
unsigned int SECTION(".sbss") GM_DisableWeapon;
int SECTION(".sbss") gTotalFrameTime;
short SECTION(".sbss") GM_Magazine;
int SECTION(".sbss") GM_PlayerAddress;
CONTROL *SECTION(".sbss") GM_PlayerControl;
SVECTOR SECTION(".sbss") GM_NoisePosition;
int SECTION(".sbss") GM_AlertMode;
int SECTION(".sbss") GM_Photocode;
int SECTION(".sbss") dword_800ABA08;
int SECTION(".sbss") GM_PlayerMap;
SVECTOR SECTION(".sbss") GM_PlayerPosition;
int SECTION(".sbss") GM_AlertLevel;
int SECTION(".sbss") dword_800ABA1C;
OBJECT *SECTION(".sbss") GM_PlayerBody;
int SECTION(".sbss") GM_NoisePower;
int SECTION(".sbss") GM_DisableItem;
short SECTION(".sbss") GM_MagazineMax;
int SECTION(".sbss") GM_NoiseLength;
short SECTION(".sbss") GM_O2;
short SECTION(".sbss") GM_PDA_ClearRank;
int SECTION(".sbss") GM_LoadComplete;
int SECTION(".sbss") GM_PadVibration;
int SECTION(".sbss") GM_PlayerAction;
STATIC int SECTION(".sbss") dword_800ABA44;
SVECTOR SECTION(".sbss") GM_PhotoViewPos;
/**
* Some known settings via GM_SetPlayerStatusFlag():
* |= 0x20008000 if Snake dies from sna_check_dead_8004E384() and sna_anim_dying_80055524().
* |= 0x20 if Snake crouches from sna_anim_crouch_800527DC().
* |= 0x40 if Snake goes prone from sna_anim_prone_begin_80053BE8() and sna_anim_prone_idle_800528BC().
* |= 0x10 if Snake runs from sna_anim_run_begin_80053B88(), sna_anim_run_8005292C(),
* sna_anim_rungun_begin_80056BDC() and sna_anim_rungun_80056C3C().
* |= 0x10 if Snake moves while prone from sna_anim_prone_move_800529C0().
* |= 0x10 if Snake moves while in a box from sna_anim_box_run_8005544C().
* |= 0x10000 if Snake pushes up against a wall from sna_anim_wall_idle_and_c4_80052A5C().
* |= 0x10010 if Snake moves while up against a wall from sna_anim_wall_move_80052BA8().
* |= 0x10020 if Snake crouches while up against a wall from sna_anim_wall_crouch_80052CCC().
* |= 0x10 from sna_anim_choke_drag_80059054().
*/
PlayerStatusFlag SECTION(".sbss") GM_PlayerStatus;
int SECTION(".sbss") GM_PadVibration2;
extern unsigned short GM_SystemCallbackProc[6];
extern int str_mute_fg;
extern unsigned int str_status;
extern int dword_800BF1A8;
extern int dword_800BF270;
extern int str_off_idx;
extern char exe_name[32];
extern char *MGS_DiskName[3]; /* in main.c */
extern int FS_DiskNum;
extern int FS_ResidentCacheDirty;
extern DG_TEX gMenuTextureRec_800B58B0;
extern gameWork GameWork;
extern unsigned char *GV_ResidentMemoryBottom;
extern void *StageCharacterEntries;
extern int gOverlayBinSize_800B5290;
/*---------------------------------------------------------------------------*/
static void GM_ClearWeaponAndItem(void)
{
GM_CurrentWeaponId = WP_None;
GM_CurrentItemId = IT_None;
}
static void GM_InitGameSystem(void)
{
int i;
GM_PlayerAddress = -1;
GM_GameStatus = 0;
GM_GameOverTimer = 0;
GM_PlayerStatus = 0;
GM_NoisePower = 0;
GM_NoiseLength = 0;
GM_ClaymoreMap = 0;
GM_AlertLevel = 0;
GM_AlertMax = 0;
GM_AlertMode = 0;
GM_WeaponChanged = 0;
GM_Magazine = 0;
GM_MagazineMax = 0;
GM_DisableItem = 0;
GM_DisableWeapon = 0;
GM_O2 = 1024;
GM_StageName = NULL;
GM_EnvironTemp = 0;
GM_PlayerPosition.vx = GM_SnakePosX;
GM_PlayerPosition.vy = GM_SnakePosY;
GM_PlayerPosition.vz = GM_SnakePosZ;
for (i = 5; i >= 0; i--)
{
GM_SystemCallbackProc[i] = 0;
}
}
static void GM_InitNoise(void)
{
int length;
int max;
// isn't this one of the inlines?
length = GM_NoiseLength;
if (GM_NoiseLength > 0)
{
length = GM_NoiseLength - 1;
}
if (!length)
{
GM_NoisePower = 0;
}
max = GM_AlertMax;
GM_NoiseLength = length;
GM_AlertMax = 0;
GM_AlertLevel = max;
}
static void GM_ResetSystem(void)
{
menuman_Reset();
GV_ResetSystem();
DG_ResetPipeline();
GCL_ResetSystem();
}
static void GM_ResetMemory(void)
{
DG_ResetTextureCache();
GV_ResetMemory();
GM_ResetChara();
}
// GM_InitStage?
static void GM_CreateLoader(void)
{
char *stage = "init";
if (GM_CurrentStageFlag != 0)
{
stage = GM_GetArea(GM_CurrentStageFlag);
}
NewLoader(stage);
}
static void GM_HidePauseScreen(void)
{
GV_PauseLevel &= ~2;
GM_SetSound(0x01ffff02, SD_ASYNC);
MENU_JimakuClear();
GM_GameStatus &= ~GAME_FLAG_BIT_08;
}
static void GM_ShowPauseScreen(void)
{
char *areaName;
areaName = "";
GV_PauseLevel |= 2;
GM_SetSound(0x01ffff01, SD_ASYNC);
if (GM_StageName)
{
areaName = GM_StageName;
}
MENU_AreaNameWrite(areaName);
}
static void GM_TogglePauseScreen(void)
{
int var1;
int var2;
int ret;
var1 = GV_PauseLevel;
var2 = var1 & ~2;
ret = var2; // Why this waste?
// It should always be true because the only caller
// does the same check before calling this function.
if (var2 == 0)
{
if ((var1 & 2) == 0)
{
GM_ShowPauseScreen();
return;
}
GM_HidePauseScreen();
}
}
static void GM_ActInit(gameWork *work)
{
GM_Reset_helper3_80030760();
GM_InitWhereSystem();
GM_ResetTargets();
GM_ResetHomingTargets();
GM_InitBinds();
GM_InitGameSystem();
GM_AlertModeInit();
}
/*---------------------------------------------------------------------------*/
#define PCC_READ 0xa0be // GV_StrCode("read")
void GM_InitReadError(void)
{
DG_TEX *tex;
tex = DG_GetTexture(PCC_READ);
gMenuTextureRec_800B58B0 = *tex;
gMenuTextureRec_800B58B0.id = 0;
}
void DrawReadError(void)
{
int u_off;
DR_TPAGE tpage;
SPRT sprt;
TILE tile;
u_off = 16 * gMenuTextureRec_800B58B0.id;
gMenuTextureRec_800B58B0.id = (gMenuTextureRec_800B58B0.id + 1) % 6;
DG_DisableClipping();
setDrawTPage(&tpage, 1, 1, gMenuTextureRec_800B58B0.tpage);
DrawPrim(&tpage);
LSTORE(0, &tile.r0);
setTile(&tile);
tile.x0 = 287;
tile.y0 = 15;
tile.h = 18;
tile.w = 18;
DrawPrim(&tile);
LSTORE(0x80808080, &sprt.r0);
setSprt(&sprt);
sprt.w = 16;
sprt.h = 16;
sprt.x0 = 288;
sprt.y0 = 16;
sprt.u0 = gMenuTextureRec_800B58B0.off_x + u_off;
sprt.v0 = gMenuTextureRec_800B58B0.off_y;
sprt.clut = gMenuTextureRec_800B58B0.clut;
DrawPrim(&sprt);
}
/*---------------------------------------------------------------------------*/
static void Act(gameWork *work)
{
int load_request;
int status;
unsigned short pad = mts_read_pad(1);
if (mts_get_pad_vibration_type(1) == 1)
{
GM_OptionFlag &= ~OPTION_VIBRATION_OFF;
}
else
{
GM_OptionFlag |= OPTION_VIBRATION_OFF;
}
if ((GM_OptionFlag & (OPTION_UNKNOWN_2000 | OPTION_VIBRATION_OFF)) == 0)
{
int vibration2;
if (GM_PadVibration != 0)
{
mts_set_pad_vibration(1, 10);
}
else
{
mts_set_pad_vibration(1, 0);
}
vibration2 = GM_PadVibration2;
if (vibration2 > 255)
{
vibration2 = 255;
}
mts_set_pad_vibration2(1, vibration2);
}
GM_PadVibration2 = 0;
GM_PadVibration = 0;
if ((GV_PauseLevel & 8) != 0)
{
if (!str_mute_fg && CDBIOS_TaskState() != 3)
{
GV_PauseLevel &= ~8;
}
else
{
DrawReadError();
}
}
else if (str_mute_fg || CDBIOS_TaskState() == 3)
{
GV_PauseLevel |= 8;
}
if ((GV_PauseLevel & 2) == 0)
{
int minutes;
gTotalFrameTime += GV_PassageTime;
minutes = gTotalFrameTime / 60;
GM_TotalHours = minutes / 3600;
GM_TotalSeconds = minutes % 3600;
}
status = work->status;
if (status != WAIT_LOAD)
{
if (status != WORKING)
{
return;
}
}
else
{
if (GM_LoadComplete == 0)
{
return;
}
GM_LoadComplete = 1;
if ((GM_LoadRequest & 0x80) != 0)
{
DG_UnDrawFrameCount = 0;
}
if (FS_ResidentCacheDirty)
{
GV_SaveResidentFileCache();
DG_SaveResidentTextureCache();
}
GM_ResetMap();
NewCameraSystem();
DG_StorePalette();
GM_Act_helper2();
if ((GM_LoadRequest & 0x10) != 0)
{
GCL_SaveVar();
}
printf("exec scenario\n");
load_request = GM_LoadRequest;
GM_LoadRequest = 0;
if ((load_request & 0x20) != 0)
{
GCL_ExecProc((unsigned int)load_request >> 16, 0);
}
else
{
GCL_ExecScript();
}
printf("end scenario\n");
MENU_ResetTexture();
GM_AlertModeReset();
GM_SoundStart();
work->status = WORKING;
return;
}
if ((work->killing_count <= 0))
{
if (GM_GameOverTimer != 0)
{
if (GM_GameOverTimer > 0)
{
if ((GM_GameOverTimer == status))
{
if (GM_StreamStatus() == -1)
{
if (NewGameOver(TRUE))
{
GM_GameOverTimer = -1;
}
else
{
GV_DestroyActorSystem(GV_ACTOR_LEVEL4);
}
}
else if (GM_StreamStatus() == status)
{
GM_StreamPlayStop();
}
}
else
{
GM_GameOverTimer--;
}
}
}
else
{
if (GM_LoadRequest != 0 && (GV_PauseLevel & 2) == 0)
{
if ((GM_LoadRequest & 0x80) != 0)
{
DG_UnDrawFrameCount = 0x7fff0000;
}
GV_DestroyActorSystem(GV_ACTOR_LEVEL4);
GV_PauseLevel &= ~8;
GM_ResetMapModel();
GM_StreamPlayStop();
work->killing_count = 3;
GM_GameStatus |= STATE_PADRELEASE | STATE_ALL_OFF;
return;
}
if (GV_PauseLevel == 0)
{
GM_AlertAct();
}
if ((GM_GameStatus & (STATE_VOX_STREAM | STATE_PAUSE_OFF | STATE_PADMASK | STATE_PADRELEASE |
STATE_PADDEMO | STATE_DEMO)) == 0)
{
if (((GV_PauseLevel & ~2) == 0) && ((GM_CurrentPadData->press & PAD_START) != 0))
{
GM_TogglePauseScreen();
}
}
else if ((GV_PauseLevel & 2) != 0)
{
GM_HidePauseScreen();
}
GM_UpdateMap();
}
#define RESET_COMBO (PAD_LR|PAD_START|PAD_SELECT)
#define RESET_DELAY (90)
if (((pad & RESET_COMBO) == RESET_COMBO) && (GM_PadResetDisable == FALSE))
{
// User must hold the combo for 90 frames.
if (--reset_timer < 0)
{
sprintf(exe_name, "cdrom:\\MGS\\%s;1", MGS_DiskName[FS_DiskNum]);
EnterCriticalSection();
SetDispMask(0);
PadStopCom();
SpuInit();
CdInit();
SpuSetIRQ(SPU_OFF);
mts_shutdown();
memcard_exit();
ResetGraph(3);
StopCallback();
SetConf(0x10, 4, 0x801FFFF0); // note: hardcoded addresses
ResetCallback();
StopCallback();
_96_remove();
_96_init();
do {
printf("load %s\n", exe_name);
LoadExec(exe_name, 0x801FFF00, 0);
} while (1);
}
}
else
{
// Reset the countdown if the combo's been released.
reset_timer = RESET_DELAY;
}
#undef RESET_COMBO
#undef RESET_DELAY
if ((GM_GameStatus < 0) && ((GM_CurrentPadData[2].press & (PAD_START | PAD_CROSS)) != 0))
{
GM_StreamPlayStop();
}
if ((mts_read_pad(2) & PAD_CIRCLE) != 0)
{
char spu_status[24];
char spu_stat;
int i;
unsigned int spu_key;
SpuGetAllKeysStatus(spu_status);
spu_key = 0;
for (i = 0; i < 24; ++i)
{
spu_key *= 2;
spu_stat = spu_status[i];
spu_key |= spu_stat & 1;
}
printf("str_status %d irq %x %X %X\n", str_status, dword_800BF1A8, dword_800BF270,
str_off_idx);
printf("key %08X\n", spu_key);
}
if (GV_PauseLevel == 0)
{
GM_InitNoise();
}
}
else
{
GV_PauseLevel &= ~8;
if ((--work->killing_count <= 0))
{
if (GM_StreamStatus() == -1)
{
if ((GV_PauseLevel & 5) == 0)
{
work->status = 0;
work->killing_count = 0;
GM_ResetMapHazard();
GM_ResetSystem();
GM_ActInit(work);
if ((GM_LoadRequest & 0x40) == 0)
{
GM_ResetMemory();
GM_CreateLoader();
}
return;
}
else if ((GM_LoadRequest & 0x80) != 0)
{
DG_UnDrawFrameCount = 0;
}
}
work->killing_count = status;
}
if (GV_PauseLevel == 0)
{
GM_InitNoise();
}
}
}
void GM_SetSystemCallbackProc(int index, int proc)
{
GM_SystemCallbackProc[index] = proc;
}
void GM_CallSystemCallbackProc(int id, int arg)
{
int proc;
if (id == 4 && GM_PlayerControl != NULL)
{
HZD_ReExecEvent(GM_PlayerControl->map->hzd,
&GM_PlayerControl->event, 0x301);
}
proc = GM_SystemCallbackProc[id];
if (proc != 0)
{
GCL_ARGS args;
long argbuf[2];
args.argc = 1;
args.argv = argbuf;
argbuf[0] = arg;
GCL_ForceExecProc(proc, &args);
}
}
void GM_SetLoadCallbackProc(int proc_id)
{
if (proc_id == -1)
{
GM_LoadRequest = 0xc0;
}
else
{
GM_LoadRequest = proc_id << 16 | 0xe0;
}
}
void GM_ContinueStart(void)
{
int total_continues;
int current_stage;
GM_CallSystemCallbackProc(1, 0);
total_continues = GM_TotalContinues;
current_stage = GM_CurrentStageFlag;
GCL_RestoreVar();
if (GM_CurrentStageFlag != current_stage)
{
GM_LoadRequest = 1;
}
else
{
GM_SetLoadCallbackProc(-1);
}
GM_TotalContinues = total_continues + 1;
// Set the bomb to no less than 10 seconds to prevent instant death
// note: casting needed to produce sltiu and lhu vs lh
if ((unsigned int)(unsigned short)GM_TimerBombFlag - 1 < 9)
{
GM_TimerBombFlag = 10;
}
}
void GM_GameOver(void)
{
if (!GM_GameOverTimer)
{
GM_GameOverTimer = 4;
GM_CallSystemCallbackProc(0, 0);
GM_GameStatus |= (STATE_RADIO_OFF | STATE_PAUSE_OFF | STATE_MENU_OFF);
}
}
/**
* @brief Overlay binary initialization handler
*
* Copies the overlay from its temporary buffer to the overlay base address.
* The overlay's filename will always be xxx.bin (where "xxx" is the name of
* the current stage).
*
* @param[in] buf pointer to cached overlay buffer
* @param[in] id strcode of the overlay's basename
*
* @retval 1 on success
* @retval <= 0 on failure (but this can't happen)
*/
static int GM_LoadInitBin(unsigned char *buf, int id)
{
#ifdef DEV_EXE
return 1; // the overlay is embedded in the executable in dev variant
#endif
if (((u_char *)StageCharacterEntries + gOverlayBinSize_800B5290) > GV_ResidentMemoryBottom)
{
printf("TOO LARGE STAGE BINARY!!\n");
}
memcpy(StageCharacterEntries, buf, gOverlayBinSize_800B5290);
return 1;
}
void GM_StartDaemon(void)
{
gTotalFrameTime = 0;
GM_GameOverTimer = 0;
GM_LoadRequest = 0;
GM_LoadComplete = 0;
MENU_StartDeamon();
GM_InitArea();
GM_InitChara();
GM_InitScript();
GV_SetLoader('b', GM_LoadInitBin);
GM_ClearWeaponAndItem();
GV_InitActor(GV_ACTOR_MANAGER, &GameWork.actor, NULL);
GV_SetNamedActor(&GameWork.actor, Act, NULL, "gamed.c");
GM_ResetSystem();
GM_ActInit(&GameWork);
GM_ResetMemory();
GM_CurrentPadData = GV_PadData;
GM_CurrentDiskFlag = FS_DiskNum + 1;
GV_SaveResidentTop();
GameWork.status = 0;
GameWork.killing_count = 0;
GM_CreateLoader();
}
| 412 | 0.955135 | 1 | 0.955135 | game-dev | MEDIA | 0.677856 | game-dev,testing-qa | 0.952465 | 1 | 0.952465 |
edge-classic/EDGE-classic | 23,397 | source_files/edge/con_main.cc | //----------------------------------------------------------------------------
// EDGE Console Main
//----------------------------------------------------------------------------
//
// Copyright (c) 1999-2024 The EDGE Team.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//----------------------------------------------------------------------------
#include "con_main.h"
#include <stdarg.h>
#include <string.h>
#include "con_var.h"
#include "ddf_language.h"
#include "ddf_sfx.h"
#include "dm_state.h"
#include "e_input.h"
#include "epi_filesystem.h"
#include "epi_str_compare.h"
#include "epi_str_util.h"
#include "g_game.h"
#include "i_system.h"
#include "m_menu.h"
#include "m_misc.h"
#include "p_local.h"
#include "r_misc.h"
#include "s_sound.h"
#include "stb_sprintf.h"
#include "version.h"
#include "w_files.h"
#include "w_wad.h"
static constexpr uint8_t kMaximumConsoleArguments = 64;
static std::string readme_names[4] = {"readme.txt", "readme.1st", "read.me", "readme.md"};
std::string working_directory;
struct ConsoleCommand
{
const char *name;
int (*func)(char **argv, int argc);
};
// forward decl.
extern const ConsoleCommand builtin_commands[];
extern void M_ChangeLevelCheat(const char *string);
extern void ShowGamepads(void);
int ConsoleCommandExec(char **argv, int argc)
{
if (argc != 2)
{
ConsoleMessage(kConsoleOnly, "Usage: exec <filename>\n");
return 1;
}
if (epi::IsPathAbsolute(argv[1]))
{
LogPrint("Absolute path %s not allowed!\n", argv[1]);
return 1;
}
if (strstr(argv[1], "..") != NULL)
{
LogPrint("Path traversal with .. is not allowed!\n");
return 1;
}
std::string path = epi::PathAppend(working_directory, argv[1]);
FILE *script = epi::FileOpenRaw(path, epi::kFileAccessRead | epi::kFileAccessBinary);
if (!script)
{
ConsoleMessage(kConsoleOnly, "Unable to open file: %s\n", argv[1]);
return 1;
}
char buffer[200];
while (fgets(buffer, sizeof(buffer) - 1, script))
{
TryConsoleCommand(buffer);
}
fclose(script);
return 0;
}
int ConsoleCommandMove(char **argv, int argc)
{
if (argc != 3)
{
ConsoleMessage(kConsoleOnly, "Usage: move <x> <y>\n");
return 1;
}
MapObject *mo = nullptr;
if (players[console_player])
mo = players[console_player]->map_object_;
if (!mo || game_state != kGameStateLevel)
{
ConsoleMessage(kConsoleOnly, "No player to move! (are you in a level?)\n");
return 1;
}
else
{
float x = atof(argv[1]);
float y = atof(argv[2]);
if (BlockmapGetX(x) < 0 || BlockmapGetX(x) > blockmap_width - 1)
{
ConsoleMessage(kConsoleOnly, "Invalid X coordinate %g\n", x);
return 1;
}
if (BlockmapGetY(y) < 0 || BlockmapGetY(y) > blockmap_height - 1)
{
ConsoleMessage(kConsoleOnly, "Invalid Y coordinate %g\n", y);
return 1;
}
if (!TryMove(mo, x, y))
{
ConsoleMessage(kConsoleOnly, "Move from (%g,%g) to (%g,%g) failed!\n", mo->x, mo->y, x, y);
return 1;
}
return 0;
}
}
int ConsoleCommandSpawn(char **argv, int argc)
{
if (argc < 2)
{
ConsoleMessage(kConsoleOnly, "Usage: spawn <name or id #> <optional x y>\n");
return 1;
}
if (argc > 2 && argc != 4)
{
ConsoleMessage(kConsoleOnly, "Usage: spawn <name or id #> <optional x y>\n");
return 1;
}
if (game_state != kGameStateLevel || !players[console_player] || !players[console_player]->map_object_)
{
ConsoleMessage(kConsoleOnly, "Need to be in a level to spawn something!\n");
return 1;
}
const MapObjectDefinition *info = nullptr;
int id = atoi(argv[1]);
if (id)
info = mobjtypes.Lookup(id);
else
info = mobjtypes.Lookup(argv[1], true);
if (!info)
{
ConsoleMessage(kConsoleOnly, "Unknown DDF thing %s; cannot spawn\n", argv[1]);
return 1;
}
float x;
float y;
float z;
if (argc == 2)
{
MapObject *pl = players[console_player]->map_object_;
x = pl->x;
y = pl->y;
z = pl->z;
// spawn thing a little bit in front of the player
x += info->radius_ * 4 * epi::BAMCos(pl->angle_);
y += info->radius_ * 4 * epi::BAMSin(pl->angle_);
}
else
{
x = atof(argv[2]);
y = atof(argv[3]);
z = info->flags_ & kMapObjectFlagSpawnCeiling ? kOnCeilingZ : kOnFloorZ;
}
if (BlockmapGetX(x) < 0 || BlockmapGetX(x) > blockmap_width - 1)
{
ConsoleMessage(kConsoleOnly, "Invalid X coordinate %g\n", x);
return 1;
}
if (BlockmapGetY(y) < 0 || BlockmapGetY(y) > blockmap_height - 1)
{
ConsoleMessage(kConsoleOnly, "Invalid Y coordinate %g\n", y);
return 1;
}
MapObject *mo = CreateMapObject(x, y, z, info);
if (!mo)
{
ConsoleMessage(kConsoleOnly, "Spawn %s at (%g,%g) failed!\n", argv[1], x, y);
return 1;
}
else
mo->angle_ = players[console_player]->map_object_->angle_;
return 0;
}
int ConsoleCommandGodMode(char **argv, int argc)
{
EPI_UNUSED(argv);
if (argc != 1)
{
ConsoleMessage(kConsoleOnly, "Usage: god\n");
return 1;
}
Player *pl = players[console_player];
if (!pl || game_state != kGameStateLevel)
{
ConsoleMessage(kConsoleOnly, "Cannot toggle God Mode! (are you in a level?)\n");
return 1;
}
else
{
pl->cheats_ ^= kCheatingGodMode;
if (pl->cheats_ & kCheatingGodMode)
{
if (pl->map_object_)
{
pl->health_ = pl->map_object_->health_ = pl->map_object_->spawn_health_;
}
ConsoleMessage(kConsoleOnly, "%s\n", language["GodModeOn"]);
}
else
ConsoleMessage(kConsoleOnly, "%s\n", language["GodModeOff"]);
return 0;
}
}
int ConsoleCommandNoClip(char **argv, int argc)
{
EPI_UNUSED(argv);
if (argc != 1)
{
ConsoleMessage(kConsoleOnly, "Usage: noclip\n");
return 1;
}
Player *pl = players[console_player];
if (!pl || game_state != kGameStateLevel)
{
ConsoleMessage(kConsoleOnly, "Cannot toggle NoClilp! (are you in a level?)\n");
return 1;
}
else
{
pl->cheats_ ^= kCheatingNoClip;
if (pl->cheats_ & kCheatingNoClip)
ConsoleMessage(kConsoleOnly, "%s\n", language["ClipOn"]);
else
ConsoleMessage(kConsoleOnly, "%s\n", language["ClipOff"]);
return 0;
}
}
int ConsoleCommandType(char **argv, int argc)
{
FILE *script;
char buffer[200];
if (argc != 2)
{
ConsoleMessage(kConsoleOnly, "Usage: %s <filename>\n", argv[0]);
return 2;
}
if (epi::IsPathAbsolute(argv[1]))
{
LogPrint("Absolute path %s not allowed!\n", argv[1]);
return 1;
}
if (strstr(argv[1], "..") != NULL)
{
LogPrint("Path traversal with .. is not allowed!\n");
return 1;
}
std::string path = epi::PathAppend(working_directory, argv[1]);
script = epi::FileOpenRaw(path, epi::kFileAccessRead);
if (!script)
{
ConsoleMessage(kConsoleOnly, "Unable to open \'%s\'!\n", argv[1]);
return 3;
}
while (fgets(buffer, sizeof(buffer) - 1, script))
{
ConsoleMessage(kConsoleOnly, "%s", buffer);
}
fclose(script);
return 0;
}
int ConsoleCommandReadme(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
epi::File *readme_file = nullptr;
// Check well known readme filenames
for (const std::string &name : readme_names)
{
readme_file = OpenFileFromPack(name);
if (readme_file)
break;
}
if (!readme_file)
{
// Check for the existence of a .txt file whose name matches a WAD or
// pack in the load order
for (int i = data_files.size() - 1; i > 0; i--)
{
std::string readme_check = data_files[i]->name_;
epi::ReplaceExtension(readme_check, ".txt");
readme_file = OpenFileFromPack(readme_check);
if (readme_file)
break;
}
}
// Check for WADINFO or README lumps
if (!readme_file)
{
if (IsLumpInAnyWad("WADINFO"))
readme_file = LoadLumpAsFile("WADINFO");
else if (IsLumpInAnyWad("README"))
readme_file = LoadLumpAsFile("README");
}
// Check for an EDGEGAME lump or file and print (if it has text; these
// aren't required to)
if (!readme_file)
{
// Datafile at index 1 should always be either the IWAD or standalone
// EPK
if (data_files[1]->wad_)
{
if (IsLumpInAnyWad("EDGEGAME"))
readme_file = LoadLumpAsFile("EDGEGAME");
}
else
readme_file = OpenFileFromPack("EDGEGAME.txt");
}
if (!readme_file)
{
ConsoleMessage(kConsoleOnly, "No readme files found in current load order!\n");
return 1;
}
else
{
std::string readme = readme_file->ReadText();
delete readme_file;
std::vector<std::string> readme_strings = epi::SeparatedStringVector(readme, '\n');
for (std::string &line : readme_strings)
{
ConsoleMessage(kConsoleOnly, "%s\n", line.c_str());
}
}
return 0;
}
int ConsoleCommandChangeDir(char **argv, int argc)
{
if (argc == 1 || argc > 2)
{
LogPrint("Usage: %s <home or game>\n", argv[0]);
return 1;
}
if (home_directory == game_directory)
{
LogPrint("Home and game directory are both %s!\nRemaining in current directory.\n",
epi::SanitizePath(working_directory).c_str());
return 1;
}
else if (epi::StringCaseCompareASCII(argv[1], "game") == 0)
{
working_directory = game_directory;
LogPrint("Switched to game directory %s\n", epi::SanitizePath(working_directory).c_str());
}
else if (epi::StringCaseCompareASCII(argv[1], "home") == 0)
{
working_directory = home_directory;
LogPrint("Switched to home directory %s\n", epi::SanitizePath(working_directory).c_str());
}
else
{
LogPrint("Unknown cd target %s (must be \"home\" or \"game\")\n", argv[1]);
return 1;
}
return 0;
}
int ConsoleCommandPrintWorkingDir(char **argv, int argc)
{
if (argc > 1)
{
LogPrint("Usage: %s\n", argv[0]);
return 1;
}
if (home_directory != game_directory)
{
if (working_directory == game_directory)
LogPrint("Using game directory %s\n", epi::SanitizePath(working_directory).c_str());
else
LogPrint("Using home directory %s\n", epi::SanitizePath(working_directory).c_str());
}
else
LogPrint("Using directory %s\n", epi::SanitizePath(working_directory).c_str());
return 0;
}
int ConsoleCommandDir(char **argv, int argc)
{
std::string path = ".";
std::string mask = "*.*";
if (argc >= 2)
{
// Assume a leading * is the beginning of a mask for the current dir
if (argv[1][0] == '*')
mask = argv[1];
else
path = argv[1];
}
if (argc >= 3)
mask = argv[2];
if (epi::IsPathAbsolute(path))
{
LogPrint("Absolute path %s not allowed!\n", path.c_str());
return 1;
}
if (path.find("..") != std::string::npos)
{
LogPrint("Path traversal with .. is not allowed!\n");
return 1;
}
path = epi::PathAppend(working_directory, path);
std::vector<epi::DirectoryEntry> fsd;
if (!ReadDirectory(fsd, path, mask.c_str()))
{
LogPrint("Failed to read dir: %s\n", path.c_str());
return 1;
}
if (fsd.empty())
{
LogPrint("No files found in provided path %s\n", path.c_str());
return 0;
}
LogPrint("Directory contents for %s matching %s\n", epi::SanitizePath(epi::GetDirectory(path)).c_str(),
mask.c_str());
for (size_t i = 0; i < fsd.size(); i++)
{
LogPrint("%4d: %-4s \"%s\"\n", (int)i + 1, fsd[i].is_dir ? "dir " : "file",
epi::GetFilename(fsd[i].name).c_str());
}
return 0;
}
int ConsoleCommandScreenShot(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
DeferredScreenShot();
return 0;
}
int ConsoleCommandQuitEDGE(char **argv, int argc)
{
#ifdef EDGE_WEB
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ConsoleMessage(kConsoleOnly, "%s\n", language["QuitWhenWebPlayer"]);
return 1;
#else
if (argc >= 2 && epi::StringCaseCompareASCII(argv[1], "now") == 0)
// this never returns
ImmediateQuit();
else
QuitEdge(0);
return 0;
#endif
}
int ConsoleCommandPlaySound(char **argv, int argc)
{
SoundEffect *sfx;
if (argc != 2)
{
ConsoleMessage(kConsoleOnly, "Usage: playsound <name>\n");
return 1;
}
sfx = sfxdefs.GetEffect(argv[1], false);
if (!sfx)
{
ConsoleMessage(kConsoleOnly, "No such sound: %s\n", argv[1]);
}
else
{
StartSoundEffect(sfx, kCategoryUi);
}
return 0;
}
int ConsoleCommandResetVars(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ResetAllConsoleVariables();
ResetDefaults(0);
return 0;
}
int ConsoleCommandShowFiles(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ShowLoadedFiles();
return 0;
}
int ConsoleCommandBrowse(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
#ifdef EDGE_WEB
ConsoleMessage(kConsoleOnly, "%s\n", language["NoBrowseFromWeb"]);
return 1;
#else
epi::OpenDirectory(working_directory);
return 0;
#endif
}
int ConsoleCommandShowVars(char **argv, int argc)
{
bool show_default = false;
char *match = nullptr;
if (argc >= 2 && epi::StringCaseCompareASCII(argv[1], "-l") == 0)
{
show_default = true;
argv++;
argc--;
}
if (argc >= 2)
match = argv[1];
LogPrint("Console Variables:\n");
int total = PrintConsoleVariables(match, show_default);
if (total == 0)
LogPrint("Nothing matched.\n");
return 0;
}
int ConsoleCommandShowCommands(char **argv, int argc)
{
char *match = nullptr;
if (argc >= 2)
match = argv[1];
LogPrint("Console Commands:\n");
int total = 0;
for (int i = 0; builtin_commands[i].name; i++)
{
if (match && *match)
if (!strstr(builtin_commands[i].name, match))
continue;
LogPrint(" %-15s\n", builtin_commands[i].name);
total++;
}
if (total == 0)
LogPrint("Nothing matched.\n");
return 0;
}
int ConsoleCommandShowMaps(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
LogPrint("Warp Name Description\n");
for (size_t i = 0; i < mapdefs.size(); i++)
{
if (MapExists(mapdefs[i]) && mapdefs[i]->episode_)
LogPrint(" %s %s\n", mapdefs[i]->name_.c_str(),
language[mapdefs[i]->description_.c_str()]);
}
return 0;
}
int ConsoleCommandShowGamepads(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ShowGamepads();
return 0;
}
int ConsoleCommandHelp(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
LogPrint("Welcome to the EDGE Console.\n");
LogPrint("\n");
LogPrint("Use the 'showcmds' command to list all commands.\n");
LogPrint("The 'showvars' command will list all variables.\n");
LogPrint("Both of these can take a keyword to match the names with.\n");
LogPrint("\n");
LogPrint("To show the value of a variable, just type its name.\n");
LogPrint("To change it, follow the name with a space and the new value.\n");
LogPrint("\n");
LogPrint("Press ESC key to close the console.\n");
LogPrint("The PGUP and PGDN keys scroll the console up and down.\n");
LogPrint("The UP and DOWN arrow keys let you recall previous commands.\n");
LogPrint("\n");
LogPrint("Have a nice day!\n");
return 0;
}
int ConsoleCommandVersion(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
LogPrint("%s v%s\n", application_name.c_str(), edge_version.c_str());
return 0;
}
int ConsoleCommandMap(char **argv, int argc)
{
if (argc <= 1)
{
ConsoleMessage(kConsoleOnly, "Usage: map <level>\n");
return 0;
}
M_ChangeLevelCheat(argv[1]);
return 0;
}
int ConsoleCommandEndoom(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ConsoleENDOOM();
return 0;
}
int ConsoleCommandClear(char **argv, int argc)
{
EPI_UNUSED(argv);
EPI_UNUSED(argc);
ClearConsole();
return 0;
}
//----------------------------------------------------------------------------
// oh lordy....
static char *StrDup(const char *start, int len)
{
char *buf = new char[len + 2];
memcpy(buf, start, len);
buf[len] = 0;
return buf;
}
static int GetArgs(const char *line, char **argv, int max_argc)
{
int argc = 0;
for (;;)
{
while (epi::IsSpaceASCII(*(uint8_t *)line))
line++;
if (!*line)
break;
// silent truncation (bad?)
if (argc >= max_argc)
break;
const char *start = line;
if (*line == '"')
{
start++;
line++;
while (*line && *line != '"')
line++;
}
else
{
while (*line && !epi::IsSpaceASCII(*(uint8_t *)line))
line++;
}
// ignore empty strings at beginning of the line
if (!(argc == 0 && start == line))
{
argv[argc++] = StrDup(start, line - start);
}
if (*line)
line++;
}
return argc;
}
static void KillArgs(char **argv, int argc)
{
for (int i = 0; i < argc; i++)
delete[] argv[i];
}
//
// Current console commands:
//
const ConsoleCommand builtin_commands[] = {{"cat", ConsoleCommandType},
{"cd", ConsoleCommandChangeDir},
{"chdir", ConsoleCommandChangeDir},
{"cls", ConsoleCommandClear},
{"clear", ConsoleCommandClear},
{"dir", ConsoleCommandDir},
{"ls", ConsoleCommandDir},
{"endoom", ConsoleCommandEndoom},
{"endtext", ConsoleCommandEndoom},
{"exec", ConsoleCommandExec},
{"help", ConsoleCommandHelp},
{"map", ConsoleCommandMap},
{"warp", ConsoleCommandMap}, // compatibility
{"playsound", ConsoleCommandPlaySound},
{"readme", ConsoleCommandReadme},
{"browse", ConsoleCommandBrowse},
{"pwd", ConsoleCommandPrintWorkingDir},
{"resetvars", ConsoleCommandResetVars},
{"showfiles", ConsoleCommandShowFiles},
{"showgamepads", ConsoleCommandShowGamepads},
{"showcmds", ConsoleCommandShowCommands},
{"showmaps", ConsoleCommandShowMaps},
{"showvars", ConsoleCommandShowVars},
{"screenshot", ConsoleCommandScreenShot},
{"type", ConsoleCommandType},
{"version", ConsoleCommandVersion},
{"quit", ConsoleCommandQuitEDGE},
{"exit", ConsoleCommandQuitEDGE},
{"move", ConsoleCommandMove},
{"spawn", ConsoleCommandSpawn},
{"god", ConsoleCommandGodMode},
{"noclip", ConsoleCommandNoClip},
// end of list
{nullptr, nullptr}};
static int FindCommand(const char *name)
{
for (int i = 0; builtin_commands[i].name; i++)
{
if (epi::StringCaseCompareASCII(name, builtin_commands[i].name) == 0)
return i;
}
return -1; // not found
}
void TryConsoleCommand(const char *cmd)
{
char *argv[kMaximumConsoleArguments];
int argc = GetArgs(cmd, argv, kMaximumConsoleArguments);
if (argc == 0)
return;
int index = FindCommand(argv[0]);
if (index >= 0)
{
(*builtin_commands[index].func)(argv, argc);
KillArgs(argv, argc);
return;
}
ConsoleVariable *var = FindConsoleVariable(argv[0]);
if (var != nullptr)
{
if (argc <= 1)
{
LogPrint("%s \"%s\"\n", argv[0], var->c_str());
}
else if (argc - 1 >= 2) // Assume string with spaces; concat args into
// one string and try it
{
std::string concatter = argv[1];
for (int i = 2; i < argc; i++)
{
// preserve spaces in original string
concatter.append(" ").append(argv[i]);
}
*var = concatter.c_str();
}
else if ((var->flags_ & kConsoleVariableFlagReadOnly) != 0)
LogPrint("The cvar '%s' is read only.\n", var->name_);
else
{
*var = argv[1];
}
KillArgs(argv, argc);
return;
}
LogPrint("Unknown console command: %s\n", argv[0]);
KillArgs(argv, argc);
return;
}
int MatchConsoleCommands(std::vector<const char *> &list, const char *pattern)
{
list.clear();
for (int i = 0; builtin_commands[i].name; i++)
{
if (!ConsoleMatchPattern(builtin_commands[i].name, pattern))
continue;
list.push_back(builtin_commands[i].name);
}
return (int)list.size();
}
//--- editor settings ---
// vi:ts=4:sw=4:noexpandtab
| 412 | 0.846059 | 1 | 0.846059 | game-dev | MEDIA | 0.612829 | game-dev | 0.742291 | 1 | 0.742291 |
metadriverse/urban-sim | 1,672 | meta_source/metaurban/metaurban/component/traffic_participants/cyclist.py | from metaurban.component.traffic_participants.base_traffic_participant import BaseTrafficParticipant
from typing import Tuple
from panda3d.bullet import BulletBoxShape
from panda3d.bullet import BulletCylinderShape
from metaurban.constants import MetaUrbanType, Semantics
from metaurban.constants import CollisionGroup
from metaurban.engine.asset_loader import AssetLoader
from metaurban.engine.physics_node import BaseRigidBodyNode
class Cyclist(BaseTrafficParticipant):
MASS = 80 # kg
TYPE_NAME = MetaUrbanType.CYCLIST
COLLISION_MASK = CollisionGroup.TrafficParticipants
SEMANTIC_LABEL = Semantics.BIKE.label
MODEL = None
HEIGHT = 1.75
def __init__(self, position, heading_theta, random_seed, name=None):
super(Cyclist, self).__init__(position, heading_theta, random_seed, name=name)
self.set_metaurban_type(self.TYPE_NAME)
n = BaseRigidBodyNode(self.name, self.TYPE_NAME)
self.add_body(n)
self.body.addShape(BulletBoxShape((self.LENGTH / 2, self.WIDTH / 2, self.HEIGHT / 2)))
if self.render:
if Cyclist.MODEL is None:
model = self.loader.loadModel(AssetLoader.file_path("models", "bicycle", "scene.gltf"))
model.setScale(0.15)
model.setPos(0, 0, -0.3)
Cyclist.MODEL = model
Cyclist.MODEL.instanceTo(self.origin)
def set_velocity(self, direction, value=None, in_local_frame=False):
super(Cyclist, self).set_velocity(direction, value, in_local_frame)
self.standup()
@property
def WIDTH(self):
return 0.4
@property
def LENGTH(self):
return 1.75
| 412 | 0.684206 | 1 | 0.684206 | game-dev | MEDIA | 0.616674 | game-dev | 0.806216 | 1 | 0.806216 |
etorth/mir2x | 1,681 | client/src/clientgasant.hpp | #pragma once
#include "dbcomid.hpp"
#include "fflerror.hpp"
#include "clientmonster.hpp"
class ClientGasAnt: public ClientMonster
{
public:
ClientGasAnt(uint64_t uid, ProcessRun *proc, const ActionNode &action)
: ClientMonster(uid, proc, action)
{
fflassert(isMonster(u8"爆毒蚂蚁"));
}
protected:
bool onActionAttack(const ActionNode &action) override
{
const auto [endX, endY, endDir] = motionEndGLoc().at(1);
m_motionQueue = makeWalkMotionQueue(endX, endY, action.x, action.y, SYS_MAXSPEED);
m_motionQueue.push_back(std::unique_ptr<MotionNode>(new MotionNode
{
.type = MOTION_MON_ATTACK0,
.direction = m_processRun->getAimDirection(action, currMotion()->direction),
.x = action.x,
.y = action.y,
}));
m_motionQueue.back()->addTrigger(false, [targetUID = action.aimUID, this](MotionNode *motionPtr) -> bool
{
if(motionPtr->frame < 2){
return false;
}
m_processRun->addFollowUIDMagic(std::unique_ptr<FollowUIDMagic>(new FollowUIDMagic
{
u8"爆毒蚂蚁_喷毒",
u8"运行",
motionPtr->x * SYS_MAPGRIDXP,
motionPtr->y * SYS_MAPGRIDYP,
0,
(motionPtr->direction - DIR_BEGIN) * 2,
20,
targetUID,
m_processRun,
}));
return true;
});
return true;
}
};
| 412 | 0.917335 | 1 | 0.917335 | game-dev | MEDIA | 0.903058 | game-dev | 0.956953 | 1 | 0.956953 |
TheKisDevs/LavaHack-Public | 13,785 | src/main/java/i/gishreloaded/gishcode/utils/BlockUtils.java | package i.gishreloaded.gishcode.utils;
import java.util.LinkedList;
import i.gishreloaded.gishcode.wrappers.Wrapper;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.client.*;
import net.minecraft.network.play.client.CPacketPlayerDigging.Action;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.*;
public final class BlockUtils {
private static Minecraft mc = Minecraft.getMinecraft();
public static IBlockState getState(BlockPos pos)
{
return mc.world.getBlockState(pos);
}
public static Block getBlock(BlockPos pos) {
return getState(pos).getBlock();
}
public static Material getMaterial(BlockPos pos)
{
return getState(pos).getMaterial();
}
public static boolean canBeClicked(BlockPos pos)
{
return getBlock(pos).canCollideCheck(getState(pos), false);
}
public static float getHardness(BlockPos pos) {
return getState(pos).getPlayerRelativeBlockHardness(Wrapper.INSTANCE.player(), Wrapper.INSTANCE.world(), pos);
}
public static boolean isBlockMaterial(BlockPos blockPos, Block block) {
return BlockUtils.getBlock(blockPos) == Blocks.AIR;
}
public static boolean isBlockMaterial(BlockPos blockPos, Material material) {
return BlockUtils.getState(blockPos).getMaterial() == material;
}
public static void placeBlock(BlockPos position, EnumHand hand, boolean packet) {
if (!BlockUtils.mc.world.getBlockState(position).getBlock().isReplaceable(mc.world, position)) {
return;
}
if (BlockUtils.getPlaceableSide(position) == null) {
return;
}
BlockUtils.clickBlock(position, BlockUtils.getPlaceableSide(position), (EnumHand)hand, (boolean)packet);
BlockUtils.mc.player.connection.sendPacket(new CPacketAnimation((EnumHand)hand));
}
public static void clickBlock(BlockPos position, EnumFacing side, EnumHand hand, boolean packet) {
if (packet != false) {
BlockUtils.mc.player.connection.sendPacket(new CPacketPlayerTryUseItemOnBlock(position.offset((EnumFacing)side), side.getOpposite(), (EnumHand)hand, Float.intBitsToFloat(Float.floatToIntBits(17.735476f) ^ 0x7E8DE241), Float.intBitsToFloat(Float.floatToIntBits(26.882437f) ^ 0x7ED70F3B), Float.intBitsToFloat(Float.floatToIntBits(3.0780227f) ^ 0x7F44FE53)));
} else {
BlockUtils.mc.playerController.processRightClickBlock(BlockUtils.mc.player, BlockUtils.mc.world, position.offset((EnumFacing)side), side.getOpposite(), new Vec3d((Vec3i)position), (EnumHand)hand);
}
}
public static EnumFacing getPlaceableSide(BlockPos pos) {
for (EnumFacing side : EnumFacing.values()) {
IBlockState blockState;
BlockPos neighbour = pos.offset(side);
if (!BlockUtils.mc.world.getBlockState(neighbour).getBlock().canCollideCheck(BlockUtils.mc.world.getBlockState(neighbour), false) || (blockState = BlockUtils.mc.world.getBlockState(neighbour)).getMaterial().isReplaceable()) continue;
return side;
}
return null;
}
public static boolean placeBlockLegit(BlockPos pos) {
Vec3d eyesPos = new Vec3d(Wrapper.INSTANCE.player().posX,
Wrapper.INSTANCE.player().posY + Wrapper.INSTANCE.player().getEyeHeight(), Wrapper.INSTANCE.player().posZ);
for(EnumFacing side : EnumFacing.values()) {
BlockPos neighbor = pos.offset(side);
EnumFacing side2 = side.getOpposite();
// check if side is visible (facing away from player)
// TODO: actual line-of-sight check
if(eyesPos.squareDistanceTo(
new Vec3d(pos).addVector(0.5, 0.5, 0.5)) >= eyesPos
.squareDistanceTo(
new Vec3d(neighbor).addVector(0.5, 0.5, 0.5)))
continue;
// check if neighbor can be right clicked
if(!getBlock(neighbor)
.canCollideCheck(Wrapper.INSTANCE.world().getBlockState(neighbor), false))
continue;
Vec3d hitVec = new Vec3d(neighbor).addVector(0.5, 0.5, 0.5)
.add(new Vec3d(side2.getDirectionVec()).scale(0.5));
// check if hitVec is within range (4.25 blocks)
if(eyesPos.squareDistanceTo(hitVec) > 18.0625)
continue;
// place block
faceVectorPacket(hitVec);
//mc.playerController.processRightClickBlock(mc.player, mc.world,
//neighbor, side2, hitVec, EnumHand.MAIN_HAND);
//mc.player.swingArm(EnumHand.MAIN_HAND);
//mc.rightClickDelayTimer = 4;
}
Wrapper.INSTANCE.sendPacket(new CPacketPlayerTryUseItem(EnumHand.MAIN_HAND));
Utils.swingMainHand();
return true;
}
public static boolean placeBlockSimple(BlockPos pos) {
Vec3d eyesPos = new Vec3d(Wrapper.INSTANCE.player().posX,
Wrapper.INSTANCE.player().posY + Wrapper.INSTANCE.player().getEyeHeight(), Wrapper.INSTANCE.player().posZ);
for(EnumFacing side : EnumFacing.values()) {
BlockPos neighbor = pos.offset(side);
EnumFacing side2 = side.getOpposite();
// check if neighbor can be right clicked
if(!getBlock(neighbor)
.canCollideCheck(BlockUtils.getState(neighbor), false))
continue;
Vec3d hitVec = new Vec3d(neighbor).addVector(0.5, 0.5, 0.5)
.add(new Vec3d(side2.getDirectionVec()).scale(0.5));
// check if hitVec is within range (6 blocks)
if(eyesPos.squareDistanceTo(hitVec) > 36)
continue;
// place block
Wrapper.INSTANCE.controller().processRightClickBlock(Wrapper.INSTANCE.player(), Wrapper.INSTANCE.world(),
neighbor, side2, hitVec, EnumHand.MAIN_HAND);
return true;
}
return false;
}
// TODO: RotationUtils class for all the faceSomething() methods
public static void faceVectorPacket(Vec3d vec) {
double diffX = vec.x - Wrapper.INSTANCE.player().posX;
double diffY = vec.y - (Wrapper.INSTANCE.player().posY + Wrapper.INSTANCE.player().getEyeHeight());
double diffZ = vec.z - Wrapper.INSTANCE.player().posZ;
double dist = MathHelper.sqrt(diffX * diffX + diffZ * diffZ);
float yaw = (float)Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F;
float pitch = (float)-Math.toDegrees(Math.atan2(diffY, dist));
Wrapper.INSTANCE.player().connection.sendPacket(new CPacketPlayer.Rotation(
Wrapper.INSTANCE.player().rotationYaw
+ MathHelper.wrapDegrees(yaw - Wrapper.INSTANCE.player().rotationYaw),
Wrapper.INSTANCE.player().rotationPitch
+ MathHelper.wrapDegrees(pitch - Wrapper.INSTANCE.player().rotationPitch),
Wrapper.INSTANCE.player().onGround));
}
public static void faceBlockClient(BlockPos blockPos) {
double diffX = blockPos.getX() + 0.5 - Wrapper.INSTANCE.player().posX;
double diffY = //0.5
blockPos.getY() + 0.0 - (Wrapper.INSTANCE.player().posY + Wrapper.INSTANCE.player().getEyeHeight());
double diffZ = blockPos.getZ() + 0.5 - Wrapper.INSTANCE.player().posZ;
double dist = MathHelper.sqrt(diffX * diffX + diffZ * diffZ);
float yaw =
(float)(Math.atan2(diffZ, diffX) * 180.0D / Math.PI) - 90.0F;
float pitch = (float)-(Math.atan2(diffY, dist) * 180.0D / Math.PI);
Wrapper.INSTANCE.player().rotationYaw = Wrapper.INSTANCE.player().rotationYaw
+ MathHelper.wrapDegrees(yaw - Wrapper.INSTANCE.player().rotationYaw);
Wrapper.INSTANCE.player().rotationPitch = Wrapper.INSTANCE.player().rotationPitch
+ MathHelper.wrapDegrees(pitch -Wrapper.INSTANCE.player().rotationPitch);
}
public static void faceBlockPacket(BlockPos blockPos) {
double diffX = blockPos.getX() + 0.5 - Wrapper.INSTANCE.player().posX;
double diffY = //0.5
blockPos.getY() + 0.0 - (Wrapper.INSTANCE.player().posY + Wrapper.INSTANCE.player().getEyeHeight());
double diffZ = blockPos.getZ() + 0.5 - Wrapper.INSTANCE.player().posZ;
double dist = MathHelper.sqrt(diffX * diffX + diffZ * diffZ);
float yaw =
(float)(Math.atan2(diffZ, diffX) * 180.0D / Math.PI) - 90.0F;
float pitch = (float)-(Math.atan2(diffY, dist) * 180.0D / Math.PI);
Wrapper.INSTANCE.player().connection.sendPacket(new CPacketPlayer.Rotation(
Wrapper.INSTANCE.player().rotationYaw
+ MathHelper.wrapDegrees(yaw - Wrapper.INSTANCE.player().rotationYaw),
Wrapper.INSTANCE.player().rotationPitch
+ MathHelper.wrapDegrees(pitch - Wrapper.INSTANCE.player().rotationPitch),
Wrapper.INSTANCE.player().onGround));
}
public static void faceBlockClientHorizontally(BlockPos blockPos) {
double diffX = blockPos.getX() + 0.5 - Wrapper.INSTANCE.player().posX;
double diffZ = blockPos.getZ() + 0.5 - Wrapper.INSTANCE.player().posZ;
float yaw =
(float)(Math.atan2(diffZ, diffX) * 180.0D / Math.PI) - 90.0F;
Wrapper.INSTANCE.player().rotationYaw = Wrapper.INSTANCE.player().rotationYaw
+ MathHelper.wrapDegrees(yaw - Wrapper.INSTANCE.player().rotationYaw);
}
public static float getPlayerBlockDistance(BlockPos blockPos) {
return getPlayerBlockDistance(blockPos.getX(), blockPos.getY(),
blockPos.getZ());
}
public static float getPlayerBlockDistance(double posX, double posY,
double posZ)
{
float xDiff = (float)(Wrapper.INSTANCE.player().posX - posX);
float yDiff = (float)(Wrapper.INSTANCE.player().posY - posY);
float zDiff = (float)(Wrapper.INSTANCE.player().posZ - posZ);
return getBlockDistance(xDiff, yDiff, zDiff);
}
public static float getBlockDistance(float xDiff, float yDiff, float zDiff)
{
return MathHelper.sqrt(
(xDiff - 0.5F) * (xDiff - 0.5F) + (yDiff - 0.5F) * (yDiff - 0.5F)
+ (zDiff - 0.5F) * (zDiff - 0.5F));
}
public static float getHorizontalPlayerBlockDistance(BlockPos blockPos)
{
float xDiff = (float)(Wrapper.INSTANCE.player().posX - blockPos.getX());
float zDiff = (float)(Wrapper.INSTANCE.player().posZ - blockPos.getZ());
return MathHelper.sqrt(
(xDiff - 0.5F) * (xDiff - 0.5F) + (zDiff - 0.5F) * (zDiff - 0.5F));
}
public static boolean breakBlockSimple(BlockPos pos)
{
EnumFacing side = null;
EnumFacing[] sides = EnumFacing.values();
Vec3d eyesPos = Utils.getEyesPos();
Vec3d relCenter = getState(pos).getBoundingBox(Wrapper.INSTANCE.world(), pos).getCenter();
Vec3d center = new Vec3d(pos).add(relCenter);
Vec3d[] hitVecs = new Vec3d[sides.length];
for(int i = 0; i < sides.length; i++)
{
Vec3i dirVec = sides[i].getDirectionVec();
Vec3d relHitVec = new Vec3d(relCenter.x * dirVec.getX(),
relCenter.y * dirVec.getY(),
relCenter.z * dirVec.getZ());
hitVecs[i] = center.add(relHitVec);
}
for(int i = 0; i < sides.length; i++)
{
if(Wrapper.INSTANCE.world().rayTraceBlocks(eyesPos, hitVecs[i], false,
true, false) != null)
continue;
side = sides[i];
break;
}
if(side == null)
{
double distanceSqToCenter = eyesPos.squareDistanceTo(center);
for(int i = 0; i < sides.length; i++)
{
if(eyesPos.squareDistanceTo(hitVecs[i]) >= distanceSqToCenter)
continue;
side = sides[i];
break;
}
}
if(side == null)
side = sides[0];
Utils.faceVectorPacket(hitVecs[side.ordinal()]);
if(!Wrapper.INSTANCE.controller().onPlayerDamageBlock(pos, side))
return false;
Wrapper.INSTANCE.sendPacket(new CPacketAnimation(EnumHand.MAIN_HAND));
return true;
}
public static void breakBlocksPacketSpam(Iterable<BlockPos> blocks)
{
Vec3d eyesPos = Utils.getEyesPos();
NetHandlerPlayClient connection = Wrapper.INSTANCE.player().connection;
for(BlockPos pos : blocks)
{
Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5);
double distanceSqPosVec = eyesPos.squareDistanceTo(posVec);
for(EnumFacing side : EnumFacing.values())
{
Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5));
if(eyesPos.squareDistanceTo(hitVec) >= distanceSqPosVec)
continue;
connection.sendPacket(new CPacketPlayerDigging(
Action.START_DESTROY_BLOCK, pos, side));
connection.sendPacket(new CPacketPlayerDigging(
Action.STOP_DESTROY_BLOCK, pos, side));
break;
}
}
}
public static LinkedList<BlockPos> findBlocksNearEntity(EntityLivingBase entity, int blockId, int blockMeta, int distance) {
LinkedList<BlockPos> blocks = new LinkedList<BlockPos>();
for (int x = (int) Wrapper.INSTANCE.player().posX - distance; x <= (int) Wrapper.INSTANCE.player().posX + distance; ++x) {
for (int z = (int) Wrapper.INSTANCE.player().posZ - distance; z <= (int) Wrapper.INSTANCE.player().posZ + distance; ++z) {
int height = Wrapper.INSTANCE.world().getHeight(x, z);
block: for (int y = 0; y <= height; ++y) {
BlockPos blockPos = new BlockPos(x, y, z);
IBlockState blockState = Wrapper.INSTANCE.world().getBlockState(blockPos);
if(blockId == -1 || blockMeta == -1) {
blocks.add(blockPos);
continue block;
}
int id = Block.getIdFromBlock(blockState.getBlock());
int meta = blockState.getBlock().getMetaFromState(blockState);
if(id == blockId && meta == blockMeta) {
blocks.add(blockPos);
continue block;
}
}
}
}
return blocks;
}
public static boolean isIntercepted(BlockPos blockPos) {
for (Entity entity : mc.world.loadedEntityList) {
if (entity instanceof EntityItem || entity instanceof EntityEnderCrystal || !new AxisAlignedBB(blockPos).intersects(entity.getEntityBoundingBox())) continue;
return true;
}
return false;
}
}
| 412 | 0.919339 | 1 | 0.919339 | game-dev | MEDIA | 0.906843 | game-dev | 0.863576 | 1 | 0.863576 |
drodin/Stratagus | 3,634 | src/spell/spell_demolish.cpp | // _________ __ __
// / _____// |_____________ _/ |______ ____ __ __ ______
// \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
// / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ |
// /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
// \/ \/ \//_____/ \/
// ______________________ ______________________
// T H E W A R B E G I N S
// Stratagus - A free fantasy real time strategy game engine
//
/**@name spell_demolish.cpp - The spell demolish. */
//
// (c) Copyright 1998-2012 by Vladi Belperchinov-Shabanski, Lutz Sammer,
// Jimmy Salmon, and Joris DAUPHIN
//
// 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; only version 2 of the 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.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
//@{
#include "stratagus.h"
#include "spell/spell_demolish.h"
#include "script.h"
#include "map.h"
#include "unit.h"
#include "unit_find.h"
/* virtual */ void Spell_Demolish::Parse(lua_State *l, int startIndex, int endIndex)
{
for (int j = startIndex; j < endIndex; ++j) {
const char *value = LuaToString(l, -1, j + 1);
++j;
if (!strcmp(value, "range")) {
this->Range = LuaToNumber(l, -1, j + 1);
} else if (!strcmp(value, "damage")) {
this->Damage = LuaToNumber(l, -1, j + 1);
} else {
LuaError(l, "Unsupported demolish tag: %s" _C_ value);
}
}
}
/**
** Cast demolish
** @param caster Unit that casts the spell
** @param spell Spell-type pointer
** @param target Target unit that spell is addressed to
** @param goalPos tilePos of target spot when/if target does not exist
**
** @return =!0 if spell should be repeated, 0 if not
*/
/* virtual */ int Spell_Demolish::Cast(CUnit &caster, const SpellType &, CUnit *&, const Vec2i &goalPos)
{
// Allow error margins. (Lame, I know)
const Vec2i offset(this->Range + 2, this->Range + 2);
Vec2i minpos = goalPos - offset;
Vec2i maxpos = goalPos + offset;
Map.FixSelectionArea(minpos, maxpos);
//
// Terrain effect of the explosion
//
Vec2i ipos;
for (ipos.x = minpos.x; ipos.x <= maxpos.x; ++ipos.x) {
for (ipos.y = minpos.y; ipos.y <= maxpos.y; ++ipos.y) {
const CMapField &mf = *Map.Field(ipos);
if (SquareDistance(ipos, goalPos) > square(this->Range)) {
// Not in circle range
continue;
} else if (mf.isAWall() || mf.RockOnMap() || mf.ForestOnMap()) {
Map.ClearTile(ipos);
}
}
}
//
// Effect of the explosion on units. Don't bother if damage is 0
//
if (this->Damage) {
std::vector<CUnit *> table;
SelectFixed(minpos, maxpos, table);
for (size_t i = 0; i != table.size(); ++i) {
CUnit &unit = *table[i];
if (unit.Type->UnitType != UnitTypeFly && unit.IsAlive()
&& unit.MapDistanceTo(goalPos) <= this->Range) {
// Don't hit flying units!
HitUnit(&caster, unit, this->Damage);
}
}
}
return 1;
}
//@}
| 412 | 0.910124 | 1 | 0.910124 | game-dev | MEDIA | 0.9794 | game-dev | 0.976184 | 1 | 0.976184 |
fholger/crysis_vrmod | 39,432 | Code/ItemResource.cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 30:8:2005 12:30 : Created by Mrcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "Item.h"
#include "ItemSharedParams.h"
#include <ICryAnimation.h>
#include <ISound.h>
#include <CryPath.h>
#include <IVehicleSystem.h>
#include "Actor.h"
#include "Game.h"
#include "GameCVars.h"
#include "Player.h"
#include "VR/VRRenderer.h"
//------------------------------------------------------------------------
void CItem::RemoveEntity(bool force)
{
if (gEnv->pSystem->IsEditor() && !force)
Hide(true);
else if (IsServer() || force)
gEnv->pEntitySystem->RemoveEntity(GetEntityId());
}
//------------------------------------------------------------------------
bool CItem::CreateCharacterAttachment(int slot, const char *name, int type, const char *bone)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return false;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (pAttachment)
{
// GameWarning("Item '%s' trying to create attachment '%s' which already exists!", GetEntity()->GetName(), name);
return false;
}
pAttachment = pAttachmentManager->CreateAttachment(name, type, bone);
if (!pAttachment)
{
if (type == CA_BONE)
GameWarning("Item '%s' failed to create attachment '%s' on bone '%s'!", GetEntity()->GetName(), name, bone);
return false;
}
return true;
}
//------------------------------------------------------------------------
void CItem::DestroyCharacterAttachment(int slot, const char *name)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
pAttachmentManager->RemoveAttachmentByName(name);
}
//------------------------------------------------------------------------
void CItem::ResetCharacterAttachment(int slot, const char *name)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to reset attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
pAttachment->ClearBinding();
}
//------------------------------------------------------------------------
const char *CItem::GetCharacterAttachmentBone(int slot, const char *name)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return 0;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to get attachment bone on '%s' which does not exist!", GetEntity()->GetName(), name);
return 0;
}
return pCharacter->GetISkeletonPose()->GetJointNameByID(pAttachment->GetBoneID());
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachment(int slot, const char *name, IEntity *pEntity, int flags)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to attach entity on '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
CEntityAttachment *pEntityAttachment = new CEntityAttachment();
pEntityAttachment->SetEntityId(pEntity->GetId());
pAttachment->AddBinding(pEntityAttachment);
pAttachment->HideAttachment(0);
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachment(int slot, const char *name, IStatObj *pObj, int flags)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to attach static object on '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
CCGFAttachment *pStatAttachment = new CCGFAttachment();
pStatAttachment->pObj = pObj;
pAttachment->AddBinding(pStatAttachment);
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachment(int slot, const char *name, ICharacterInstance *pAttachedCharacter, int flags)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to attach character on '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
CCHRAttachment *pCharacterAttachment = new CCHRAttachment();
pCharacterAttachment->m_pCharInstance = pAttachedCharacter;
// sub skin ?
if (pAttachment->GetType() == CA_SKIN)
{
pAttachment->AddBinding(pCharacterAttachment);
}
else
{
pAttachment->AddBinding(pCharacterAttachment);
}
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachment(int slot, const char *name, CDLight &light, int flags)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to attach light on '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
CLightAttachment *pLightAttachment = new CLightAttachment();
pLightAttachment->LoadLight(light);
pAttachment->AddBinding(pLightAttachment);
pAttachment->HideAttachment(0);
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachment(int slot, const char *name, IEntity *pEntity, int objSlot, int flags)
{
SEntitySlotInfo info;
if (!pEntity->GetSlotInfo(objSlot, info))
return;
if (info.pCharacter)
SetCharacterAttachment(slot, name, info.pCharacter, flags);
else if (info.pStatObj)
SetCharacterAttachment(slot, name, info.pStatObj, flags);
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachmentLocalTM(int slot, const char *name, const Matrix34 &tm)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to set local TM on attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
pAttachment->SetAttRelativeDefault( QuatT(tm));
}
//------------------------------------------------------------------------
void CItem::SetCharacterAttachmentWorldTM(int slot, const char *name, const Matrix34 &tm)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to set world TM on attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
// Matrix34 boneWorldMatrix = GetEntity()->GetSlotWorldTM(slot) * pCharacter->GetISkeleton()->GetAbsJMatrixByID(pAttachment->GetBoneID());
Matrix34 boneWorldMatrix = GetEntity()->GetSlotWorldTM(slot) * Matrix34(pCharacter->GetISkeletonPose()->GetAbsJointByID(pAttachment->GetBoneID()) );
Matrix34 localAttachmentMatrix = (boneWorldMatrix.GetInverted()*tm);
pAttachment->SetAttRelativeDefault(QuatT(localAttachmentMatrix));
}
//------------------------------------------------------------------------
Matrix34 CItem::GetCharacterAttachmentLocalTM(int slot, const char *name)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return Matrix34::CreateIdentity();;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to get local TM on attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return Matrix34::CreateIdentity();
}
return Matrix34(pAttachment->GetAttRelativeDefault());
}
//------------------------------------------------------------------------
Matrix34 CItem::GetCharacterAttachmentWorldTM(int slot, const char *name)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return Matrix34::CreateIdentity();
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to get local TM on attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return Matrix34::CreateIdentity();
}
return Matrix34(pAttachment->GetAttWorldAbsolute());
}
//------------------------------------------------------------------------
void CItem::HideCharacterAttachment(int slot, const char *name, bool hide)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
IAttachmentManager *pAttachmentManager = pCharacter->GetIAttachmentManager();
IAttachment *pAttachment = pAttachmentManager->GetInterfaceByName(name);
if (!pAttachment)
{
GameWarning("Item '%s' trying to hide attachment '%s' which does not exist!", GetEntity()->GetName(), name);
return;
}
pAttachment->HideAttachment(hide?1:0);
}
//------------------------------------------------------------------------
void CItem::HideCharacterAttachmentMaster(int slot, const char *name, bool hide)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter)
return;
pCharacter->HideMaster(hide?1:0);
}
//------------------------------------------------------------------------
void CItem::CreateAttachmentHelpers(int slot)
{
for (THelperVector::iterator it = m_sharedparams->helpers.begin(); it != m_sharedparams->helpers.end(); it++)
{
if (it->slot != slot)
continue;
CreateCharacterAttachment(slot, it->name.c_str(), CA_BONE, it->bone.c_str());
}
if (slot == eIGS_FirstPerson)
CreateCharacterAttachment(slot, ITEM_ARMS_ATTACHMENT_NAME, CA_SKIN, 0);
}
//------------------------------------------------------------------------
void CItem::DestroyAttachmentHelpers(int slot)
{
for (THelperVector::iterator it = m_sharedparams->helpers.begin(); it != m_sharedparams->helpers.end(); ++it)
{
if (it->slot != slot)
continue;
DestroyCharacterAttachment(slot, it->name.c_str());
}
}
//------------------------------------------------------------------------
const CItem::THelperVector& CItem::GetAttachmentHelpers()
{
return m_sharedparams->helpers;
}
//------------------------------------------------------------------------
bool CItem::SetGeometry(int slot, const ItemString& name, const Vec3& poffset, const Ang3& aoffset, float scale, bool forceReload)
{
bool changedfp=false;
switch(slot)
{
case eIGS_Arms:
{
if (!name || forceReload)
{
GetEntity()->FreeSlot(slot);
#ifndef ITEM_USE_SHAREDSTRING
m_geometry[slot].resize(0);
#else
m_geometry[slot].reset();
#endif
}
ResetCharacterAttachment(eIGS_FirstPerson, ITEM_ARMS_ATTACHMENT_NAME);
ICharacterInstance *pCharacter=0;
if (name && name[0])
{
if (name != m_geometry[slot])
GetEntity()->LoadCharacter(slot, name);
DrawSlot(eIGS_Arms, false);
pCharacter = GetEntity()->GetCharacter(eIGS_Arms);
}
else if (m_pForcedArms)
{
pCharacter = m_pForcedArms;
}
else
{
int armsId=m_stats.hand==eIH_Right?0:1;
pCharacter = GetOwnerActor()?GetOwnerActor()->GetFPArms(armsId):0;
}
if (pCharacter)
{
pCharacter->SetFlags(pCharacter->GetFlags()&(~CS_FLAG_UPDATE));
SetCharacterAttachment(eIGS_FirstPerson, ITEM_ARMS_ATTACHMENT_NAME, pCharacter, 0);
}
}
break;
case eIGS_FirstPerson:
case eIGS_ThirdPerson:
default:
{
if (!name || forceReload)
{
GetEntity()->FreeSlot(slot);
#ifndef ITEM_USE_SHAREDSTRING
m_geometry[slot].resize(0);
#else
m_geometry[slot].reset();
#endif
}
DestroyAttachmentHelpers(slot);
if (name && name[0])
{
if (m_geometry[slot] != name)
{
const char* ext = PathUtil::GetExt(name.c_str());
if ((stricmp(ext, "chr") == 0) || (stricmp(ext, "cdf") == 0) || (stricmp(ext, "cga") == 0) )
GetEntity()->LoadCharacter(slot, name, 0);
else
GetEntity()->LoadGeometry(slot, name, 0, 0);
changedfp=slot==eIGS_FirstPerson;
}
CreateAttachmentHelpers(slot);
SetDefaultIdleAnimation(slot, g_pItemStrings->idle);
}
if (slot == eIGS_FirstPerson)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(eIGS_FirstPerson);
if (pCharacter)
{
pCharacter->SetFlags(pCharacter->GetFlags()&(~CS_FLAG_UPDATE));
}
}
else if (slot == eIGS_Destroyed)
DrawSlot(eIGS_Destroyed, false);
}
break;
}
Matrix34 slotTM;
slotTM = Matrix34::CreateRotationXYZ(aoffset);
slotTM.Scale(Vec3(scale, scale, scale));
slotTM.SetTranslation(poffset);
GetEntity()->SetSlotLocalTM(slot, slotTM);
if (changedfp && m_stats.mounted)
{
PlayAction(m_idleAnimation[eIGS_FirstPerson], 0, true);
ForceSkinning(true);
if (!m_mountparams.pivot.empty())
{
Matrix34 tm=GetEntity()->GetSlotLocalTM(eIGS_FirstPerson, false);
Vec3 pivot = GetSlotHelperPos(eIGS_FirstPerson, m_mountparams.pivot.c_str(), false);
tm.AddTranslation(pivot);
GetEntity()->SetSlotLocalTM(eIGS_FirstPerson, tm);
}
GetEntity()->InvalidateTM();
}
m_geometry[slot] = name ? name : "";
ReAttachAccessories();
return true;
}
//------------------------------------------------------------------------
void CItem::SetDefaultIdleAnimation(int slot, const ItemString& actionName)
{
TActionMap::iterator it = m_sharedparams->actions.find(CONST_TEMPITEM_STRING(actionName));
if (it == m_sharedparams->actions.end())
{
// GameWarning("Action '%s' not found on item '%s'!", actionName, GetEntity()->GetName());
return;
}
SAction &action = it->second;
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (pCharacter)
{
if (action.animation[slot].size() > 0)
{
TempResourceName name;
FixResourceName(action.animation[slot][0].name, name, 0);
}
//changed by ivo!
//pCharacter->SetDefaultIdleAnimation(0, name.c_str());
}
m_idleAnimation[slot] = actionName;
}
//------------------------------------------------------------------------
void CItem::ForceSkinning(bool always)
{
for (int slot=0; slot<eIGS_Last; slot++)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (pCharacter)
{
Matrix34 m34=GetEntity()->GetSlotWorldTM(slot);
QuatT renderLocation = QuatT(m34);
Vec3 CharOffset = GetEntity()->GetSlotLocalTM(slot,false).GetTranslation();
pCharacter->GetISkeletonPose()->SetForceSkeletonUpdate(7);
pCharacter->SkeletonPreProcess(renderLocation, renderLocation, gVRRenderer->GetCurrentViewCamera(), 0x55);
pCharacter->SkeletonPostProcess(renderLocation, renderLocation, 0, 0.0f, 0x55 );
if (!always)
pCharacter->GetISkeletonPose()->SetForceSkeletonUpdate(0);
}
}
}
//------------------------------------------------------------------------
void CItem::EnableHiddenSkinning(bool enable)
{
/*
for (int slot=0; slot<eIGS_Last; slot++)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (pCharacter)
{
if (enable)
pCharacter->SetFlags(pCharacter->GetFlags()|CS_FLAG_UPDATE_ALWAYS);
else
pCharacter->SetFlags(pCharacter->GetFlags()&(~CS_FLAG_UPDATE_ALWAYS));
}
}
*/
}
//------------------------------------------------------------------------
void CItem::FixResourceName(const ItemString& inName, TempResourceName& name, int flags, const char *hand, const char *suffix, const char *pose, const char *pov, const char *env)
{
// the whole thing of fixing is not nice, but at least we don't allocate too often
// StringHelper<TempResourceName::SIZE> name (inName.c_str(), inName.length());
name.assign(inName.c_str(), inName.length());
if (!hand)
{
if (m_stats.hand == eIH_Left)
hand = "left";
else
hand = "right";
}
name.replace("%hand%", hand);
if (m_stats.hand == eIH_Left)
name.replace("%offhand%", "right");
else
name.replace("%offhand%", "left");
if (!suffix)
suffix = m_actionSuffix.c_str();
name.replace("%suffix%", suffix);
if (!pose)
{
if (!m_params.pose.empty())
pose = m_params.pose.c_str();
else
pose = "";
}
name.replace("%pose%", "");
if (!pov)
{
if ((m_stats.fp || flags&eIPAF_ForceFirstPerson) && !(flags&eIPAF_ForceThirdPerson))
pov = ITEM_FIRST_PERSON_TOKEN;
else
pov = ITEM_THIRD_PERSON_TOKEN;
}
name.replace("%pov%", pov);
if (!env)
{
// Instead if the weapons sound proxy, the owners is used to retrieve the tail name
IEntity* pOwner = GetOwner();
if (GetIWeapon() && pOwner) // restricting to weapon sounds only
{
if (pOwner)
{
IEntitySoundProxy *pSoundProxy = (IEntitySoundProxy *)pOwner->GetProxy(ENTITY_PROXY_SOUND);
if (!pSoundProxy)
pSoundProxy = (IEntitySoundProxy *)pOwner->CreateProxy(ENTITY_PROXY_SOUND);
if (pSoundProxy)
{
// check for a roof 10m above the Owner
// recalculate visibility when owner move more than 2 meters
pSoundProxy->CheckVisibilityForTailName(10.0f, 2.0f);
env = pSoundProxy->GetTailName();
}
}
}
if (!env || !env[0] || !stricmp("indoor", env))
name.replace("%env%", "");
else
{
static const size_t MAX_LEN = 256;
char envstr[MAX_LEN];
envstr[0] = '_';
strncpy(envstr+1, env, MAX_LEN-1); // no 0 pad, if MAX_LEN-1 are copied
envstr[MAX_LEN-1] = '\0'; // always zero-terminate
name.replace("%env%", envstr);
}
}
else
name.replace("%env%", env);
}
//------------------------------------------------------------------------
tSoundID CItem::PlayAction(const ItemString& actionName, int layer, bool loop, uint flags, float speedOverride)
{
if (!m_enableAnimations)
return -1;
TActionMap::iterator it = m_sharedparams->actions.find(CONST_TEMPITEM_STRING(actionName));
if (it == m_sharedparams->actions.end())
{
// GameWarning("Action '%s' not found on item '%s'!", actionName, GetEntity()->GetName());
for (int i=0;i<eIGS_Last;i++)
{
m_animationTime[i]=0;
m_animationSpeed[i]=1.0f;
m_animationEnd[i]=0;
}
return 0;
}
bool fp = m_stats.fp;
if (m_parentId)
{
CItem *pParent=static_cast<CItem *>(m_pItemSystem->GetItem(m_parentId));
if (pParent)
fp=pParent->GetStats().fp;
}
if (flags&eIPAF_ForceFirstPerson)
fp = true;
if (flags&eIPAF_ForceThirdPerson)
fp = false;
int sid=fp?eIGS_FirstPerson:eIGS_ThirdPerson;
SAction &action = it->second;
tSoundID result = INVALID_SOUNDID;
if ((flags&eIPAF_Sound) && !action.sound[sid].name.empty() && IsSoundEnabled() && g_pGameCVars->i_soundeffects)
{
int nSoundFlags = FLAG_SOUND_DEFAULT_3D;
nSoundFlags |= flags&eIPAF_SoundStartPaused?FLAG_SOUND_START_PAUSED:0;
IEntitySoundProxy *pSoundProxy = GetSoundProxy(true);
//GetSound proxy from dualwield master if neccesary
if(IsDualWieldSlave())
{
CItem* pMaster = static_cast<CItem*>(GetDualWieldMaster());
if(pMaster)
{
pSoundProxy = pMaster->GetSoundProxy(true);
}
}
EntityId pSkipEnts[3];
int nSkipEnts = 0;
// TODO for Marcio :)
// check code changes
// Skip the Item
pSkipEnts[nSkipEnts] = GetEntity()->GetId();
++nSkipEnts;
// Skip the Owner
if (GetOwner())
{
pSkipEnts[nSkipEnts] = GetOwner()->GetId();
++nSkipEnts;
}
if (pSoundProxy)
{
TempResourceName name;
FixResourceName(action.sound[sid].name, name, flags);
//nSoundFlags = nSoundFlags | (fp?FLAG_SOUND_DEFAULT_3D|FLAG_SOUND_RELATIVE:FLAG_SOUND_DEFAULT_3D);
Vec3 vOffset(0,0,0);
if (fp)
vOffset.x = 0.3f; // offset for first person weapon to the front
if (!g_pGameCVars->i_staticfiresounds)
{
result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
ISound *pSound = pSoundProxy->GetSound(result);
if (pSound && action.sound[sid].sphere>0.0f)
pSound->SetSphereSpec(action.sound[sid].sphere);
}
else
{
SInstanceAudio *pInstanceAudio=0;
if (action.sound[sid].isstatic)
{
TInstanceActionMap::iterator iit = m_instanceActions.find(CONST_TEMPITEM_STRING(actionName));
if (iit == m_instanceActions.end())
{
std::pair<TInstanceActionMap::iterator, bool> insertion=m_instanceActions.insert(TInstanceActionMap::value_type(actionName, SInstanceAction()));
pInstanceAudio=&insertion.first->second.sound[sid];
}
else
pInstanceAudio=&iit->second.sound[sid];
}
if (pInstanceAudio && (pInstanceAudio->id != INVALID_SOUNDID) && (name != pInstanceAudio->static_name))
ReleaseStaticSound(pInstanceAudio);
if (!pInstanceAudio || pInstanceAudio->id == INVALID_SOUNDID)
{
result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
ISound *pSound = pSoundProxy->GetSound(result);
if (pSound && action.sound[sid].sphere>0.0f)
pSound->SetSphereSpec(action.sound[sid].sphere);
}
if (action.sound[sid].isstatic)
{
if (pInstanceAudio->id == INVALID_SOUNDID)
{
if(pSoundProxy->SetStaticSound(result, true))
{
pInstanceAudio->id = result;
pInstanceAudio->static_name = name;
pInstanceAudio->synch = action.sound[sid].issynched;
}
}
else
{
ISound *pSound = pSoundProxy->GetSound(pInstanceAudio->id);
if (pSound)
pSound->Play(1.0, true, true, pSoundProxy);
}
}
}
if (action.sound[sid].airadius > 0.0f)
{
IEntity *pOwner = GetOwner();
// associate sound event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
IAIObject *pAIOwner = pOwner ? pOwner->GetAI() : NULL;
CActor *pOwnerActor = GetOwnerActor();
if(pOwnerActor)
{
IVehicle* pOvnerVehicle = pOwnerActor->GetLinkedVehicle();
if(pOvnerVehicle && pOvnerVehicle->GetEntity() && pOvnerVehicle->GetEntity()->GetAI())
pAIOwner = pOvnerVehicle->GetEntity()->GetAI();
}
if (gEnv->pAISystem)
gEnv->pAISystem->SoundEvent(GetEntity()->GetWorldPos(), action.sound[sid].airadius, AISE_WEAPON, pAIOwner);
}
}
}
if (flags&eIPAF_Animation)
{
TempResourceName name;
// generate random number only once per call to allow animations to
// match across geometry slots (like first person and third person)
float randomNumber = Random();
for (int i=0; i<eIGS_Last; i++)
{
if (!(flags&(1<<i)))
continue;
int nanimations=action.animation[i].size();
if (nanimations <= 0)
continue;
int anim = int( randomNumber * float(nanimations) );
if (action.animation[i][anim].name.empty())
continue;
FixResourceName(action.animation[i][anim].name, name, flags);
if ((i == eIGS_Owner) || (i == eIGS_OwnerLooped))
{
if (!action.animation[i][anim].name.empty())
{
bool looping=(eIGS_OwnerLooped==i);
CActor *pOwner = GetOwnerActor();
if (pOwner)
{
if (IsDualWield() && !m_params.dual_wield_pose.empty())
pOwner->PlayAction(name, m_params.dual_wield_pose.c_str(), looping);
else
pOwner->PlayAction(name, m_params.pose.c_str(), looping);
}
}
continue;
}
else if (i == eIGS_OffHand)
{
if (!action.animation[eIGS_OffHand][anim].name.empty())
{
CActor *pOwner = GetOwnerActor();
if (pOwner)
{
CItem *pOffHand = pOwner->GetItemByClass(CItem::sOffHandClass);
if (pOffHand && pOffHand!=this)
{
uint ohflags=eIPAF_Default;
if (action.animation[eIGS_OffHand][anim].blend==0.0f)
ohflags|=eIPAF_NoBlend;
pOffHand->PlayAction(action.animation[eIGS_OffHand][anim].name, 0, false, ohflags);
}
}
}
continue;
}
SAnimation &animation=action.animation[i][anim];
if (!animation.name.empty())
{
float blend = animation.blend;
if (flags&eIPAF_NoBlend)
blend = 0.0f;
if (speedOverride > 0.0f)
PlayAnimationEx(name, i, layer, loop, blend, speedOverride, flags);
else
PlayAnimationEx(name, i, layer, loop, blend, animation.speed, flags);
}
if ((m_stats.fp || m_stats.viewmode&eIVM_FirstPerson) && i==eIGS_FirstPerson && !animation.camera_helper.empty())
{
m_camerastats.animating=true;
m_camerastats.helper=animation.camera_helper;
m_camerastats.position=animation.camera_pos;
m_camerastats.rotation=animation.camera_rot;
m_camerastats.follow=animation.camera_follow;
m_camerastats.reorient=animation.camera_reorient;
}
else if (m_camerastats.animating)
m_camerastats=SCameraAnimationStats();
}
}
if (flags&eIPAF_Effect && !action.effect[sid].name.empty())
{
// change this to attach, if needed
SpawnEffect(sid, action.effect[sid].name.c_str(), action.effect[sid].helper.c_str());
}
if (action.children)
{
for (TAccessoryMap::iterator ait=m_accessories.begin(); ait!=m_accessories.end(); ait++)
{
EntityId aId=(EntityId)ait->second;
CItem *pAccessory=static_cast<CItem *>(m_pItemSystem->GetItem(aId));
if (pAccessory)
pAccessory->PlayAction(actionName, layer, loop, flags, speedOverride);
}
}
return result;
}
//------------------------------------------------------------------------
void CItem::PlayAnimation(const char* animationName, int layer, bool loop, uint flags)
{
for (int i=0; i<eIGS_Last; i++)
{
if (!(flags&1<<i))
continue;
PlayAnimationEx(animationName, i, layer, loop, 0.175f, 1.0f, flags);
}
}
//------------------------------------------------------------------------
void CItem::PlayAnimationEx(const char* animationName, int slot, int layer, bool loop, float blend, float speed, uint flags)
{
bool start=true;
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(slot);
if (!pCharacter && slot==eIGS_FirstPerson && ((m_stats.viewmode&eIVM_FirstPerson)==0))
{
start=false;
int idx = 0;
if (m_stats.hand == eIH_Right)
idx = 1;
else if (m_stats.hand == eIH_Left)
idx = 2;
if (m_fpgeometry[idx].name.empty())
idx = 0;
pCharacter = m_pItemSystem->GetCachedCharacter(m_fpgeometry[idx].name.c_str());
}
if (pCharacter && animationName)
{
ISkeletonAnim* pSkeletonAnim = pCharacter->GetISkeletonAnim();
if (flags&eIPAF_CleanBlending)
{
while(pSkeletonAnim->GetNumAnimsInFIFO(layer)>1)
{
if (!pSkeletonAnim->RemoveAnimFromFIFO(layer, pSkeletonAnim->GetNumAnimsInFIFO(layer)-1))
break;
}
}
if (flags&eIPAF_NoBlend)
blend = 0.0f;
if (start)
{
CryCharAnimationParams params;
params.m_fTransTime = blend;
params.m_nLayerID = layer;
params.m_nFlags = (loop?CA_LOOP_ANIMATION:0)|(flags&eIPAF_RestartAnimation?CA_ALLOW_ANIM_RESTART:0)|(flags&eIPAF_RepeatLastFrame?CA_REPEAT_LAST_KEY:0);
pSkeletonAnim->StartAnimation(animationName, 0, 0,0, params);
pSkeletonAnim->SetLayerUpdateMultiplier(layer, speed);
//pCharacter->GetISkeleton()->SetDebugging( true );
}
float duration=0.0f;
int animationId = pCharacter->GetIAnimationSet()->GetAnimIDByName(animationName);
if (animationId>=0)
duration = pCharacter->GetIAnimationSet()->GetDuration_sec(animationId);
m_animationTime[slot] = (uint)(duration*1000.0f/speed);
m_animationEnd[slot] = (uint)(gEnv->pTimer->GetCurrTime()*1000.0f)+m_animationTime[slot];
m_animationSpeed[slot] = speed;
}
}
//------------------------------------------------------------------------
void CItem::PlayLayer(const ItemString& layerName, int flags, bool record)
{
TLayerMap::iterator it = m_sharedparams->layers.find(CONST_TEMPITEM_STRING(layerName));
if (it == m_sharedparams->layers.end())
return;
TempResourceName tempResourceName;
for (int i=0; i<eIGS_Last; i++)
{
if (!(flags&1<<i))
continue;
SLayer &layer = it->second;
if (!layer.name[i].empty())
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
{
CryCharAnimationParams params;
float blend = 0.125f;
if (flags&eIPAF_NoBlend)
blend = 0.0f;
params.m_fTransTime = blend;
params.m_fLayerBlendIn = 0;
params.m_nLayerID = layer.id[i];
params.m_nFlags = CA_LOOP_ANIMATION;
FixResourceName(layer.name[i], tempResourceName, flags);
ISkeletonAnim* pSkeletonAnim=pCharacter->GetISkeletonAnim();
// pSkeleton->SetRedirectToLayer0(1);
pSkeletonAnim->StartAnimation(tempResourceName, 0, 0,0, params);
if (layer.bones.empty())
{
pCharacter->GetISkeletonPose()->SetLayerMask(layer.id[i], 1);
}
else
{
pCharacter->GetISkeletonPose()->SetLayerMask(layer.id[i], 0);
for (std::vector<ItemString>::iterator bit = layer.bones.begin(); bit != layer.bones.end(); bit++)
pCharacter->GetISkeletonPose()->SetJointMask(bit->c_str(), layer.id[i], 1);
}
}
}
}
if (record)
{
TActiveLayerMap::iterator ait = m_activelayers.find(CONST_TEMPITEM_STRING(layerName));
if (ait == m_activelayers.end())
m_activelayers.insert(TActiveLayerMap::value_type(layerName, flags));
}
}
//------------------------------------------------------------------------
void CItem::StopLayer(const ItemString& layerName, int flags, bool record)
{
TLayerMap::iterator it = m_sharedparams->layers.find(CONST_TEMPITEM_STRING(layerName));
if (it == m_sharedparams->layers.end())
return;
for (int i=0; i<eIGS_Last; i++)
{
if (!(flags&1<<i))
continue;
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
pCharacter->GetISkeletonAnim()->StopAnimationInLayer(it->second.id[i],0.0f);
}
if (record)
{
TActiveLayerMap::iterator ait = m_activelayers.find(CONST_TEMPITEM_STRING(layerName));
if (ait != m_activelayers.end())
m_activelayers.erase(ait);
}
}
//------------------------------------------------------------------------
void CItem::RestoreLayers()
{
for (TActiveLayerMap::iterator it = m_activelayers.begin(); it != m_activelayers.end(); it++)
PlayLayer(it->first, it->second, false);
for (TLayerMap::iterator lit = m_sharedparams->layers.begin(); lit != m_sharedparams->layers.end(); lit++)
{
if (lit->second.isstatic)
PlayLayer(lit->first, eIPAF_Default, false);
}
}
//------------------------------------------------------------------------
void CItem::ResetAnimation(int layer, uint flags)
{
for (int i=0; i<eIGS_Last; i++)
{
if (!(flags&1<<i))
continue;
if ((i == eIGS_Owner) || (i == eIGS_OwnerLooped))
continue;
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
pCharacter->GetISkeletonAnim()->StopAnimationsAllLayers();
}
}
//------------------------------------------------------------------------
uint CItem::GetCurrentAnimationTime(int slot)
{
return m_animationTime[slot];
}
//------------------------------------------------------------------------
uint CItem::GetCurrentAnimationEnd(int slot)
{
return m_animationEnd[slot];
}
//------------------------------------------------------------------------
uint CItem::GetCurrentAnimationStart(int slot)
{
return m_animationEnd[slot]-m_animationTime[slot];
}
//------------------------------------------------------------------------
void CItem::DrawSlot(int slot, bool bDraw, bool bNear)
{
uint flags = GetEntity()->GetSlotFlags(slot);
if (bDraw)
flags |= ENTITY_SLOT_RENDER;
else
flags &= ~ENTITY_SLOT_RENDER;
if (bNear)
flags |= ENTITY_SLOT_RENDER_NEAREST;
else
flags &= ~ENTITY_SLOT_RENDER_NEAREST;
GetEntity()->SetSlotFlags(slot, flags);
}
//------------------------------------------------------------------------
Vec3 CItem::GetSlotHelperPos(int slot, const char *helper, bool worldSpace, bool relative)
{
Vec3 position(0,0,0);
// if mounted force the slot to be 1st person
if (m_stats.mounted)
slot=eIGS_FirstPerson;
SEntitySlotInfo info;
if (GetEntity()->GetSlotInfo(slot, info))
{
if (info.pStatObj)
{
IStatObj *pStatsObj = info.pStatObj;
position = pStatsObj->GetHelperPos(helper);
position = GetEntity()->GetSlotLocalTM(slot, false).TransformPoint(position);
}
else if (info.pCharacter)
{
ICharacterInstance *pCharacter = info.pCharacter;
int16 id = pCharacter->GetISkeletonPose()->GetJointIDByName(helper);
if (id > -1)
{
if (relative)
position = pCharacter->GetISkeletonPose()->GetRelJointByID(id).t;
else
position = pCharacter->GetISkeletonPose()->GetAbsJointByID(id).t;
}
if (!relative)
position = GetEntity()->GetSlotLocalTM(slot, false).TransformPoint(position);
}
}
if (worldSpace)
return GetEntity()->GetWorldTM().TransformPoint(position);
return position;
}
//------------------------------------------------------------------------
const Matrix33 &CItem::GetSlotHelperRotation(int slot, const char *helper, bool worldSpace, bool relative)
{
// if mounted force the slot to be 1st person
if (m_stats.mounted)
slot=eIGS_FirstPerson;
static Matrix33 rotation;
rotation.SetIdentity();
IEntity* pEntity = GetEntity();
if(!pEntity)
return rotation;
SEntitySlotInfo info;
if (pEntity->GetSlotInfo(slot, info))
{
if (info.pStatObj)
{
IStatObj *pStatObj = info.pStatObj;
rotation = Matrix33(pStatObj->GetHelperTM(helper));
rotation.OrthonormalizeFast();
rotation = Matrix33(GetEntity()->GetSlotLocalTM(slot, false))*rotation;
}
else if (info.pCharacter)
{
ICharacterInstance *pCharacter = info.pCharacter;
if(!pCharacter)
return rotation;
int16 id = pCharacter->GetISkeletonPose()->GetJointIDByName(helper);
// if (id > -1) rotation = Matrix33(pCharacter->GetISkeleton()->GetAbsJMatrixByID(id));
if (id > -1)
{
if (relative)
rotation = Matrix33(pCharacter->GetISkeletonPose()->GetRelJointByID(id).q);
else
rotation = Matrix33(pCharacter->GetISkeletonPose()->GetAbsJointByID(id).q);
}
if (!relative)
rotation = Matrix33(pEntity->GetSlotLocalTM(slot, false))*rotation;
}
}
if (worldSpace)
rotation=Matrix33(pEntity->GetWorldTM())*rotation;
return rotation;
}
//------------------------------------------------------------------------
void CItem::StopSound(tSoundID id)
{
if (id == INVALID_SOUNDID)
return;
bool synchSound = false;
IEntitySoundProxy *pSoundProxy = GetSoundProxy(false);
if (pSoundProxy)
{
for (TInstanceActionMap::iterator it = m_instanceActions.begin(); it != m_instanceActions.end(); ++it)
{
SInstanceAction &action = it->second;
for (int i=0;i<2;i++)
{
if (action.sound[i].id == id)
{
pSoundProxy->SetStaticSound(id, false);
action.sound[i].id = INVALID_SOUNDID;
synchSound = action.sound[i].synch;
break;
}
}
}
if(synchSound)
pSoundProxy->StopSound(id, ESoundStopMode_OnSyncPoint);
else
pSoundProxy->StopSound(id);
}
}
//------------------------------------------------------------------------
void CItem::Quiet()
{
IEntitySoundProxy *pSoundProxy = GetSoundProxy(false);
if (pSoundProxy)
{
for (TInstanceActionMap::iterator it = m_instanceActions.begin(); it != m_instanceActions.end(); ++it)
{
SInstanceAction &action = it->second;
for (int i=0;i<2;i++)
{
if (action.sound[i].id != INVALID_SOUNDID)
{
pSoundProxy->SetStaticSound(action.sound[i].id, false);
action.sound[i].id = INVALID_SOUNDID;
}
}
}
pSoundProxy->StopAllSounds();
}
}
//------------------------------------------------------------------------
ISound *CItem::GetISound(tSoundID id)
{
IEntitySoundProxy *pSoundProxy = GetSoundProxy(false);
if (pSoundProxy)
return pSoundProxy->GetSound(id);
return 0;
}
//------------------------------------------------------------------------
void CItem::ReleaseStaticSound(SInstanceAudio *sound)
{
if (sound->id != INVALID_SOUNDID)
{
IEntitySoundProxy *pSoundProxy = GetSoundProxy(false);
if (pSoundProxy)
{
pSoundProxy->SetStaticSound(sound->id, false);
if(sound->synch)
pSoundProxy->StopSound(sound->id,ESoundStopMode_OnSyncPoint);
else
pSoundProxy->StopSound(sound->id);
sound->id = INVALID_SOUNDID;
#ifndef ITEM_USE_SHAREDSTRING
sound->static_name.resize(0);
#else
sound->static_name.reset();
#endif
}
}
}
//------------------------------------------------------------------------
void CItem::ReleaseStaticSounds()
{
for (TInstanceActionMap::iterator it = m_instanceActions.begin(); it != m_instanceActions.end(); ++it)
{
ReleaseStaticSound(&it->second.sound[0]);
ReleaseStaticSound(&it->second.sound[1]);
}
}
//------------------------------------------------------------------------
IEntitySoundProxy *CItem::GetSoundProxy(bool create)
{
IEntitySoundProxy *pSoundProxy = (IEntitySoundProxy *)GetEntity()->GetProxy(ENTITY_PROXY_SOUND);
if (!pSoundProxy && create)
pSoundProxy = (IEntitySoundProxy *)GetEntity()->CreateProxy(ENTITY_PROXY_SOUND);
return pSoundProxy;
}
//------------------------------------------------------------------------
IEntityRenderProxy *CItem::GetRenderProxy(bool create)
{
IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy *)GetEntity()->GetProxy(ENTITY_PROXY_RENDER);
if (!pRenderProxy && create)
pRenderProxy = (IEntityRenderProxy *)GetEntity()->CreateProxy(ENTITY_PROXY_RENDER);
return pRenderProxy;
}
//------------------------------------------------------------------------
IEntityPhysicalProxy *CItem::GetPhysicalProxy(bool create)
{
IEntityPhysicalProxy *pPhysicalProxy = (IEntityPhysicalProxy *)GetEntity()->GetProxy(ENTITY_PROXY_PHYSICS);
if (!pPhysicalProxy && create)
pPhysicalProxy = (IEntityPhysicalProxy *)GetEntity()->CreateProxy(ENTITY_PROXY_PHYSICS);
return pPhysicalProxy;
}
//------------------------------------------------------------------------
void CItem::DestroyedGeometry(bool use)
{
if (!m_geometry[eIGS_Destroyed].empty())
{
DrawSlot(eIGS_Destroyed, use);
if (m_stats.viewmode&eIVM_FirstPerson)
DrawSlot(eIGS_FirstPerson, !use);
else
DrawSlot(eIGS_ThirdPerson, !use);
if (use)
GetEntity()->SetSlotLocalTM(eIGS_Destroyed, GetEntity()->GetSlotLocalTM(eIGS_ThirdPerson, false));
}
}
| 412 | 0.972064 | 1 | 0.972064 | game-dev | MEDIA | 0.794262 | game-dev | 0.695634 | 1 | 0.695634 |
lukflug/PanelStudio | 1,796 | example-mod19/src/main/java/com/lukflug/examplemod19/ExampleMod.java | package com.lukflug.examplemod19;
import org.lwjgl.glfw.GLFW;
import com.lukflug.examplemod19.module.Category;
import com.lukflug.examplemod19.module.ClickGUIModule;
import com.lukflug.examplemod19.module.HUDEditorModule;
import com.lukflug.examplemod19.module.LogoModule;
import com.lukflug.examplemod19.module.TabGUIModule;
import com.lukflug.examplemod19.module.WatermarkModule;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
public class ExampleMod implements ModInitializer {
private static ClickGUI gui;
private boolean inited=false;
private final boolean keys[]=new boolean[266];
@Override
public void onInitialize() {
Category.init();
Category.OTHER.modules.add(new ClickGUIModule());
Category.OTHER.modules.add(new HUDEditorModule());
Category.HUD.modules.add(new TabGUIModule());
Category.HUD.modules.add(new WatermarkModule());
Category.HUD.modules.add(new LogoModule());
ClientTickEvents.END_CLIENT_TICK.register(client -> {
if (!inited) {
for (int i=32;i<keys.length;i++) keys[i]=GLFW.glfwGetKey(MinecraftClient.getInstance().getWindow().getHandle(),i)==GLFW.GLFW_PRESS;
gui=new ClickGUI();
HudRenderCallback.EVENT.register((cli,tickDelta)->gui.render());
inited=true;
}
for (int i=32;i<keys.length;i++) {
if (keys[i]!=(GLFW.glfwGetKey(MinecraftClient.getInstance().getWindow().getHandle(),i)==GLFW.GLFW_PRESS)) {
keys[i]=!keys[i];
if (keys[i]) {
if (i==ClickGUIModule.keybind.getKey()) gui.enterGUI();
if (i==HUDEditorModule.keybind.getKey()) gui.enterHUDEditor();
gui.handleKeyEvent(i);
}
}
}
});
}
}
| 412 | 0.801426 | 1 | 0.801426 | game-dev | MEDIA | 0.947524 | game-dev | 0.644385 | 1 | 0.644385 |
geraked/tradingview | 5,280 | strategies/3MAF.pine | // A simple strategy using three Moving Averages and Williams Fractals for scalping.
// The strategy has been explained in this video: https://youtu.be/bKPs2aOsvsk
// It should be noted that the reverse of the strategy works better! :D
// © 2023 Geraked, Rabist
// Licensed under MIT
// Backtesting result:
// Symbol: USDCAD
// Timeframe: 1 MIN
// Range: 2023-07-09 21:00 — 2023-07-13 13:14
// Percent Profitable: 70.8%
// Total Trades: 127
// Profit Factor: 1.326
// Backtesting result:
// Symbol: EURUSD
// Timeframe: 30 MIN
// Range: 2023-01-02 00:00 — 2023-07-13 13:00
// Percent Profitable: 76.7%
// Total Trades: 172
// Profit Factor: 1.399
//@version=5
strategy("3MA and Fractals Strategy", "3MAF", overlay=true)
len1 = input.int(20, "EMA1 Len", 1)
len2 = input.int(50, "EMA2 Len", 1)
len3 = input.int(100, "EMA3 Len", 1)
n = input.int(2, "Fractals Len", 2)
tpCoef = input.float(1, "TP Coef")
reverse = input.bool(false, "Reverse Signal")
dispInd = input.bool(false, "Display Indicators")
ma1 = ta.ema(close, len1)
ma2 = ta.ema(close, len2)
ma3 = ta.ema(close, len3)
plot(dispInd ? ma1 : na, title="EMA1", color=color.red)
plot(dispInd ? ma2 : na, title="EMA2", color=color.green)
plot(dispInd ? ma3 : na, title="EMA3", color=color.blue)
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
plotshape(dispInd ? downFractal : na, style=shape.triangledown, location=location.belowbar, offset=-n, color=#F44336, size=size.small)
plotshape(dispInd ? upFractal : na, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size=size.small)
longSignal = ma1 > ma2 and ma2 > ma3 and low > ma3 and low < ma1 and downFractal
shortSignal = ma3 > ma2 and ma2 > ma1 and high < ma3 and high > ma1 and upFractal
longSL = low > ma2 ? ma2 : ma3
shortSL = high < ma2 ? ma2 : ma3
if longSignal
if not reverse
strategy.entry("long", strategy.long)
inn = strategy.opentrades.entry_price(strategy.opentrades - 1)
longTP = inn + tpCoef * (inn - longSL)
strategy.exit("exit", "long", stop=longSL, limit=longTP, comment_loss="SL long", comment_profit="TP long")
else
strategy.entry("short", strategy.short)
inn = strategy.opentrades.entry_price(strategy.opentrades - 1)
longTP = inn + tpCoef * (inn - longSL)
strategy.exit("exit", "short", stop=longTP, limit=longSL, comment_loss="SL short", comment_profit="TP short")
if shortSignal
if not reverse
strategy.entry("short", strategy.short)
inn = strategy.opentrades.entry_price(strategy.opentrades - 1)
shortTp = inn - tpCoef * (shortSL - inn)
strategy.exit("exit", "short", stop=shortSL, limit=shortTp, comment_loss="SL short", comment_profit="TP short")
else
strategy.entry("long", strategy.long)
inn = strategy.opentrades.entry_price(strategy.opentrades - 1)
shortTp = inn - tpCoef * (shortSL - inn)
strategy.exit("exit", "long", stop=shortTp, limit=shortSL, comment_loss="SL long", comment_profit="TP long")
| 412 | 0.71712 | 1 | 0.71712 | game-dev | MEDIA | 0.742671 | game-dev | 0.893579 | 1 | 0.893579 |
diasurgical/DevilutionX | 1,941 | Source/DiabloUI/button.cpp | #include "DiabloUI/button.h"
#include <optional>
#ifdef USE_SDL3
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_mouse.h>
#else
#include <SDL.h>
#endif
#include "DiabloUI/diabloui.h"
#include "DiabloUI/ui_flags.hpp"
#include "DiabloUI/ui_item.h"
#include "engine/clx_sprite.hpp"
#include "engine/load_clx.hpp"
#include "engine/load_pcx.hpp"
#include "engine/rectangle.hpp"
#include "engine/render/clx_render.hpp"
#include "engine/render/text_render.hpp"
#include "engine/surface.hpp"
#include "utils/sdl_compat.h"
namespace devilution {
namespace {
OptionalOwnedClxSpriteList ButtonSprites;
} // namespace
void LoadDialogButtonGraphics()
{
ButtonSprites = LoadOptionalClx("ui_art\\dvl_but_sml.clx");
if (!ButtonSprites) {
ButtonSprites = LoadPcxSpriteList("ui_art\\but_sml", 15);
}
}
void FreeDialogButtonGraphics()
{
ButtonSprites = std::nullopt;
}
ClxSprite ButtonSprite(bool pressed)
{
return (*ButtonSprites)[pressed ? 1 : 0];
}
void RenderButton(const UiButton &button)
{
const Surface &out = Surface(DiabloUiSurface()).subregion(button.m_rect.x, button.m_rect.y, button.m_rect.w, button.m_rect.h);
RenderClxSprite(out, ButtonSprite(button.IsPressed()), { 0, 0 });
Rectangle textRect { { 0, 0 }, { button.m_rect.w, button.m_rect.h } };
if (!button.IsPressed()) {
--textRect.position.y;
}
DrawString(out, button.GetText(), textRect,
{ .flags = UiFlags::AlignCenter | UiFlags::FontSizeDialog | UiFlags::ColorDialogWhite });
}
bool HandleMouseEventButton(const SDL_Event &event, UiButton *button)
{
if (event.button.button != SDL_BUTTON_LEFT)
return false;
switch (event.type) {
case SDL_EVENT_MOUSE_BUTTON_UP:
if (button->IsPressed()) {
button->Activate();
return true;
}
return false;
case SDL_EVENT_MOUSE_BUTTON_DOWN:
button->Press();
return true;
default:
return false;
}
}
void HandleGlobalMouseUpButton(UiButton *button)
{
button->Release();
}
} // namespace devilution
| 412 | 0.923056 | 1 | 0.923056 | game-dev | MEDIA | 0.801959 | game-dev,desktop-app | 0.611257 | 1 | 0.611257 |
mana/mana | 2,471 | src/gui/outfitwindow.h | /*
* The Mana Client
* Copyright (C) 2007-2009 The Mana World Development Team
* Copyright (C) 2009-2012 The Mana Developers
*
* This file is part of The Mana Client.
*
* 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
* 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/>.
*/
#pragma once
#include "gui/widgets/window.h"
#include <guichan/actionlistener.hpp>
constexpr int OUTFITS_COUNT = 15;
constexpr int OUTFIT_ITEM_COUNT = 9;
class Button;
class CheckBox;
class Item;
class Label;
class OutfitWindow : public Window, gcn::ActionListener
{
public:
OutfitWindow();
~OutfitWindow() override;
void action(const gcn::ActionEvent &event) override;
void draw(gcn::Graphics *graphics) override;
void mouseDragged(gcn::MouseEvent &event) override;
void mousePressed(gcn::MouseEvent &event) override;
void mouseReleased(gcn::MouseEvent &event) override;
void load();
void setItemSelected(int itemId)
{ mItemSelected = itemId; }
bool isItemSelected() const
{ return mItemSelected > -1; }
void wearOutfit(int outfit);
void copyOutfit(int outfit);
void unequipNotInOutfit(int outfit);
private:
Button *mPreviousButton;
Button *mNextButton;
Label *mCurrentLabel;
CheckBox *mUnequipCheck;
int getIndexFromGrid(int pointX, int pointY) const;
int mBoxWidth = 33;
int mBoxHeight = 33;
int mCursorPosX, mCursorPosY;
int mGridWidth = 3;
int mGridHeight = 3;
bool mItemClicked = false;
Item *mItemMoved = nullptr;
void save();
struct Outfit
{
int items[OUTFIT_ITEM_COUNT];
bool unequip = true;
};
Outfit mOutfits[OUTFITS_COUNT];
int mItemSelected = -1;
int mCurrentOutfit = 0;
};
extern OutfitWindow *outfitWindow;
| 412 | 0.728527 | 1 | 0.728527 | game-dev | MEDIA | 0.852313 | game-dev | 0.631653 | 1 | 0.631653 |
mikekov/ExifPro | 1,518 | lua/src/lvm.h | /*
** $Id: lvm.h,v 2.17 2011/05/31 18:27:56 roberto Exp $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
#ifndef lvm_h
#define lvm_h
#include "ldo.h"
#include "lobject.h"
#include "ltm.h"
#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o)))
#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))
#define equalobj(L,o1,o2) (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))
#define luaV_rawequalobj(t1,t2) \
(ttisequal(t1,t2) && luaV_equalobj_(NULL,t1,t2))
/* not to called directly */
LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);
LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
StkId val);
LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
StkId val);
LUAI_FUNC void luaV_finishOp (lua_State *L);
LUAI_FUNC void luaV_execute (lua_State *L);
LUAI_FUNC void luaV_concat (lua_State *L, int total);
LUAI_FUNC void luaV_arith (lua_State *L, StkId ra, const TValue *rb,
const TValue *rc, TMS op);
LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
#endif
| 412 | 0.785529 | 1 | 0.785529 | game-dev | MEDIA | 0.415541 | game-dev | 0.641367 | 1 | 0.641367 |
Maproom/qmapshack | 6,866 | 3rdparty/GarminFitSdk/cpp/fit_hrm_profile_mesg.hpp | /////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2024 Garmin International, Inc.
// Licensed under the Flexible and Interoperable Data Transfer (FIT) Protocol License; you
// may not use this file except in compliance with the Flexible and Interoperable Data
// Transfer (FIT) Protocol License.
/////////////////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.158.0Release
// Tag = production/release/21.158.0-0-gc9428aa
/////////////////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_HRM_PROFILE_MESG_HPP)
#define FIT_HRM_PROFILE_MESG_HPP
#include "fit_mesg.hpp"
namespace fit
{
class HrmProfileMesg : public Mesg
{
public:
class FieldDefNum final
{
public:
static const FIT_UINT8 MessageIndex = 254;
static const FIT_UINT8 Enabled = 0;
static const FIT_UINT8 HrmAntId = 1;
static const FIT_UINT8 LogHrv = 2;
static const FIT_UINT8 HrmAntIdTransType = 3;
static const FIT_UINT8 Invalid = FIT_FIELD_NUM_INVALID;
};
HrmProfileMesg(void) : Mesg(Profile::MESG_HRM_PROFILE)
{
}
HrmProfileMesg(const Mesg &mesg) : Mesg(mesg)
{
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of message_index field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsMessageIndexValid() const
{
const Field* field = GetField(254);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns message_index field
///////////////////////////////////////////////////////////////////////
FIT_MESSAGE_INDEX GetMessageIndex(void) const
{
return GetFieldUINT16Value(254, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set message_index field
///////////////////////////////////////////////////////////////////////
void SetMessageIndex(FIT_MESSAGE_INDEX messageIndex)
{
SetFieldUINT16Value(254, messageIndex, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of enabled field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsEnabledValid() const
{
const Field* field = GetField(0);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns enabled field
///////////////////////////////////////////////////////////////////////
FIT_BOOL GetEnabled(void) const
{
return GetFieldENUMValue(0, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set enabled field
///////////////////////////////////////////////////////////////////////
void SetEnabled(FIT_BOOL enabled)
{
SetFieldENUMValue(0, enabled, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of hrm_ant_id field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsHrmAntIdValid() const
{
const Field* field = GetField(1);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns hrm_ant_id field
///////////////////////////////////////////////////////////////////////
FIT_UINT16Z GetHrmAntId(void) const
{
return GetFieldUINT16ZValue(1, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set hrm_ant_id field
///////////////////////////////////////////////////////////////////////
void SetHrmAntId(FIT_UINT16Z hrmAntId)
{
SetFieldUINT16ZValue(1, hrmAntId, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of log_hrv field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsLogHrvValid() const
{
const Field* field = GetField(2);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns log_hrv field
///////////////////////////////////////////////////////////////////////
FIT_BOOL GetLogHrv(void) const
{
return GetFieldENUMValue(2, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set log_hrv field
///////////////////////////////////////////////////////////////////////
void SetLogHrv(FIT_BOOL logHrv)
{
SetFieldENUMValue(2, logHrv, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of hrm_ant_id_trans_type field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsHrmAntIdTransTypeValid() const
{
const Field* field = GetField(3);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns hrm_ant_id_trans_type field
///////////////////////////////////////////////////////////////////////
FIT_UINT8Z GetHrmAntIdTransType(void) const
{
return GetFieldUINT8ZValue(3, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set hrm_ant_id_trans_type field
///////////////////////////////////////////////////////////////////////
void SetHrmAntIdTransType(FIT_UINT8Z hrmAntIdTransType)
{
SetFieldUINT8ZValue(3, hrmAntIdTransType, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
};
} // namespace fit
#endif // !defined(FIT_HRM_PROFILE_MESG_HPP)
| 412 | 0.505448 | 1 | 0.505448 | game-dev | MEDIA | 0.370579 | game-dev | 0.630634 | 1 | 0.630634 |
eezstreet/SWATEliteForce | 1,674 | Source/Game/SwatProcedures/Classes/Bonuses/Procedure_ArrestUnIncapacitatedSuspects.uc | class Procedure_ArrestUnIncapacitatedSuspects extends Procedure_ArrestSuspects
implements IInterested_GameEvent_PawnArrested,
IInterested_GameEvent_PawnIncapacitated;
function PostInitHook()
{
Super.PostInitHook();
//register for notifications that interest me
GetGame().GameEvents.PawnArrested.Register(self);
}
//interface IInterested_GameEvent_PawnArrested implementation
function OnPawnArrested( Pawn Pawn, Pawn Arrester )
{
if (!Pawn.IsA('SwatEnemy')) return; //we don't care
//stick it in the correct arrests array
if (!IsInArray(Pawn, IncapacitatedEnemies))
{
Add(Pawn, NeutralizedEnemies);
if (GetGame().DebugLeadership)
log("[LEADERSHIP] "$class.name
$" added "$Pawn.name
$" to its list of NeutralizedEnemies because PawnArrested (and was not previously Incapacitated)."
$" NeutralizedEnemies.length="$NeutralizedEnemies.length);
}
}
//interface IInterested_GameEvent_PawnIncapacitated implementation
function OnPawnIncapacitated(Pawn Pawn, Actor Incapacitator, bool WasAThreat)
{
Super.OnPawnIncapacitated( Pawn, Incapacitator, WasAThreat );
if (!Pawn.IsA('SwatEnemy')) return; //we don't care
Remove(Pawn, NeutralizedEnemies);
if (GetGame().DebugLeadership)
log("[LEADERSHIP] "$class.name
$" removed "$Pawn.name
$" from its list of NeutralizedEnemies because PawnDied."
$" NeutralizedEnemies.length="$NeutralizedEnemies.length);
}
function int AdditionalBonus()
{
if( TotalEnemies == 0 )
return TotalBonus;
return Super.AdditionalBonus();
}
| 412 | 0.901684 | 1 | 0.901684 | game-dev | MEDIA | 0.976451 | game-dev | 0.661665 | 1 | 0.661665 |
FPSG-UIUC/micro24-fusemax-artifact | 1,068 | workspace/outputs/pregenerated-check/timeloop/timeloop-model.ART_summary.yaml | ART_summary:
version: '0.4'
table_summary:
- name: system_top_level.DRAM[1..1]
area: 0.0
primitive_estimations: CactiDRAM
- name: system_top_level.reg_file_1d[1..1]
area: 18.1792
primitive_estimations: Library
- name: system_top_level.inter_PE_col_spatial[1..1]
area: 1.0
primitive_estimations: dummy_table
- name: system_top_level.inter_PE_spatial[1..256]
area: 1.0
primitive_estimations: dummy_table
- name: system_top_level.reg_file[1..65536]
area: 18.1792
primitive_estimations: Library
- name: system_top_level.L3[1..1]
area: 14641628.09825
primitive_estimations:
- name: storage
estimator: CactiSRAM
- name: address_generators[0..1]
estimator: Neurosim Plug-In
- name: system_top_level.mac[1..65536]
area: 79.23
primitive_estimations:
- name: intadder
estimator: Library
- name: intmultiplier
estimator: Library
| 412 | 0.554204 | 1 | 0.554204 | game-dev | MEDIA | 0.655841 | game-dev | 0.549409 | 1 | 0.549409 |
MergHQ/CRYENGINE | 8,316 | Code/CryEngine/Cry3DEngine/CloudsManager.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
// -------------------------------------------------------------------------
// File name: CloudsManager.h
// Version: v1.00
// Created: 15/2/2005 by Timur.
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "CloudRenderNode.h"
#include "CloudsManager.h"
#include "MatMan.h"
//////////////////////////////////////////////////////////////////////////
SCloudDescription::~SCloudDescription()
{
delete m_pCloudTree;
m_pCloudTree = 0;
// Unregister itself from clouds manager.
if (!filename.empty())
Get3DEngine()->GetCloudsManager()->Unregister(this);
}
//////////////////////////////////////////////////////////////////////////
SCloudDescription* CCloudsManager::LoadCloud(const char* sFilename)
{
string filename = PathUtil::ToUnixPath(sFilename);
SCloudDescription* pCloud = stl::find_in_map(m_cloudsMap, filename, NULL);
if (!pCloud)
{
XmlNodeRef root = GetISystem()->LoadXmlFromFile(filename);
if (root)
{
pCloud = new SCloudDescription;
pCloud->filename = filename;
ParseCloudFromXml(root, pCloud);
CloudParticles particles;
particles.resize(pCloud->m_particles.size());
for (uint32 i = 0; i < particles.size(); i++)
particles[i] = &pCloud->m_particles[i];
pCloud->m_pCloudTree = new SCloudQuadTree();
pCloud->m_pCloudTree->Init(pCloud->m_bounds, particles);
Register(pCloud);
}
}
return pCloud;
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::ParseCloudFromXml(XmlNodeRef root, SCloudDescription* pCloud)
{
assert(pCloud);
pCloud->m_bounds.min = Vec3(0, 0, 0);
pCloud->m_bounds.max = Vec3(0, 0, 0);
pCloud->m_pMaterial = 0;
const char* sMtlName = root->getAttr("Material");
if (sMtlName && sMtlName[0] != '\0')
{
pCloud->m_pMaterial = GetMatMan()->LoadMaterial(sMtlName);
if (!pCloud->m_pMaterial)
CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_ERROR, "Error: Failed to load cloud material" /*,sMtlName*/);
}
int numRows = 1;
int numCols = 1;
root->getAttr("TextureNumRows", numRows);
root->getAttr("TextureNumCols", numCols);
if (numRows < 1)
numRows = 1;
if (numCols < 1)
numCols = 1;
pCloud->m_textureRows = numRows;
pCloud->m_textureCols = numCols;
pCloud->m_numSprites = root->getChildCount();
pCloud->m_particles.reserve(pCloud->m_numSprites);
pCloud->m_particles.clear();
float xTextureStep = 1.0f / numCols;
float yTextureStep = 1.0f / numRows;
Vec3 pos(0, 0, 0);
int texID = 0;
float angle = 0;
float radius = 0;
Vec2 uv[2];
if (pCloud->m_numSprites > 0)
pCloud->m_bounds.Reset();
for (int i = 0; i < root->getChildCount(); i++)
{
XmlNodeRef child = root->getChild(i);
child->getAttr("Pos", pos);
child->getAttr("texID", texID);
child->getAttr("Radius", radius);
if (!child->getAttr("Angle", angle))
angle = 0;
int x = texID % numCols;
int y = texID / numCols;
uv[0].x = x * xTextureStep;
uv[0].y = y * yTextureStep;
uv[1].x = (x + 1) * xTextureStep;
uv[1].y = (y + 1) * yTextureStep;
SCloudParticle sprite(pos, radius, radius, 0, 0, uv);
pCloud->m_particles.push_back(sprite);
pCloud->m_bounds.Add(pos - Vec3(radius, radius, radius));
pCloud->m_bounds.Add(pos + Vec3(radius, radius, radius));
}
// Offset particles so that bounding box is centered at origin.
pCloud->m_offset = -pCloud->m_bounds.GetCenter();
pCloud->m_bounds.min += pCloud->m_offset;
pCloud->m_bounds.max += pCloud->m_offset;
for (uint32 i = 0; i < pCloud->m_particles.size(); i++)
{
pCloud->m_particles[i].SetPosition(pCloud->m_particles[i].GetPosition() + pCloud->m_offset);
}
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::Register(SCloudDescription* desc)
{
assert(desc);
m_cloudsMap[desc->filename] = desc;
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::Unregister(SCloudDescription* desc)
{
assert(desc);
m_cloudsMap.erase(desc->filename);
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::AddCloudRenderNode(CCloudRenderNode* pNode)
{
m_cloudNodes.push_back(pNode);
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::RemoveCloudRenderNode(CCloudRenderNode* pNode)
{
int size = m_cloudNodes.size();
for (int i = 0; i < size; i++)
{
if (m_cloudNodes[i] == pNode)
{
if (i < size - 1)
m_cloudNodes[i] = m_cloudNodes[size - 1];
m_cloudNodes.resize(size - 1);
break;
}
}
}
//!!! WARNING
//bool Sp_IsDraw = false;
//Matrix34 Sp_Mat;
//Vec3 Sp_Pos;
//float Sp_Rad;
//////////////////////////////////////////////////////////////////////////
bool CCloudsManager::CheckIntersectClouds(const Vec3& p1, const Vec3& p2)
{
for (std::vector<CCloudRenderNode*>::iterator it = m_cloudNodes.begin(); it != m_cloudNodes.end(); ++it)
{
//Sp_IsDraw = false;
if ((*it)->CheckIntersection(p1, p2))
{
//Sp_Mat = (*it)->m_offsetedMatrix;
//Sp_IsDraw = true;
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
void CCloudsManager::MoveClouds()
{
FUNCTION_PROFILER_3DENGINE;
std::vector<CCloudRenderNode*>::iterator it(m_cloudNodes.begin());
std::vector<CCloudRenderNode*>::iterator itEnd(m_cloudNodes.end());
for (; it != itEnd; ++it)
{
(*it)->MoveCloud();
}
}
//////////////////////////////////////////////////////////////////////////
void SCloudQuadTree::Init(const AABB& bounds, const CloudParticles& particles, int maxlevel)
{
m_bounds = bounds;
if (m_level >= maxlevel)
{
m_particles.resize(particles.size());
memcpy(&m_particles[0], &particles[0], particles.size() * sizeof(SCloudParticle*));
return;
}
CloudParticles parts;
for (int k = 0; k < 4; k++)
{
AABB bnds;
parts.resize(0);
Vec3 centr = (bounds.min + bounds.max) / 2;
if (k == 0)
bnds = AABB(bounds.min, Vec3(centr.x, centr.y, bounds.max.z));
else if (k == 1)
bnds = AABB(Vec3(bounds.min.x, centr.y, bounds.min.z), Vec3(centr.x, bounds.max.y, bounds.max.z));
else if (k == 2)
bnds = AABB(Vec3(centr.x, bounds.min.y, bounds.min.z), Vec3(bounds.max.x, centr.y, bounds.max.z));
else if (k == 3)
bnds = AABB(Vec3(centr.x, centr.y, bounds.min.z), bounds.max);
for (uint32 i = 0; i < particles.size(); i++)
{
SCloudParticle* pPtcl = particles[i];
if (bnds.IsOverlapSphereBounds(pPtcl->GetPosition(), pPtcl->GetRadiusX()) ||
bnds.IsContainSphere(pPtcl->GetPosition(), pPtcl->GetRadiusX()))
{
parts.push_back(pPtcl);
}
}
if (!parts.empty())
{
m_pQuads[k] = new SCloudQuadTree(m_level + 1);
m_pQuads[k]->Init(bnds, parts, maxlevel);
}
}
}
//////////////////////////////////////////////////////////////////////////
bool SCloudQuadTree::CheckIntersection(const Vec3& p1, const Vec3& p2)
{
Vec3 outp, outp2;
if (Intersect::Lineseg_AABB(Lineseg(p1, p2), m_bounds, outp))
{
if (m_pQuads[0] && m_pQuads[0]->CheckIntersection(p1, p2))
return true;
if (m_pQuads[1] && m_pQuads[1]->CheckIntersection(p1, p2))
return true;
if (m_pQuads[2] && m_pQuads[2]->CheckIntersection(p1, p2))
return true;
if (m_pQuads[3] && m_pQuads[3]->CheckIntersection(p1, p2))
return true;
if (!m_particles.empty())
{
for (uint32 i = 0; i < m_particles.size(); i++)
//if(Intersect::Lineseg_Sphere(Lineseg(p1, p2), Sphere (m_particles[i]->GetPosition(), m_particles[i]->GetRadiusX()*(2.0f/3)), outp, outp2))
if (Intersect::Lineseg_Sphere(Lineseg(p1, p2), Sphere(m_particles[i]->GetPosition(), m_particles[i]->GetRadiusX()), outp, outp2))
{
//Sp_Pos = m_particles[i]->GetPosition();
//Sp_Rad = m_particles[i]->GetRadiusX()/2;
return true;
}
}
}
return false;
}
/*
//!!! WARNING
extern bool Sp_IsDraw;
extern Matrix34 Sp_Mat;
extern Vec3 Sp_Pos;
extern float Sp_Rad;
void C3DEngine::Hack_GetSprite(bool & IsDraw, Matrix34 & Mat, Vec3 & Pos, float & Rad)
{
IsDraw = Sp_IsDraw;
Mat = Sp_Mat;
Pos = Sp_Pos;
Rad = Sp_Rad;
}
*/
| 412 | 0.970829 | 1 | 0.970829 | game-dev | MEDIA | 0.598489 | game-dev,graphics-rendering | 0.997912 | 1 | 0.997912 |
unishiki/Unity-UGUI-Effect | 8,850 | Assets/Presets/DOTween/Modules/DOTweenModuleAudio.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
#if true // MODULE_MARKER
using System;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using UnityEngine;
#if UNITY_5 || UNITY_2017_1_OR_NEWER
using UnityEngine.Audio; // Required for AudioMixer
#endif
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenModuleAudio
{
#region Shortcuts
#region Audio
/// <summary>Tweens an AudioSource's volume to the given value.
/// Also stores the AudioSource as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOFade(this AudioSource target, float endValue, float duration)
{
if (endValue < 0) endValue = 0;
else if (endValue > 1) endValue = 1;
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.volume, x => target.volume = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an AudioSource's pitch to the given value.
/// Also stores the AudioSource as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOPitch(this AudioSource target, float endValue, float duration)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.pitch, x => target.pitch = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#if UNITY_5 || UNITY_2017_1_OR_NEWER
#region AudioMixer (Unity 5 or Newer)
/// <summary>Tweens an AudioMixer's exposed float to the given value.
/// Also stores the AudioMixer as the tween's target so it can be used for filtered operations.
/// Note that you need to manually expose a float in an AudioMixerGroup in order to be able to tween it from an AudioMixer.</summary>
/// <param name="floatName">Name given to the exposed float to set</param>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOSetFloat(this AudioMixer target, string floatName, float endValue, float duration)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(()=> {
float currVal;
target.GetFloat(floatName, out currVal);
return currVal;
}, x=> target.SetFloat(floatName, x), endValue, duration);
t.SetTarget(target);
return t;
}
#region Operation Shortcuts
/// <summary>
/// Completes all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens completed
/// (meaning the tweens that don't have infinite loops and were not already complete)
/// </summary>
/// <param name="withCallbacks">For Sequences only: if TRUE also internal Sequence callbacks will be fired,
/// otherwise they will be ignored</param>
public static int DOComplete(this AudioMixer target, bool withCallbacks = false)
{
return DOTween.Complete(target, withCallbacks);
}
/// <summary>
/// Kills all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens killed.
/// </summary>
/// <param name="complete">If TRUE completes the tween before killing it</param>
public static int DOKill(this AudioMixer target, bool complete = false)
{
return DOTween.Kill(target, complete);
}
/// <summary>
/// Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens flipped.
/// </summary>
public static int DOFlip(this AudioMixer target)
{
return DOTween.Flip(target);
}
/// <summary>
/// Sends to the given position all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens involved.
/// </summary>
/// <param name="to">Time position to reach
/// (if higher than the whole tween duration the tween will simply reach its end)</param>
/// <param name="andPlay">If TRUE will play the tween after reaching the given position, otherwise it will pause it</param>
public static int DOGoto(this AudioMixer target, float to, bool andPlay = false)
{
return DOTween.Goto(target, to, andPlay);
}
/// <summary>
/// Pauses all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens paused.
/// </summary>
public static int DOPause(this AudioMixer target)
{
return DOTween.Pause(target);
}
/// <summary>
/// Plays all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlay(this AudioMixer target)
{
return DOTween.Play(target);
}
/// <summary>
/// Plays backwards all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlayBackwards(this AudioMixer target)
{
return DOTween.PlayBackwards(target);
}
/// <summary>
/// Plays forward all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlayForward(this AudioMixer target)
{
return DOTween.PlayForward(target);
}
/// <summary>
/// Restarts all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens restarted.
/// </summary>
public static int DORestart(this AudioMixer target)
{
return DOTween.Restart(target);
}
/// <summary>
/// Rewinds all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens rewinded.
/// </summary>
public static int DORewind(this AudioMixer target)
{
return DOTween.Rewind(target);
}
/// <summary>
/// Smoothly rewinds all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens rewinded.
/// </summary>
public static int DOSmoothRewind(this AudioMixer target)
{
return DOTween.SmoothRewind(target);
}
/// <summary>
/// Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens involved.
/// </summary>
public static int DOTogglePause(this AudioMixer target)
{
return DOTween.TogglePause(target);
}
#endregion
#endregion
#endif
#endregion
}
}
#endif
| 412 | 0.79846 | 1 | 0.79846 | game-dev | MEDIA | 0.963203 | game-dev | 0.953189 | 1 | 0.953189 |
oxygine/oxygine-framework | 1,868 | examples/Game/part5/src/GameScene.cpp | #include "GameScene.h"
#include "MainMenuScene.h"
#include "MyButton.h"
#include "res.h"
#include "GameMenu.h"
spGameScene GameScene::instance;
GameScene::GameScene()
{
//create game actor
_game = new Game;
_game->init();
_game->attachTo(_view);
//Game Actor would have own Clock.
//clock is internal time of each Actor
//by default own clock has only Stage
//clock could be paused and all children of this Actor would be paused to
_game->setClock(new Clock);
//create menu button
spSprite btn = new MyButton;
btn->setResAnim(res::ui.getResAnim("menu"));
btn->setAnchor(0.5f, 0.5f);
btn->attachTo(_view);
//align it to top right
btn->setX(_view->getWidth() - btn->getWidth() / 2);
btn->setY(btn->getHeight() / 2);
//handle click to menu
btn->addEventListener(TouchEvent::CLICK, CLOSURE(this, &GameScene::onEvent));
//subscribe to Hidden Event from GameMenu
GameMenu::instance->addEventListener(GameScene::HiddenEvent::EVENT, CLOSURE(this, &GameScene::onEvent));
}
void GameScene::onEvent(Event* ev)
{
if (ev->type == TouchEvent::CLICK)
{
//menu button clicked
//pause game by pausing it's clock
_game->getClock()->pause();
//show GameMenu dialog
GameMenu::instance->show();
}
if (ev->type == GameScene::HiddenEvent::EVENT)
{
//event from GameMenu called after GameMenu::instance->hide()
const string& name = GameMenu::instance->getLastClicked();
if (name == "Exit")
{
//if "Exit" button was clicked
changeScene(MainMenuScene::instance);
}
else
{
//"Continue" button was clicked
//dialog already hidden
//just resume Clock to continue game
_game->getClock()->resume();
}
}
} | 412 | 0.778618 | 1 | 0.778618 | game-dev | MEDIA | 0.972071 | game-dev | 0.754746 | 1 | 0.754746 |
b1inkie/dst-api | 5,758 | scripts_619045/stategraphs/SGwinona_storage_robot.lua | require("stategraphs/commonstates")
local actionhandlers =
{
ActionHandler(ACTIONS.PICKUP, "pickup"),
ActionHandler(ACTIONS.STORE, "store"),
}
local events =
{
CommonHandlers.OnLocomote(true, false),
EventHandler("onfueldsectionchanged", function(inst, data)
if not inst.sg:HasStateTag("busy") then
inst.sg.statemem.keepnofaced = true
inst.sg:GoToState("poweroff")
end
end),
EventHandler("sleepmode", function(inst)
if not inst.sg:HasStateTag("busy") then
inst.sg.statemem.keepnofaced = true
inst.sg:GoToState("poweroff")
else
inst.sg.mem.wantstosleep = true
end
end),
}
local function SetSoundLoop(inst, name)
if name ~= "idle_lp" then
inst.SoundEmitter:KillSound("idle_lp")
elseif not inst.SoundEmitter:PlayingSound("idle_lp") then
inst.SoundEmitter:PlaySound("meta4/winbot/idle_lp", "idle_lp")
end
if name ~= "run_lp" then
inst.SoundEmitter:KillSound("run_lp")
else--if not inst.SoundEmitter:PlayingSound("run_lp") then
inst.SoundEmitter:PlaySound("meta4/winbot/run_lp", "run_lp")
end
end
local states =
{
State{
name = "idle",
tags = { "idle", "canrotate" },
onenter = function(inst, pushanim)
if inst.components.fueled:IsEmpty() or inst.sg.mem.wantstosleep then
inst.sg.statemem.keepnofaced = true
inst.sg:GoToState("poweroff")
return
end
inst.components.locomotor:StopMoving()
inst.Transform:SetNoFaced()
if pushanim then
inst.AnimState:PushAnimation("idle")
else
inst.AnimState:PlayAnimation("idle", true)
end
SetSoundLoop(inst, "idle_lp")
end,
onexit = function(inst)
if not inst.sg.statemem.keepnofaced then
inst.Transform:SetFourFaced()
end
end,
},
State{
name = "poweron",
tags = { "busy" },
onenter = function(inst)
inst.components.locomotor:Stop()
inst.Transform:SetNoFaced()
inst.AnimState:PlayAnimation("poweron")
SetSoundLoop(inst, nil)
inst.SoundEmitter:PlaySound("meta4/winbot/poweron")
end,
timeline =
{
FrameEvent(34, function(inst)
inst.sg.statemem.keepnofaced = true
inst.sg:GoToState("idle", true)
end),
},
onexit = function(inst)
if not inst.sg.statemem.keepnofaced then
inst.Transform:SetFourFaced()
end
end,
},
State{
name = "poweroff",
tags = { "busy" },
onenter = function(inst)
inst.components.locomotor:Stop()
inst.Transform:SetNoFaced()
inst.AnimState:PlayAnimation("poweroff")
SetSoundLoop(inst, nil)
inst.SoundEmitter:PlaySound("meta4/winbot/poweroff")
end,
events =
{
EventHandler("animover", function(inst)
if inst.AnimState:AnimDone() then
inst:OnDeactivateRobot()
end
end),
},
onexit = function(inst)
if not inst.sg.statemem.keepnofaced then
inst.Transform:SetFourFaced()
end
end,
},
State{
name = "pickup",
tags = { "busy", "jumping" },
onenter = function(inst)
inst.components.locomotor:Stop()
inst.AnimState:PlayAnimation("pickup")
SetSoundLoop(inst, nil)
inst.SoundEmitter:PlaySound("meta4/winbot/pickup")
end,
timeline =
{
FrameEvent(0, function(inst)
--can't start physics in onenter, since it'll get stopped after entering the action state
local target = inst.bufferedaction and inst.bufferedaction.target or nil
if target and target:IsValid() then
local x, y, z = inst.Transform:GetWorldPosition()
local x1, y1, z1 = target.Transform:GetWorldPosition()
local dx, dz = x1 - x, z1 - z
if dx ~= 0 or dz ~= 0 then
inst.Transform:SetRotation(math.atan2(-dz, dx) * RADIANS)
local dist = dx * dx + dz * dz
dist = dist < 4 and math.sqrt(dist) or 2
local speed = dist / (10 * FRAMES)
inst.Physics:SetMotorVelOverride(speed, 0, 0)
end
else
inst.Physics:SetMotorVelOverride(0.75 / (7 * FRAMES), 0, 0)
end
end),
FrameEvent(10, function(inst)
inst.Physics:ClearMotorVelOverride()
inst.Physics:Stop()
local target = inst.bufferedaction and inst.bufferedaction.target
if target and not target:IsInLimbo() and target:IsValid() and inst:IsNear(target, 0.5) then
inst:PerformBufferedAction()
else
inst:ClearBufferedAction()
end
end),
FrameEvent(16, function(inst)
SetSoundLoop(inst, "idle_lp")
end),
},
events =
{
EventHandler("animover", function(inst)
if inst.AnimState:AnimDone() then
inst.sg:GoToState("idle")
end
end),
},
onexit = function(inst)
inst.Physics:ClearMotorVelOverride()
inst.Physics:Stop()
end,
},
State{
name = "store",
tags = { "busy" },
onenter = function(inst)
inst.components.locomotor:Stop()
inst.Transform:SetNoFaced()
inst.AnimState:PlayAnimation("dropoff")
inst.Physics:SetMass(0)
SetSoundLoop(inst, nil)
inst.SoundEmitter:PlaySound("meta4/winbot/dropoff")
end,
timeline =
{
FrameEvent(7, function(inst)
inst.Physics:SetMass(50)
inst:PerformBufferedAction()
end),
FrameEvent(35, function(inst)
inst.components.inventory:CloseAllChestContainers()
end),
FrameEvent(42, function(inst)
SetSoundLoop(inst, "idle_lp")
end),
},
events =
{
EventHandler("animover", function(inst)
if inst.AnimState:AnimDone() then
inst.sg.statemem.keepnofaced = true
inst.sg:GoToState("idle")
end
end),
},
onexit = function(inst)
if not inst.sg.statemem.keepnofaced then
inst.Transform:SetFourFaced()
end
inst.components.inventory:CloseAllChestContainers()
end,
},
}
CommonStates.AddRunStates(states, nil, nil, nil, nil, {
startonenter = function(inst)
SetSoundLoop(inst, "run_lp")
end,
endonenter = function(inst)
SetSoundLoop(inst, "idle_lp")
end,
})
return StateGraph("winona_storage_robot", states, events, "poweron", actionhandlers)
| 412 | 0.830915 | 1 | 0.830915 | game-dev | MEDIA | 0.947074 | game-dev | 0.96299 | 1 | 0.96299 |
ServUO/ServUO | 6,722 | Scripts/Services/Seasonal Events/RisingTide/PlunderBeaconSpawner.cs | using System;
using System.Linq;
using System.Collections.Generic;
using Server;
using Server.Items;
using Server.Mobiles;
using Server.Multis;
namespace Server.Items
{
public class PlunderBeaconSpawner
{
public enum PlunderZone
{
None = -1,
Tram,
Fel,
Tokuno1,
Tokuno2,
Tokuno3,
Tokuno4
}
public static PlunderBeaconSpawner Spawner { get; set; }
public Dictionary<PlunderZone, List<PlunderBeaconAddon>> PlunderBeacons { get; set; }
public static void AddPlunderBeacon(PlunderZone zone, PlunderBeaconAddon beacon)
{
if (Spawner == null)
return;
if (!Spawner.PlunderBeacons[zone].Contains(beacon))
{
Spawner.PlunderBeacons[zone].Add(beacon);
}
}
public void RemovePlunderBeacon(PlunderBeaconAddon beacon)
{
if (Spawner == null || Spawner.PlunderBeacons == null)
return;
foreach (var kvp in Spawner.PlunderBeacons)
{
if (kvp.Value.Contains(beacon))
{
kvp.Value.Remove(beacon);
}
}
}
public void SystemDeactivate()
{
if (Timer != null)
{
Timer.Stop();
Timer = null;
}
var list = new List<PlunderBeaconAddon>();
foreach (var kvp in PlunderBeacons)
{
list.AddRange(kvp.Value);
}
foreach (var beacon in list)
{
beacon.Delete();
}
PlunderBeacons.Clear();
Spawner = null;
}
private Rectangle2D[] _Zones =
{
new Rectangle2D(1574, 3620, 766, 465),
new Rectangle2D(1574, 3620, 766, 465),
new Rectangle2D(403, 843, 80, 335),
new Rectangle2D(631, 20, 189, 110),
new Rectangle2D(1037, 20, 190, 150),
new Rectangle2D(1274, 977, 141, 221)
};
private int[] _SpawnCount =
{
5, 5, 3, 3, 3, 3
};
public Timer Timer { get; set; }
public PlunderBeaconSpawner()
{
if (Spawner == null)
{
Spawner = this;
Timer = Timer.DelayCall(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), TickTock);
PlunderBeacons = new Dictionary<PlunderZone, List<PlunderBeaconAddon>>();
PlunderBeacons[PlunderZone.Tram] = new List<PlunderBeaconAddon>();
PlunderBeacons[PlunderZone.Fel] = new List<PlunderBeaconAddon>();
PlunderBeacons[PlunderZone.Tokuno1] = new List<PlunderBeaconAddon>();
PlunderBeacons[PlunderZone.Tokuno2] = new List<PlunderBeaconAddon>();
PlunderBeacons[PlunderZone.Tokuno3] = new List<PlunderBeaconAddon>();
PlunderBeacons[PlunderZone.Tokuno4] = new List<PlunderBeaconAddon>();
}
else
{
Console.WriteLine("ALREADY HAS A SPAWNER!");
}
}
public void TickTock()
{
CheckSpawn();
}
public void CheckSpawn()
{
foreach (int i in Enum.GetValues(typeof(PlunderZone)))
{
if (i == -1)
continue;
var zone = (PlunderZone)i;
int low = _SpawnCount[i] - PlunderBeacons[zone].Count;
if (low > 0)
{
Spawn(zone, low);
}
}
}
public void Spawn(PlunderZone zone, int amount)
{
Map map = Map.Trammel;
if (zone == PlunderZone.Fel)
map = Map.Felucca;
else if (zone > PlunderZone.Fel)
map = Map.Tokuno;
for (int i = 0; i < amount; i++)
{
var rec = _Zones[(int)zone];
Point3D p;
while(true)
{
p = map.GetRandomSpawnPoint(rec); //new Point3D(rec.X + Utility.Random(rec.Width), rec.Y + Utility.RandomMinMax(rec.Start.X, rec.Height), -5);
if (p.Z != -5)
p.Z = -5;
var bounds = new Rectangle2D(p.X - 7, p.Y - 7, 15, 15);
bool badSpot = false;
for (int x = bounds.Start.X; x <= bounds.Start.X + bounds.Width; x++)
{
for (int y = bounds.Start.Y; y <= bounds.Start.Y + bounds.Height; y++)
{
if (BaseBoat.FindBoatAt(new Point3D(x, y, -5), map) != null || !SpecialFishingNet.ValidateDeepWater(map, x, y))
{
badSpot = true;
break;
}
}
if (badSpot)
break;
}
if (!badSpot)
{
IPooledEnumerable eable = map.GetMobilesInBounds(bounds);
foreach (Mobile m in eable)
{
if (m.AccessLevel == AccessLevel.Player)
{
badSpot = true;
break;
}
}
eable.Free();
if (!badSpot)
{
var beacon = new PlunderBeaconAddon();
beacon.MoveToWorld(p, map);
PlunderBeacons[zone].Add(beacon);
break;
}
}
}
}
}
public void Serialize(GenericWriter writer)
{
writer.Write(0);
writer.Write(PlunderBeacons.Count);
foreach (var kvp in PlunderBeacons)
{
writer.Write((int)kvp.Key);
writer.WriteItemList(kvp.Value);
}
}
public void Deserialize(GenericReader reader)
{
reader.ReadInt();
int count = reader.ReadInt();
for (int i = 0; i < count; i++)
{
PlunderBeacons[(PlunderZone)reader.ReadInt()] = reader.ReadStrongItemList<PlunderBeaconAddon>();
}
}
}
}
| 412 | 0.858709 | 1 | 0.858709 | game-dev | MEDIA | 0.959306 | game-dev | 0.892084 | 1 | 0.892084 |
ARM-software/gator | 3,499 | daemon/hwcpipe2/device/src/device/ioctl/kinstr_prfcnt/compare_manual.hpp | /*
* Copyright (c) 2022-2023 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "compare.hpp"
#include <cassert>
namespace hwcpipe {
namespace device {
namespace ioctl {
namespace kinstr_prfcnt {
bool operator==(const enum_item &lhs, const enum_item &rhs) {
if (lhs.hdr != rhs.hdr)
return false;
switch (lhs.hdr.type) {
case enum_item::item_type::block:
return lhs.u.block_counter == rhs.u.block_counter;
case enum_item::item_type::request:
return lhs.u.request == rhs.u.request;
case enum_item::item_type::sample_info:
return lhs.u.sample_info == rhs.u.sample_info;
}
assert(!&"Unknown enum_item::item_type");
return false;
}
bool operator==(const metadata_item &lhs, const metadata_item &rhs) {
if (lhs.hdr != rhs.hdr)
return false;
switch (lhs.hdr.type) {
case metadata_item::item_type::none:
return true;
case metadata_item::item_type::block:
return lhs.u.block_md == rhs.u.block_md;
case metadata_item::item_type::clock:
return lhs.u.clock_md == rhs.u.clock_md;
case metadata_item::item_type::sample:
return lhs.u.sample_md == rhs.u.sample_md;
}
assert(!&"Unknown metadata_item::item_type");
return false;
}
bool operator==(const request_item &lhs, const request_item &rhs) {
if (lhs.hdr != rhs.hdr)
return false;
switch (lhs.hdr.type) {
case request_item::item_type::none:
return true;
case request_item::item_type::enable:
return lhs.u.req_enable == rhs.u.req_enable;
case request_item::item_type::mode:
return lhs.u.req_mode == rhs.u.req_mode;
case request_item::item_type::scope:
return lhs.u.req_scope == rhs.u.req_scope;
}
assert(!&"Unknown request_item::item_type");
return false;
}
bool operator==(const request_item::request_mode &lhs, const request_item::request_mode &rhs) {
if (lhs.mode != rhs.mode)
return false;
switch (lhs.mode) {
case request_item::request_mode::sampling_mode::manual:
return true;
case request_item::request_mode::sampling_mode::periodic:
return lhs.mode_config.periodic == rhs.mode_config.periodic;
}
assert(!&"Unknown request_item::request_mode::sampling_mode");
return false;
}
} // namespace kinstr_prfcnt
} // namespace ioctl
} // namespace device
} // namespace hwcpipe
| 412 | 0.733718 | 1 | 0.733718 | game-dev | MEDIA | 0.135172 | game-dev | 0.530695 | 1 | 0.530695 |
lllyasviel/YGOProUnity_V2 | 4,921 | Assets/old/UiverseAssests/TextMesh Pro/Scripts/TMPro_EventManager.cs | using UnityEngine;
using System.Collections;
namespace TMPro
{
public enum Compute_DistanceTransform_EventTypes { Processing, Completed };
public static class TMPro_EventManager
{
//public delegate void PROGRESS_BAR_EVENT_HANDLER(object Sender, Progress_Bar_EventArgs e);
//public static event PROGRESS_BAR_EVENT_HANDLER PROGRESS_BAR_EVENT;
public delegate void COMPUTE_DT_EVENT_HANDLER(object Sender, Compute_DT_EventArgs e);
public static event COMPUTE_DT_EVENT_HANDLER COMPUTE_DT_EVENT;
// Event & Delegate used to notify TextMesh Pro objects that Material properties have been changed.
public delegate void MaterialProperty_Event_Handler(bool isChanged, Material mat);
public static event MaterialProperty_Event_Handler MATERIAL_PROPERTY_EVENT;
public delegate void FontProperty_Event_Handler(bool isChanged, TextMeshProFont font);
public static event FontProperty_Event_Handler FONT_PROPERTY_EVENT;
public delegate void SpriteAssetProperty_Event_Handler(bool isChanged, Object obj);
public static event SpriteAssetProperty_Event_Handler SPRITE_ASSET_PROPERTY_EVENT;
public delegate void TextMeshProProperty_Event_Handler(bool isChanged, TextMeshPro obj);
public static event TextMeshProProperty_Event_Handler TEXTMESHPRO_PROPERTY_EVENT;
public delegate void DragAndDrop_Event_Handler(GameObject sender, Material currentMaterial, Material newMaterial);
public static event DragAndDrop_Event_Handler DRAG_AND_DROP_MATERIAL_EVENT;
#if UNITY_4_6 || UNITY_5
public delegate void TextMeshProUGUIProperty_Event_Handler(bool isChanged, TextMeshProUGUI obj);
public static event TextMeshProUGUIProperty_Event_Handler TEXTMESHPRO_UGUI_PROPERTY_EVENT;
public delegate void BaseMaterial_Event_Handler(Material mat);
public static event BaseMaterial_Event_Handler BASE_MATERIAL_EVENT;
#endif
public delegate void OnPreRenderObject_Event_Handler();
public static event OnPreRenderObject_Event_Handler OnPreRenderObject_Event;
public static void ON_PRE_RENDER_OBJECT_CHANGED()
{
if (OnPreRenderObject_Event != null)
OnPreRenderObject_Event();
}
public static void ON_MATERIAL_PROPERTY_CHANGED(bool isChanged, Material mat)
{
if (MATERIAL_PROPERTY_EVENT != null)
MATERIAL_PROPERTY_EVENT(isChanged, mat);
}
public static void ON_FONT_PROPERTY_CHANGED(bool isChanged, TextMeshProFont font)
{
if (FONT_PROPERTY_EVENT != null)
FONT_PROPERTY_EVENT(isChanged, font);
}
public static void ON_SPRITE_ASSET_PROPERTY_CHANGED(bool isChanged, Object obj)
{
if (SPRITE_ASSET_PROPERTY_EVENT != null)
SPRITE_ASSET_PROPERTY_EVENT(isChanged, obj);
}
public static void ON_TEXTMESHPRO_PROPERTY_CHANGED(bool isChanged, TextMeshPro obj)
{
if (TEXTMESHPRO_PROPERTY_EVENT != null)
TEXTMESHPRO_PROPERTY_EVENT(isChanged, obj);
}
public static void ON_DRAG_AND_DROP_MATERIAL_CHANGED(GameObject sender, Material currentMaterial, Material newMaterial)
{
if (DRAG_AND_DROP_MATERIAL_EVENT != null)
DRAG_AND_DROP_MATERIAL_EVENT(sender, currentMaterial, newMaterial);
}
#if UNITY_4_6 || UNITY_5
public static void ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED(bool isChanged, TextMeshProUGUI obj)
{
if (TEXTMESHPRO_UGUI_PROPERTY_EVENT != null)
TEXTMESHPRO_UGUI_PROPERTY_EVENT(isChanged, obj);
}
public static void ON_BASE_MATERIAL_CHANGED(Material mat)
{
if (BASE_MATERIAL_EVENT != null)
BASE_MATERIAL_EVENT(mat);
}
#endif
//public static void ON_PROGRESSBAR_UPDATE(Progress_Bar_EventTypes event_type, Progress_Bar_EventArgs eventArgs)
//{
// if (PROGRESS_BAR_EVENT != null)
// PROGRESS_BAR_EVENT(event_type, eventArgs);
//}
public static void ON_COMPUTE_DT_EVENT(object Sender, Compute_DT_EventArgs e)
{
if (COMPUTE_DT_EVENT != null)
COMPUTE_DT_EVENT(Sender, e);
}
}
public class Compute_DT_EventArgs
{
public Compute_DistanceTransform_EventTypes EventType;
public float ProgressPercentage;
public Color[] Colors;
public Compute_DT_EventArgs(Compute_DistanceTransform_EventTypes type, float progress)
{
EventType = type;
ProgressPercentage = progress;
}
public Compute_DT_EventArgs(Compute_DistanceTransform_EventTypes type, Color[] colors)
{
EventType = type;
Colors = colors;
}
}
} | 412 | 0.553921 | 1 | 0.553921 | game-dev | MEDIA | 0.621636 | game-dev,desktop-app | 0.738786 | 1 | 0.738786 |
ill-inc/biomes-game | 17,918 | src/client/game/scripts/group_placement.ts | import type { Events } from "@/client/game/context_managers/events";
import type { ClientInput } from "@/client/game/context_managers/input";
import type { PermissionsManager } from "@/client/game/context_managers/permissions_manager";
import type { ClientTable } from "@/client/game/game";
import type { InteractContext } from "@/client/game/interact/types";
import type { GroupPlacementPreview } from "@/client/game/resources/group_placement";
import { slotRefFromSelection } from "@/client/game/resources/inventory";
import type {
ClientReactResources,
ClientResources,
} from "@/client/game/resources/types";
import type { Script } from "@/client/game/scripts/script_controller";
import type { Reflect } from "@/shared/asset_defs/shapes";
import { Box } from "@/shared/ecs/gen/components";
import type { ReadonlyEntity } from "@/shared/ecs/gen/entities";
import {
CloneGroupEvent,
DeleteGroupPreviewEvent,
PlaceBlueprintEvent,
PlaceGroupEvent,
UpdateGroupPreviewEvent,
} from "@/shared/ecs/gen/events";
import type { Item, OwnedItemReference, ShardId } from "@/shared/ecs/gen/types";
import { getBlueprintData } from "@/shared/game/blueprint";
import { CollisionHelper } from "@/shared/game/collision";
import { groupTensorBox, rotateGroupTensor } from "@/shared/game/group";
import { OwnedItemReferencesEqual } from "@/shared/game/inventory";
import type { BiomesId } from "@/shared/ids";
import {
add,
approxEquals,
approxEquals2,
centerAABB,
centerAABBXZ,
length,
round,
scale,
shiftAABB,
sub,
} from "@/shared/math/linear";
import {
normalizeRotation,
orientationToRotation,
rotationToOrientation,
} from "@/shared/math/rotation";
import type { ReadonlyVec2, ReadonlyVec3, Vec3 } from "@/shared/math/types";
import { GROUP_PLACEMENT_ENVIRONMENT_PARAMS } from "@/shared/physics/environments";
import { verticalForce, walkingForce } from "@/shared/physics/forces";
import { isCollidingJoined, moveBodyJoined } from "@/shared/physics/movement";
import type { Force } from "@/shared/physics/types";
import { canClimbBlock, grounded } from "@/shared/physics/utils";
import { fireAndForget } from "@/shared/util/async";
import { EventThrottle, StateThrottle } from "@/shared/util/throttling";
import type { AABB } from "@/shared/wasm/types/biomes";
interface MoveState {
position: ReadonlyVec3;
orientation: ReadonlyVec2;
reflection: Reflect;
}
export async function beginShowingPlaceablePreviewAtCoordinate(
{
table,
resources,
voxeloo,
}: InteractContext<"table" | "resources" | "voxeloo">,
position: Vec3,
item: Item,
inventoryRef: OwnedItemReference
) {
let tensorBlob: string | undefined;
let blueprintId: BiomesId | undefined;
let groupId: BiomesId | undefined;
const itemId = item.id;
let tensorAssetRotation: number | undefined;
if (itemId && item.isBlueprint) {
blueprintId = itemId;
const playerHasRequiredItems = resources.get(
"/groups/blueprint/has_required_items",
blueprintId
);
if (playerHasRequiredItems) {
({ tensor: tensorBlob } = getBlueprintData(itemId));
tensorAssetRotation = item.rotation;
}
} else {
groupId = item.groupId;
if (groupId) {
const groupEntity = await table.oob.oobFetchSingle(groupId);
tensorBlob = groupEntity?.group_component?.tensor;
}
}
if (tensorBlob) {
resources.update("/groups/placement/tensor", (val) => {
if (val.tensor) {
val.tensor.delete();
}
val.tensor = new voxeloo.GroupTensor();
val.tensor.load(tensorBlob!);
if (tensorAssetRotation) {
const rotatedTensor = rotateGroupTensor(
voxeloo,
val.tensor,
normalizeRotation(tensorAssetRotation)
);
val.tensor.delete();
val.tensor = rotatedTensor;
}
val.box = groupTensorBox(val.tensor);
val.groupId = groupId;
val.blueprintId = blueprintId;
val.item = item;
val.itemReference = inventoryRef;
return val;
});
resources.update("/groups/placement/preview", (val) => {
val.orientation = [0, 0];
val.reflection = [0, 0, 0];
val.centeredXZPosition = add(position, [0, 1, 0]);
});
}
}
export function stopShowingPlaceablePreview(resources: ClientResources) {
resources.update("/groups/placement/tensor", (val) => {
if (val.tensor) {
val.tensor.delete();
}
val.tensor = undefined;
val.groupId = undefined;
val.box = undefined;
val.blueprintId = undefined;
val.item = undefined;
val.itemReference = undefined;
});
}
export function aclAllowsPlacementForPlaceablePreview(
resources: ClientResources | ClientReactResources,
_permissionsManager: PermissionsManager
) {
const newGroupPreview = resources.get("/groups/placement/preview");
if (!newGroupPreview.active()) {
return false;
}
return true;
}
export function actualizePlaceablePreview(
resources: ClientResources | ClientReactResources,
permissionsManager: PermissionsManager,
events: Events,
userId: BiomesId,
item: Item,
inventoryRef: OwnedItemReference,
options: { clone: boolean } = { clone: false }
) {
const newGroupPreview = resources.get("/groups/placement/preview");
if (!newGroupPreview.active() || !newGroupPreview.canActualize) {
return;
}
if (newGroupPreview.groupPlacementTensor.blueprintId) {
const placementTensor = newGroupPreview.placementTensorTakeOwnership();
const position = centerAABBXZ(placementTensor.box);
if (
permissionsManager.clientActionAllowedAABB("place", placementTensor.box)
) {
void (async () => {
await events.publish(
new PlaceBlueprintEvent({
id: userId,
inventory_ref: inventoryRef,
item: item.id,
position: position,
orientation: newGroupPreview.orientation,
})
);
})();
placementTensor.tensor.delete();
resources.set("/groups/placement/tensor", {});
}
} else if (newGroupPreview.groupPlacementTensor.groupId) {
const placementTensor = newGroupPreview.placementTensorTakeOwnership();
const localPlayer = resources.get("/scene/local_player");
const label = resources.get(
"/ecs/c/label",
newGroupPreview.groupPlacementTensor.groupId
);
if (options.clone) {
fireAndForget(
events.publish(
new CloneGroupEvent({
id: newGroupPreview.groupPlacementTensor.groupId,
user_id: userId,
inventory_ref: inventoryRef,
tensor: placementTensor.tensor.save(),
rotation: placementTensor.rotation,
reflection: placementTensor.reflection as Vec3,
box: Box.clone({
v0: placementTensor.box[0],
v1: placementTensor.box[1],
}),
})
)
);
} else {
if (
permissionsManager.clientActionAllowedAABB("place", placementTensor.box)
) {
const groupId = newGroupPreview.groupPlacementTensor.groupId;
void (async () => {
await events.publish(
new PlaceGroupEvent({
id: groupId,
user_id: userId,
inventory_ref: inventoryRef,
tensor: placementTensor.tensor.save(),
rotation: placementTensor.rotation,
reflection: placementTensor.reflection as Vec3,
name: label?.text,
warp: {
warp_to: localPlayer.player.position,
orientation: localPlayer.player.orientation,
},
box: Box.clone({
v0: placementTensor.box[0],
v1: placementTensor.box[1],
}),
})
);
})();
placementTensor.tensor.delete();
resources.set("/groups/placement/tensor", {});
}
}
}
}
export class GroupPlacementScript implements Script {
readonly name = "groupPlacement";
private desireFlip = false;
private desireMirror = false;
private flipCallback: (() => unknown) | undefined;
private mirrorCallback: (() => unknown) | undefined;
// A throttle to prevent sending
private previewUpdatePositionThrottle = new StateThrottle(
{
position: [0, 0, 0],
orientation: [0, 0],
reflection: [0, 0, 0],
} as MoveState,
(prev, { position, orientation, reflection }: MoveState) => {
return {
state: { position, orientation, reflection },
allow:
!approxEquals(position, prev.position) ||
!approxEquals2(orientation, prev.orientation) ||
!approxEquals(reflection, prev.reflection),
};
}
);
private previewUpdateEventThrottle = new EventThrottle(100);
constructor(
private readonly input: ClientInput,
private readonly resources: ClientResources,
private readonly table: ClientTable,
private readonly events: Events,
private readonly permissionsManager: PermissionsManager,
private readonly tweaks = resources.get("/tweaks")
) {
this.installListeners();
}
installListeners() {
const flipCb = () => {
if (this.isActive()) {
this.desireFlip = true;
}
};
const mirrorCb = () => {
if (this.isActive()) {
this.desireMirror = true;
}
};
this.input.emitter.on("flip", flipCb);
this.input.emitter.on("mirror", mirrorCb);
this.flipCallback = flipCb;
this.mirrorCallback = mirrorCb;
}
removeListeners() {
if (this.flipCallback) {
this.input.emitter.removeListener("flip", this.flipCallback);
}
if (this.mirrorCallback) {
this.input.emitter.removeListener("mirror", this.mirrorCallback);
}
}
clear() {
this.removeListeners();
}
intersect([v0, v1]: AABB, fn: (hit: AABB) => boolean | void) {
const ignoreSelfFn = (aabb: AABB, entity?: ReadonlyEntity) => {
if (!entity) {
fn(aabb);
}
};
CollisionHelper.intersect(
(id) => this.resources.get("/physics/boxes", id),
this.table,
this.resources.get("/ecs/metadata"),
[v0, v1],
ignoreSelfFn
);
}
private climbable(aabb: AABB, dir: Vec3) {
return canClimbBlock({
index: (...args) => this.intersect(...args),
aabb,
dir,
});
}
isActive() {
const placementPreview = this.resources.get("/groups/placement/preview");
return placementPreview.active();
}
updateSharedPreview() {
const placementPreview = this.resources.get("/groups/placement/preview");
const localPlayer = this.resources.get("/scene/local_player");
if (placementPreview.active()) {
if (
this.previewUpdateEventThrottle.testAndSet() &&
this.previewUpdatePositionThrottle.test({
position: placementPreview.position,
orientation: placementPreview.orientation,
reflection: placementPreview.reflection,
})
) {
const place = placementPreview.placementTensorTakeOwnership();
fireAndForget(
this.events.publish(
new UpdateGroupPreviewEvent({
id: localPlayer.id,
tensor: place.tensor.save(),
box: { v0: place.box[0], v1: place.box[1] },
blueprint_id: placementPreview.groupPlacementTensor.blueprintId,
})
)
);
place.tensor.delete();
}
} else {
const pid = localPlayer.player.previewId;
if (pid && this.previewUpdateEventThrottle.testAndSet()) {
const cp = this.resources.get("/ecs/c/group_preview_component", pid);
if (cp) {
fireAndForget(
this.events.publish(
new DeleteGroupPreviewEvent({ id: localPlayer.id })
)
);
}
}
}
}
preserveCenterPointDuringTransform(
placementPreview: GroupPlacementPreview,
transformFn: () => unknown
) {
// Because the origin point is in the corner, we also need to move the position to keep centering
const originalCenter = centerAABB(placementPreview.aabb());
transformFn();
const newCenter = centerAABB(placementPreview.aabb());
placementPreview.position = add(
placementPreview.position,
sub(originalCenter, newCenter)
);
}
handleCanActualize() {
const placementPreview = this.resources.get("/groups/placement/preview");
if (!placementPreview.active()) {
placementPreview.cannotActualizeReason = "Inactive group";
return;
}
if (
!aclAllowsPlacementForPlaceablePreview(
this.resources,
this.permissionsManager
)
) {
placementPreview.cannotActualizeReason = "No permissions to place here";
return;
}
const aabb = placementPreview.aabb();
const colliding = isCollidingJoined(
aabb,
this.localCollisionBoxes(),
(...args) => this.intersect(...args)
);
if (colliding) {
placementPreview.cannotActualizeReason = "Colliding with other builds";
return;
}
placementPreview.cannotActualizeReason = undefined;
}
localCollisionBoxes() {
const placementPreview = this.resources.get("/groups/placement/preview");
if (!placementPreview.active()) {
return [];
}
const aabb = placementPreview.aabb();
const localBoxes: AABB[] = [];
placementPreview.groupPlacementBoxDict?.scan((a) => {
localBoxes.push(
shiftAABB(placementPreview.transformAABB(a), scale(-1.0, aabb[0]))
);
});
return localBoxes;
}
handlePhysics(dt: number) {
const placementPreview = this.resources.get("/groups/placement/preview");
if (!placementPreview.active()) {
return;
}
const tweaks = this.resources.get("/tweaks");
const aabb = placementPreview.aabb();
const forward = Math.sign(this.input.motion("forward")) as -1 | 0 | 1;
const lateral = Math.sign(this.input.motion("lateral")) as -1 | 0 | 1;
const forces: Force[] = [];
const speed =
// Moving backwards is slower.
(forward < 0
? this.tweaks.playerPhysics.reverse
: this.tweaks.playerPhysics.forward) *
// Moving sideways is slower.
(lateral === 0 ? 1 : this.tweaks.playerPhysics.lateralMultiplier);
// Figure out what direction the player is moving.
const [_pitch, yaw] = placementPreview.camOrientation;
if (forward || lateral) {
forces.push(walkingForce(speed, yaw, forward, lateral));
}
const boxesIndex = (id: ShardId) =>
this.resources.get("/physics/boxes", id);
// Snapping force to be voxel aligned
forces.push(() => {
const nearestValidPosition = round(placementPreview.position);
const delta = sub(nearestValidPosition, placementPreview.position);
delta[1] = 0;
if (length(delta) < 0.01 || forward !== 0 || lateral !== 0) {
return [0, 0, 0];
}
const springForce = scale(
tweaks.youAreTheGroupSnappingCharacteristic,
delta
);
const dampingForce = scale(
-tweaks.youAreTheGroupDamping,
placementPreview.velocity
);
return add(springForce, dampingForce);
});
const localBoxes = this.localCollisionBoxes();
if (this.input.action("jump")) {
for (const box of localBoxes) {
const globalBox = shiftAABB(box, aabb[0]);
const onGround = grounded(
(...args) => CollisionHelper.intersectAABB(boxesIndex, ...args),
globalBox
);
if (onGround) {
forces.push(verticalForce(this.tweaks.playerPhysics.groundJump));
}
break;
}
}
const result = moveBodyJoined(
dt,
{
aabb: aabb,
velocity: [...placementPreview.velocity],
},
localBoxes,
GROUP_PLACEMENT_ENVIRONMENT_PARAMS,
(...args) => this.intersect(...args),
forces,
[]
);
placementPreview.position = add(
placementPreview.position,
result.movement.impulse
);
placementPreview.velocity = [...result.movement.velocity];
}
hidePreviewIfInactive() {
// If inventory selection has switched, stop showing placeable component
const placementPreview = this.resources.get("/groups/placement/preview");
const selection = this.resources.get("/hotbar/selection");
const itemReference = placementPreview.groupPlacementTensor.itemReference;
const slotRef = slotRefFromSelection(selection);
if (
placementPreview.active() &&
((!itemReference && slotRef) ||
(itemReference && !slotRef) ||
(itemReference &&
slotRef &&
!OwnedItemReferencesEqual(itemReference, slotRef)))
) {
stopShowingPlaceablePreview(this.resources);
}
}
handleFlipControls() {
const placementPreview = this.resources.get("/groups/placement/preview");
if (!placementPreview.active()) {
return;
}
if (this.desireFlip) {
this.preserveCenterPointDuringTransform(placementPreview, () => {
placementPreview.orientation = rotationToOrientation(
orientationToRotation([
placementPreview.orientation[0],
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
placementPreview.orientation[1] + Math.PI / 2,
])
);
});
this.desireFlip = false;
}
if (this.desireMirror) {
this.preserveCenterPointDuringTransform(placementPreview, () => {
placementPreview.reflection = [
placementPreview.reflection[0] ? 0 : 1,
placementPreview.reflection[1],
placementPreview.reflection[2],
];
});
this.desireMirror = false;
}
}
tick(dt: number) {
this.handleFlipControls();
this.handlePhysics(dt);
this.handleCanActualize();
this.updateSharedPreview();
this.hidePreviewIfInactive();
}
}
| 412 | 0.898442 | 1 | 0.898442 | game-dev | MEDIA | 0.400973 | game-dev | 0.967787 | 1 | 0.967787 |
andreasdr/tdme2 | 24,991 | ext/fbx/win64/include/fbxsdk/core/fbxpropertyhandle.h | /****************************************************************************************
Copyright (C) 2015 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
//! \file fbxpropertyhandle.h
#ifndef _FBXSDK_CORE_PROPERTY_HANDLE_H_
#define _FBXSDK_CORE_PROPERTY_HANDLE_H_
#include <fbxsdk/fbxsdk_def.h>
#include <fbxsdk/core/fbxconnectionpoint.h>
#include <fbxsdk/core/fbxpropertytypes.h>
#include <fbxsdk/core/fbxpropertydef.h>
#include <fbxsdk/fbxsdk_nsbegin.h>
class FbxPropertyPage;
class FbxPropertyHandle;
class FbxConnectionPointFilter;
//! \brief Class to manage property handle.
class FBXSDK_DLL FbxPropertyHandle
{
public:
/**
* \name Constructor and Destructor
*/
//@{
//! Create an instance
static FbxPropertyHandle Create();
/** Create an instance with given instance.
* \param pInstanceOf The given instance. */
static FbxPropertyHandle Create(const FbxPropertyHandle& pInstanceOf);
/** Create an instance with given name and type.
* \param pName Property name.
* \param pType Property type. */
static FbxPropertyHandle Create(const char* pName, EFbxType pType=eFbxUndefined);
/** Create an instance with given name and type info.
* \param pName
* \param pTypeInfo */
static FbxPropertyHandle Create(const char* pName, FbxPropertyHandle pTypeInfo);
/** If this property is root property, delete the property page, otherwise delete the property.
* \return If succeed, return true. */
bool Destroy();
//! Default constructor.
FbxPropertyHandle();
/** Copy constructor.
* \param pAddress FbxPropertyHandle copied to this one. */
FbxPropertyHandle(const FbxPropertyHandle& pAddress);
//! Destructor
~FbxPropertyHandle();
/** Character constructor.
* \param pPage
* \param pId */
FbxPropertyHandle(FbxPropertyPage* pPage, FbxInt pId=FBXSDK_PROPERTY_ID_ROOT);
//@}
/**
* \name Assignment and basic info
*/
//@{
/** FbxPropertyHandle assignment operator.
* \param pHandle FbxPropertyHandle assigned to this one. */
FbxPropertyHandle& operator=(const FbxPropertyHandle& pHandle);
/** Equality operator.
* \param pHandle FbxPropertyHandle compared with this one.
* \return \c True if equal, \c false otherwise. */
bool operator==(const FbxPropertyHandle& pHandle) const;
/** Inequality operator.
* \param pHandle FbxPropertyHandle compared with this one.
* \return \c True if unequal, \c false otherwise. */
bool operator!=(const FbxPropertyHandle& pHandle) const;
/** Lesser operator, used to sort property handle in map.
* \param pHandle The property handle compared to this property handle.
* \return \c true if less, \c false otherwise. */
bool operator< (const FbxPropertyHandle& pHandle) const;
/** Greater operator, used to sort property handle in map.
* \param pProperty The property handle compared to this property handle.
* \return \c true if greater, \c false otherwise. */
bool operator> (const FbxPropertyHandle& pHandle) const;
/** Compare type info together
* \param pHandle FbxPropertyHandle compared with this one.
* \return \c True if equal, \c false otherwise. */
bool Is(const FbxPropertyHandle& pHandle) const;
//! Judge validity
bool Valid() const;
//! Get the property name
const char* GetName() const;
//! Get the property label
const char* GetLabel() const;
/** Set a label to the property
* \param pLabel The given label string
* \return \c true if successful. */
bool SetLabel(const char* pLabel);
//! Get the property type
EFbxType GetType() const;
//! Get the property type info
FbxPropertyHandle GetTypeInfo() const;
//! Get the property attribute state
FbxPropertyFlags::EFlags GetFlags() const;
/** Gets the inheritance type for the given flag.
* \param pFlags The flag to query
* \param pCheckReferences Decide whether check instance. If it is true, check instance.
* \return The inheritance type */
FbxPropertyFlags::EInheritType GetFlagsInheritType(FbxPropertyFlags::EFlags pFlags, bool pCheckReferences) const;
/** According the given parameter Change the attributes of the property.
* \param pFlags The given flags used as mask.
* \param pValue If pValue is true, set mask with given flags, otherwise unset mask with given flags.
* \return If succeed, return true. */
bool ModifyFlags(FbxPropertyFlags::EFlags pFlags, bool pValue);
/**Sets the inheritance type for the given flag
* \param pFlags The flag to set
* \param pType The inheritance type to set
* \return If succeed, return true. */
bool SetFlagsInheritType(FbxPropertyFlags::EFlags pFlags, FbxPropertyFlags::EInheritType pType);
//! Get the property user data.
void* GetUserData() const;
/** Set user data to the property
* \param pUserData The given user data
* \return If succeed, return true. */
bool SetUserData(const void* pUserData);
//! Get the property user tag
int GetUserTag() const;
/** Set user tag to the property
* \param pUserData The given user tag
* \return If succeed, return true. */
bool SetUserTag(int pUserData);
//@}
/**
* \name Enum management
*/
//@{
/** Add new value at the end of the enum list in the property.
* \param pStringValue The given new value
* \return The index of the value. */
int AddEnumValue(const char* pStringValue);
/** Insert new value at the given index of the enum list in property.
* \param pIndex The given index
* \param pStringValue The given new value */
void InsertEnumValue(int pIndex, const char* pStringValue);
/** Get the enum count of enum list in property
* \return The enum count of enum list in property */
int GetEnumCount();
/** Set value at the given index of the enum list in the property.
* \param pIndex The given index
* \param pStringValue The given new value used to instead the old value. */
void SetEnumValue(int pIndex, const char* pStringValue);
/** Remove the value at the index of the enum list in the property.
* \param pIndex The given index */
void RemoveEnumValue(int pIndex);
/** Get the value at the index of enum list in the property.
* \param pIndex The given index
* \return The value at the given index */
char* GetEnumValue(int pIndex);
//@}
/**
* \name Child and Struct management
*/
//@{
//! Create the map for find property in the property page
void BeginCreateOrFindProperty();
//! Clear the map which created for find property.
void EndCreateOrFindProperty();
/** Judge if the property is the root property.
* \return Return true if this property is root property. */
inline bool IsRoot() const { return ( mPage && mId == 0 ) ? true : false; }
/** Judge if the property is the child property of the given parent property.
* \param pParent The given parent property handle
* \return Return true if this property is child of given property. */
bool IsChildOf(const FbxPropertyHandle& pParent) const;
/** Judge if the property is descendent property of the given property.
* \param pParent The given parent property handle
* \return Return true if this property is descendant of given property. */
bool IsDescendentOf(const FbxPropertyHandle& pParent) const;
/** Set parent property handle.No matter what enters,the result is always false.
* \param pOther
* \return False */
bool SetParent(const FbxPropertyHandle& pOther );
/** Add a property to the property page.
* \param pName The name of property.
* \param pTypeInfo The added property's type info.
* \return The handle of the new added property */
FbxPropertyHandle Add(const char* pName, const FbxPropertyHandle& pTypeInfo);
/** Get parent property
* \return If the parent property exists, return the property handle,otherwise return -1. */
FbxPropertyHandle GetParent() const;
/** Get child property
* \return If the child property is exist, return the property handle,otherwise return -1. */
FbxPropertyHandle GetChild() const;
/** Get sibling property
* \return If the sibling property is exist, return the property handle,otherwise return -1. */
FbxPropertyHandle GetSibling() const;
/** Get first descendent property
* \return If the descendent property is exist, return the first descendent property handle,otherwise return -1. */
FbxPropertyHandle GetFirstDescendent() const;
/** Get first descendent property which after the given property
* \param pHandle The given property handle
* \return If the descendent property can be found after the given property,
* return the first found property handle,otherwise return -1. */
FbxPropertyHandle GetNextDescendent(const FbxPropertyHandle& pHandle) const;
/** Find the property with given name
* \param pName The given property name
* \param pCaseSensitive Decide if the given property name is case sensitive
* \return Return a property handle which be created with the found property. */
FbxPropertyHandle Find(const char* pName, bool pCaseSensitive) const;
/** Find the property with given name and type info.
* \param pName The given property name
* \param pTypeInfo The given property type info
* \param pCaseSensitive Decide if the given property name is case sensitive
* \return Return a property handle which be created with the found property. */
FbxPropertyHandle Find(const char* pName, const FbxPropertyHandle& pTypeInfo, bool pCaseSensitive) const;
/** Separate the given name by children separator string and then find the property.The step is
* strip the first part of the name and search, if the property can be found, strip the second part
* of the name and continue search, until no property be found,then return the last found property.
* \param pName The given property name
* \param pChildrenSeparator The given children separator string
* \param pCaseSensitive Decide if the given property name is case sensitive
* \return Return a property handle which be created with the found property. */
FbxPropertyHandle Find(const char* pName, const char* pChildrenSeparator, bool pCaseSensitive) const;
/** Separate the given name by children separator string and then find the property.The step is
* strip the first part of the name and search, if the property can be found, strip the second part
* of the name and continue search, until no property be found,then return the last found property.
* \param pName The given property name
* \param pChildrenSeparator The given children separator string
* \param pTypeInfo The given property type info
* \param pCaseSensitive Decide if the given property name is case sensitive
* \return Return a property handle which be created with the found property. */
FbxPropertyHandle Find(const char* pName, const char* pChildrenSeparator, const FbxPropertyHandle& pTypeInfo, bool pCaseSensitive) const;
//@}
/**
* \name Connection management
*/
//@{
/** Connect source property.
* \param pSrc The given source property
* \param pType The given property type
* \return If connect successfully, return true,otherwise, return false. */
bool ConnectSrc(const FbxPropertyHandle& pSrc, const FbxConnection::EType pType=FbxConnection::eDefault);
/** Get source properties' count.
* \param pFilter The filter used to get sub connection point. If it is not zero, return the source count of the sub connection point.
* Otherwise, return the src count of this property.
* \return The count of source properties */
int GetSrcCount(FbxConnectionPointFilter* pFilter=0) const;
/** Get source property with the given index.
* \param pFilter The filter used to get sub connection point. If it is not zero, return the source property of the sub connection point.
* Otherwise, return the source property of this property.
* \param pIndex The given index
* \return The source property handle. */
FbxPropertyHandle GetSrc(FbxConnectionPointFilter* pFilter=0, int pIndex=0) const;
/** Disconnect source property.
* \param pSrc The given source property
* \return If disconnect successfully, return true, otherwise return false. */
bool DisconnectSrc(const FbxPropertyHandle& pSrc);
/** Judge if it is connected with the given source property.
* \param pSrc The given source property
* \return If it is connected, return true, otherwise return false. */
bool IsConnectedSrc(const FbxPropertyHandle& pSrc);
/** Connect destination property.
* \param pDst The given destination property
* \param pType The given property type
* \return If connect successfully, return true,otherwise, return false. */
bool ConnectDst(const FbxPropertyHandle& pDst, const FbxConnection::EType pType=FbxConnection::eDefault);
/** Get destination properties' count.
* \param pFilter The filter used to get sub connection point.If it is not zero,return the destination count of the sub connection point.
* Otherwise, return the destination count of this property.
* \return The count of destination properties */
int GetDstCount(FbxConnectionPointFilter* pFilter=0) const;
/** Get destination property with the given index.
* \param pFilter The filter used to get sub connection point.If it is not zero,return the destination property of the sub connection point.
* Otherwise, return the destination property of this property.
* \param pIndex The given index
* \return The destination property handle. */
FbxPropertyHandle GetDst(FbxConnectionPointFilter* pFilter=0, int pIndex=0) const;
/** Disconnect destination property.
* \param pDst The given destination property
* \return If disconnect successfully, return true,otherwise, return false. */
bool DisconnectDst(const FbxPropertyHandle& pDst);
/** Judge if it is connected with the given destination property.
* \param pDst The given destination property
* \return If it is connected, return true,otherwise, return false. */
bool IsConnectedDst(const FbxPropertyHandle& pDst);
//! Clear connect cache
void ClearConnectCache();
//! Clear all connect without sending any notification (Internal use ONLY)
void WipeAllConnections();
//@}
/** \name Limits Functions
* Minimum and maximum value limits can be associated with properties, but FBX
* will not verify that these limits are respected. FBX however will store and
* retrieve limits from files, and will assure that they are persistent in memory
* while the property handle object exists.
*
* Soft minimums and maximums values are specifying a second set of limits that can be
* used for UI objects such as sliders. FBX will handle them the same way it does
* with the normal limits. */
//@{
/** Judge if this property has a minimum value.
* \return If the minimum value exist, return true,otherwise, return false. */
bool HasMin() const;
/** Get the minimum value and value type of this property.
* \param pValue The minimum value of this property.
* \param pValueType The value type of this property.
* \return If the minimum value exist, return true,otherwise, return false. */
bool GetMin(void* pValue, EFbxType pValueType) const;
/** Set the minimum value and value type for this property.
* \param pValue The given minimum value .
* \param pValueType The given value type .
* \return If it be set successfully, return true,otherwise, return false. */
bool SetMin(const void* pValue, EFbxType pValueType);
/** According the given value and its value type, set the minimum value and value type for this property.
* \param pValue The given value .
* \return If it be set successfully, return true,otherwise, return false.
*/
template <class T> inline bool SetMin(const T& pValue){ return SetMin(&pValue, FbxTypeOf(pValue)); }
/** Get the minimum value of this property.
* \param pFBX_TYPE Not used in this function. This is a dummy argument for
* the correct instantiation of the templated function.
* \return The minimum value of this property */
template <class T> inline T GetMin(const T* pFBX_TYPE) const { T lValue; GetMin(&lValue, FbxTypeOf(lValue)); return lValue; }
/** Judge if this property has soft minimum value.
* \return If the soft minimum value exist, return true,otherwise, return false. */
bool HasSoftMin() const;
/** Get the soft minimum value and value type of this property.
* \param pValue The soft minimum value of this property.
* \param pValueType The value type of this property.
* \return If the soft minimum value exist, return true,otherwise, return false. */
bool GetSoftMin(void* pValue, EFbxType pValueType) const;
/** Set the soft minimum value and value type for this property.
* \param pValue The given soft minimum value .
* \param pValueType The given value type .
* \return If it be set successfully, return true,otherwise, return false. */
bool SetSoftMin(const void* pValue, EFbxType pValueType);
/** According the given value and its value type, set the soft minimum value and value type for this property.
* \param pValue The given value .
* \return If it be set successfully, return true,otherwise, return false. */
template <class T> inline bool SetSoftMin(const T& pValue){ return SetSoftMin(&pValue, FbxTypeOf(pValue)); }
/** Get the soft minimum value of this property.
* \param pFBX_TYPE Not used in this function. This is a dummy argument for
* the correct instantiation of the templated function.
* \return The soft minimum value of this property */
template <class T> inline T GetSoftMin(const T* pFBX_TYPE) const { T lValue; GetSoftMin(&lValue, FbxTypeOf(lValue)); return lValue; }
/** Judge if this property has maximum value.
* \return If the maximum value exist, return true,otherwise, return false. */
bool HasMax() const;
/** Get the maximum value and value type of this property.
* \param pValue The maximum value of this property.
* \param pValueType The value type of this property.
* \return If the maximum value exist, return true,otherwise, return false. */
bool GetMax(void* pValue, EFbxType pValueType) const;
/** Set the maximum value and value type for this property.
* \param pValue The given maximum value .
* \param pValueType The given value type .
* \return If it be set successfully, return true,otherwise, return false. */
bool SetMax(const void* pValue, EFbxType pValueType);
/** According the given value and its value type, set the maximum value and value type for this property.
* \param pValue The given value .
* \return If it be set successfully, return true,otherwise, return false. */
template <class T> inline bool SetMax(const T& pValue){ return SetMax(&pValue, FbxTypeOf(pValue)); }
/** Get the maximum value of this property.
* \param pFBX_TYPE Not used in this function. This is a dummy argument for
* the correct instantiation of the templated function.
* \return The maximum value of this property */
template <class T> inline T GetMax(const T* pFBX_TYPE) const { T lValue; GetMax(&lValue, FbxTypeOf(lValue)); return lValue; }
/** Judge if this property has soft maximum value.
* \return If the soft maximum value exist, return true,otherwise, return false. */
bool HasSoftMax() const;
/** Get the soft maximum value and value type of this property.
* \param pValue The soft maximum value of this property.
* \param pValueType The value type of this property.
* \return If the soft maximum value exist, return true,otherwise, return false. */
bool GetSoftMax(void* pValue, EFbxType pValueType) const;
/** Set the soft maximum value and value type for this property.
* \param pValue The given soft maximum value .
* \param pValueType The given value type .
* \return If it be set successfully, return true,otherwise, return false. */
bool SetSoftMax(const void* pValue, EFbxType pValueType);
/** According the given value and its value type, set the soft maximum value and value type for this property.
* \param pValue The given value .
* \return If it be set successfully, return true,otherwise, return false. */
template <class T> inline bool SetSoftMax(const T& pValue){ return SetSoftMax(&pValue, FbxTypeOf(pValue)); }
/** Get the soft maximum value of this property.
* \param pFBX_TYPE Not used in this function. This is a dummy argument for
* the correct instantiation of the templated function.
* \return The soft maximum value of this property */
template <class T> inline T GetSoftMax(const T* pFBX_TYPE) const { T lValue; GetSoftMax(&lValue, FbxTypeOf(lValue)); return lValue; }
//@}
/**
* \name Value
*/
//@{
/** Get value inherit type of this property.
* \param pCheckReferences If it is true,check instance of this property page,otherwise,only check this page.
* \return The value inherit type of this property */
FbxPropertyFlags::EInheritType GetValueInheritType(bool pCheckReferences) const;
/** Set value inherit type for this property .
* \param pType The given value inherit type.
* \return If set successfully, return true,otherwise, return false. */
bool SetValueInheritType(FbxPropertyFlags::EInheritType pType);
/** Get default value and value type of this property .
* \param pValue The gotten default value of this property.
* \param pValueType The gotten default value type of this property.
* \return If default value be gotten successfully, return true,otherwise, return false. */
bool GetDefaultValue(void* pValue, EFbxType pValueType) const;
/** Get value and value type of this property .
* \param pValue The gotten value of this property.
* \param pValueType The gotten value type of this property.
* \return If value be gotten successfully, return true,otherwise, return false. */
bool Get(void* pValue, EFbxType pValueType) const;
/** Set property value and value type for this property.
* \param pValue The given property value .
* \param pValueType The given property value type
* \param pCheckValueEquality If it is true, when the given value is equal with
* the property value, the property value will not be set.
* \return If the property value be set successfully, return true,otherwise, return false. */
bool Set(const void* pValue, EFbxType pValueType, bool pCheckValueEquality);
/** Set property value with the given value .
* \param pValue The given value .
* \return If set successfully, return true,otherwise, return false. */
template <class T> inline bool Set(const T& pValue){ return Set(&pValue, FbxTypeOf(pValue)); }
/** get property value.
* \param pFBX_TYPE Not be used.
* \return The gotten property value. */
template <class T> inline T Get(const T* pFBX_TYPE) const { T lValue; Get(&lValue, FbxTypeOf(lValue)); return lValue; }
//@}
/**
* \name Page settings
*/
//@{
/** Set the property page data pointer.
* \param pData The given page data pointer. */
void SetPageDataPtr(void* pData);
/** Get property page data pointer.
* \return The gotten property page data pointer. */
void* GetPageDataPtr() const;
//@}
/**
* \name Page Internal Entry Management
*/
//@{
/** Push properties to parent instance.
* \return If push successful return true,otherwise,return false. */
bool PushPropertiesToParentInstance();
//@}
/**
* \name Reference Management
*/
//@{
/** Judge if this property page is a instance of other page.
* \return If this property page is a instance of other page, return true,otherwise,return false. */
bool IsAReferenceTo(void) const;
/** Get the property page which this property page make reference to
* \return The property page which this property page make reference to */
void* GetReferenceTo(void) const;
/** Judge if this property page is referenced by other pages.
* \return If this property page is referenced by other pages, return true,otherwise,return false. */
bool IsReferencedBy(void) const;
/** Get the count of property pages which make reference to this property page.
* \return The count of property pages which make reference to this property page. */
int GetReferencedByCount(void) const;
/** According the given index,get the property page which make reference to this property page.
* \param pIndex The given index
* \return The pointer to the property page which reference to this property page and be found by index. */
void* GetReferencedBy(int pIndex) const;
//@}
private:
FbxPropertyPage* mPage;
FbxInt mId;
};
#include <fbxsdk/fbxsdk_nsend.h>
#endif /* _FBXSDK_CORE_PROPERTY_HANDLE_H_ */
| 412 | 0.980287 | 1 | 0.980287 | game-dev | MEDIA | 0.656303 | game-dev | 0.852971 | 1 | 0.852971 |
jiaxwu/gommon | 1,514 | pool/level/pool_test.go | package level
import (
"math/rand"
"sync/atomic"
"testing"
"github.com/jiaxwu/gommon/math"
"github.com/jiaxwu/gommon/pool"
)
const (
blocks = 64
blockSize = 1024
)
var block = make([]byte, blockSize)
func BenchmarkBytePoolRandomBlcoks(b *testing.B) {
var eqCap int64
pool := pool.NewBytePool(0, 0)
for n := 0; n < b.N; n++ {
blocks := rand.Intn(blocks) + 1
needCap := blocks * blockSize
b := pool.Get()
if cap(b) >= needCap && cap(b) <= needCap*2 {
atomic.AddInt64(&eqCap, 1)
}
for i := 0; i < blocks; i++ {
b = append(b, block...)
}
pool.Put(b)
}
b.Logf("eq cap cnt: %d", eqCap)
}
func BenchmarkLevelBytePoolRandomBlcoks(b *testing.B) {
var eqCap int64
var pool = NewBytePool(blockSize, math.Log2(blocks)+1)
for n := 0; n < b.N; n++ {
blocks := rand.Intn(blocks) + 1
needCap := blocks * blockSize
b := pool.Get(needCap)
if cap(b) >= needCap && cap(b) <= needCap*2 {
atomic.AddInt64(&eqCap, 1)
}
for i := 0; i < blocks; i++ {
b = append(b, block...)
}
pool.Put(b)
}
b.Logf("eq cap cnt: %d", eqCap)
}
func BenchmarkLevelBufferPoolRandomBlcoks(b *testing.B) {
var eqCap int64
var pool = NewBufferPool(blockSize, math.Log2(blocks)+1)
for n := 0; n < b.N; n++ {
blocks := rand.Intn(blocks) + 1
needCap := blocks * blockSize
b := pool.Get(needCap)
if b.Cap() >= needCap && b.Cap() <= needCap*2 {
atomic.AddInt64(&eqCap, 1)
}
for i := 0; i < blocks; i++ {
b.Write(block)
}
pool.Put(b)
}
b.Logf("eq cap cnt: %d", eqCap)
}
| 412 | 0.923208 | 1 | 0.923208 | game-dev | MEDIA | 0.523169 | game-dev | 0.92092 | 1 | 0.92092 |
DigitalMars/dmc | 8,731 | mfc/SRC/32-BIT/MAP_SS.CPP |
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1995 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
/////////////////////////////////////////////////////////////////////////////
//
// Implementation of parmeterized Map from CString to value
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#ifdef AFX_COLL2_SEG
#pragma code_seg(AFX_COLL2_SEG)
#endif
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "elements.h" // used for special creation
#define new DEBUG_NEW
/////////////////////////////////////////////////////////////////////////////
CMapStringToString::CMapStringToString(int nBlockSize)
{
ASSERT(nBlockSize > 0);
m_pHashTable = NULL;
m_nHashTableSize = 17; // default size
m_nCount = 0;
m_pFreeList = NULL;
m_pBlocks = NULL;
m_nBlockSize = nBlockSize;
}
inline UINT CMapStringToString::HashKey(LPCTSTR key) const
{
UINT nHash = 0;
while (*key)
nHash = (nHash<<5) + nHash + *key++;
return nHash;
}
void CMapStringToString::InitHashTable(
UINT nHashSize, BOOL bAllocNow)
//
// Used to force allocation of a hash table or to override the default
// hash table size of (which is fairly small)
{
ASSERT_VALID(this);
ASSERT(m_nCount == 0);
ASSERT(nHashSize > 0);
if (m_pHashTable != NULL)
{
// free hash table
delete[] m_pHashTable;
m_pHashTable = NULL;
}
if (bAllocNow)
{
m_pHashTable = new CAssoc* [nHashSize];
memset(m_pHashTable, 0, sizeof(CAssoc*) * nHashSize);
}
m_nHashTableSize = nHashSize;
}
void CMapStringToString::RemoveAll()
{
ASSERT_VALID(this);
if (m_pHashTable != NULL)
{
// destroy elements
for (UINT nHash = 0; nHash < m_nHashTableSize; nHash++)
{
CAssoc* pAssoc;
for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL;
pAssoc = pAssoc->pNext)
{
DestructElement(&pAssoc->key); // free up string data
DestructElement(&pAssoc->value);
}
}
// free hash table
delete [] m_pHashTable;
m_pHashTable = NULL;
}
m_nCount = 0;
m_pFreeList = NULL;
m_pBlocks->FreeDataChain();
m_pBlocks = NULL;
}
CMapStringToString::~CMapStringToString()
{
RemoveAll();
ASSERT(m_nCount == 0);
}
/////////////////////////////////////////////////////////////////////////////
// Assoc helpers
// same as CList implementation except we store CAssoc's not CNode's
// and CAssoc's are singly linked all the time
CMapStringToString::CAssoc*
CMapStringToString::NewAssoc()
{
if (m_pFreeList == NULL)
{
// add another block
CPlex* newBlock = CPlex::Create(m_pBlocks, m_nBlockSize,
sizeof(CMapStringToString::CAssoc));
// chain them into free list
CMapStringToString::CAssoc* pAssoc =
(CMapStringToString::CAssoc*) newBlock->data();
// free in reverse order to make it easier to debug
pAssoc += m_nBlockSize - 1;
for (int i = m_nBlockSize-1; i >= 0; i--, pAssoc--)
{
pAssoc->pNext = m_pFreeList;
m_pFreeList = pAssoc;
}
}
ASSERT(m_pFreeList != NULL); // we must have something
CMapStringToString::CAssoc* pAssoc = m_pFreeList;
m_pFreeList = m_pFreeList->pNext;
m_nCount++;
ASSERT(m_nCount > 0); // make sure we don't overflow
memcpy(&pAssoc->key, &afxEmptyString, sizeof(CString));
ConstructElement(&pAssoc->value);
return pAssoc;
}
void CMapStringToString::FreeAssoc(CMapStringToString::CAssoc* pAssoc)
{
DestructElement(&pAssoc->key); // free up string data
DestructElement(&pAssoc->value);
pAssoc->pNext = m_pFreeList;
m_pFreeList = pAssoc;
m_nCount--;
ASSERT(m_nCount >= 0); // make sure we don't underflow
// if no more elements, cleanup completely
if (m_nCount == 0)
RemoveAll();
}
CMapStringToString::CAssoc*
CMapStringToString::GetAssocAt(LPCTSTR key, UINT& nHash) const
// find association (or return NULL)
{
nHash = HashKey(key) % m_nHashTableSize;
if (m_pHashTable == NULL)
return NULL;
// see if it exists
CAssoc* pAssoc;
for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext)
{
if (pAssoc->key == key)
return pAssoc;
}
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
BOOL CMapStringToString::Lookup(LPCTSTR key, CString& rValue) const
{
ASSERT_VALID(this);
UINT nHash;
CAssoc* pAssoc = GetAssocAt(key, nHash);
if (pAssoc == NULL)
return FALSE; // not in map
rValue = pAssoc->value;
return TRUE;
}
BOOL CMapStringToString::LookupKey(LPCTSTR key, LPCTSTR& rKey) const
{
ASSERT_VALID(this);
UINT nHash;
CAssoc* pAssoc = GetAssocAt(key, nHash);
if (pAssoc == NULL)
return FALSE; // not in map
rKey = pAssoc->key;
return TRUE;
}
CString& CMapStringToString::operator[](LPCTSTR key)
{
ASSERT_VALID(this);
UINT nHash;
CAssoc* pAssoc;
if ((pAssoc = GetAssocAt(key, nHash)) == NULL)
{
if (m_pHashTable == NULL)
InitHashTable(m_nHashTableSize);
// it doesn't exist, add a new Association
pAssoc = NewAssoc();
pAssoc->nHashValue = nHash;
pAssoc->key = key;
// 'pAssoc->value' is a constructed object, nothing more
// put into hash table
pAssoc->pNext = m_pHashTable[nHash];
m_pHashTable[nHash] = pAssoc;
}
return pAssoc->value; // return new reference
}
BOOL CMapStringToString::RemoveKey(LPCTSTR key)
// remove key - return TRUE if removed
{
ASSERT_VALID(this);
if (m_pHashTable == NULL)
return FALSE; // nothing in the table
CAssoc** ppAssocPrev;
ppAssocPrev = &m_pHashTable[HashKey(key) % m_nHashTableSize];
CAssoc* pAssoc;
for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext)
{
if (pAssoc->key == key)
{
// remove it
*ppAssocPrev = pAssoc->pNext; // remove from list
FreeAssoc(pAssoc);
return TRUE;
}
ppAssocPrev = &pAssoc->pNext;
}
return FALSE; // not found
}
/////////////////////////////////////////////////////////////////////////////
// Iterating
void CMapStringToString::GetNextAssoc(POSITION& rNextPosition,
CString& rKey, CString& rValue) const
{
ASSERT_VALID(this);
ASSERT(m_pHashTable != NULL); // never call on empty map
CAssoc* pAssocRet = (CAssoc*)rNextPosition;
ASSERT(pAssocRet != NULL);
if (pAssocRet == (CAssoc*) BEFORE_START_POSITION)
{
// find the first association
for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++)
if ((pAssocRet = m_pHashTable[nBucket]) != NULL)
break;
ASSERT(pAssocRet != NULL); // must find something
}
// find next association
ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc)));
CAssoc* pAssocNext;
if ((pAssocNext = pAssocRet->pNext) == NULL)
{
// go to next bucket
for (UINT nBucket = pAssocRet->nHashValue + 1;
nBucket < m_nHashTableSize; nBucket++)
if ((pAssocNext = m_pHashTable[nBucket]) != NULL)
break;
}
rNextPosition = (POSITION) pAssocNext;
// fill in return data
rKey = pAssocRet->key;
rValue = pAssocRet->value;
}
/////////////////////////////////////////////////////////////////////////////
// Serialization
void CMapStringToString::Serialize(CArchive& ar)
{
ASSERT_VALID(this);
CObject::Serialize(ar);
if (ar.IsStoring())
{
ar.WriteCount(m_nCount);
if (m_nCount == 0)
return; // nothing more to do
ASSERT(m_pHashTable != NULL);
for (UINT nHash = 0; nHash < m_nHashTableSize; nHash++)
{
CAssoc* pAssoc;
for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL;
pAssoc = pAssoc->pNext)
{
ar << pAssoc->key;
ar << pAssoc->value;
}
}
}
else
{
DWORD nNewCount = ar.ReadCount();
CString newKey;
CString newValue;
while (nNewCount--)
{
ar >> newKey;
ar >> newValue;
SetAt(newKey, newValue);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Diagnostics
#ifdef _DEBUG
void CMapStringToString::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
dc << "with " << m_nCount << " elements";
if (dc.GetDepth() > 0)
{
// Dump in format "[key] -> value"
CString key;
CString val;
POSITION pos = GetStartPosition();
while (pos != NULL)
{
GetNextAssoc(pos, key, val);
dc << "\n\t[" << key << "] = " << val;
}
}
dc << "\n";
}
void CMapStringToString::AssertValid() const
{
CObject::AssertValid();
ASSERT(m_nHashTableSize > 0);
ASSERT(m_nCount == 0 || m_pHashTable != NULL);
// non-empty map should have hash table
}
#endif //_DEBUG
#ifdef AFX_INIT_SEG
#pragma code_seg(AFX_INIT_SEG)
#endif
IMPLEMENT_SERIAL(CMapStringToString, CObject, 0)
/////////////////////////////////////////////////////////////////////////////
| 412 | 0.968184 | 1 | 0.968184 | game-dev | MEDIA | 0.483021 | game-dev | 0.976893 | 1 | 0.976893 |
HeBianGu/WPF-ControlBase | 3,352 | Source/Application/HeBianGu.App.Touch.Share/Model/ModelBase/LinkActionEntity.cs | using HeBianGu.Service.Mvc;
using System;
using System.Threading.Tasks;
using System.Windows;
namespace HeBianGu.App.Touch
{
/// <summary> 测量具体项目基类</summary>
internal abstract class LinkActionEntity : LinkAction, IMeasure
{
#region - 属性 -
private bool _success;
/// <summary> 是否测量成功 用于下标状态显示 </summary>
public bool Success
{
get { return _success; }
set
{
_success = value;
RaisePropertyChanged("Success");
}
}
private Visibility _visbleNext = Visibility.Visible;
/// <summary> 下一项是否可见 </summary>
public Visibility VisbleNext
{
get { return _visbleNext; }
set
{
_visbleNext = value;
RaisePropertyChanged("VisbleNext");
}
}
private string _message;
/// <summary> 运行提示消息 </summary>
public string Message
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged("Message");
}
}
#endregion
#region - 命令 -
#endregion
#region - 方法 -
/// <summary> 提交后清理方法 </summary>
public void Clear()
{
Success = false;
Message = string.Empty;
IsCancel = false;
System.Reflection.PropertyInfo[] ps = GetType().GetProperties();
foreach (System.Reflection.PropertyInfo item in ps)
{
if (item.GetValue(this) is DataValueEntity entity)
{
entity.Value = null;
entity.IsBuzy = true;
}
}
}
public bool IsCancel { get; private set; }
public void Stop()
{
IsCancel = true;
Message = "用户已取消获取数据";
}
/// <summary> 开始测量 获取结果 </summary>
public virtual async Task<object> Start()
{
Message = "连接成功,测量中...";
await Task.Delay(2000);
if (new Random().Next(1, 8) == 2)
{
Message = "获取数据失败,请检查...";
return null;
}
if (IsCancel)
{
Message = "用户已取消获取数据";
return null;
}
Message = "测量完成";
return new object();
}
/// <summary> 初始化设备 </summary>
public virtual async Task<bool> BeginInit()
{
Message = "正在连接设备...";
await Task.Delay(2000);
if (new Random().Next(1, 8) == 2)
{
Message = "设备连接失败,请检查...";
return false;
}
return true;
}
public virtual bool IsAvailable()
{
System.Reflection.PropertyInfo[] ps = GetType().GetProperties();
// Do :检验所有DataValueEntity是否都可用
foreach (System.Reflection.PropertyInfo item in ps)
{
if (item.GetValue(this) is DataValueEntity entity)
{
if (!entity.IsAvailable()) return false;
}
}
return true;
}
#endregion
}
}
| 412 | 0.726911 | 1 | 0.726911 | game-dev | MEDIA | 0.621952 | game-dev | 0.88984 | 1 | 0.88984 |
dkfans/keeperfx | 12,185 | src/front_torture.c | /******************************************************************************/
// Free implementation of Bullfrog's Dungeon Keeper strategy game.
/******************************************************************************/
/** @file front_torture.c
* Torture screen displaying routines.
* @par Purpose:
* Functions to show and maintain the torture screen.
* Torture screen is a bonus, available after the game which has finished
* with imprisoning Lord of the Land.
* @par Comment:
* None.
* @author Tomasz Lis
* @date 11 May 2009 - 20 Jun 2009
* @par Copying and copyrights:
* 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.
*/
/******************************************************************************/
#include "pre_inc.h"
#include "front_torture.h"
#include "globals.h"
#include "bflib_basics.h"
#include "config_settings.h"
#include "bflib_sprite.h"
#include "bflib_sprfnt.h"
#include "bflib_filelst.h"
#include "bflib_dernc.h"
#include "bflib_keybrd.h"
#include "bflib_video.h"
#include "bflib_vidraw.h"
#include "bflib_mouse.h"
#include "bflib_sound.h"
#include "bflib_sndlib.h"
#include "config.h"
#include "engine_render.h"
#include "engine_textures.h"
#include "game_lghtshdw.h"
#include "player_data.h"
#include "room_list.h"
#include "kjm_input.h"
#include "front_simple.h"
#include "frontend.h"
#include "vidmode.h"
#include "vidfade.h"
#include "game_legacy.h"
#include "keeperfx.hpp"
#include "post_inc.h"
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************/
static long torture_left_button;
static long torture_sprite_direction;
static long torture_end_sprite;
static long torture_sprite_frame;
static long torture_door_selected;
static struct DoorSoundState door_sound_state[TORTURE_DOORS_COUNT];
static struct TortureState torture_state;
static unsigned char *torture_background;
static unsigned char *torture_palette;
extern struct DoorDesc doors[TORTURE_DOORS_COUNT];
extern struct TbSpriteSheet *fronttor_sprites;
long torture_doors_available = TORTURE_DOORS_COUNT;
/******************************************************************************/
#ifdef __cplusplus
}
#endif
/******************************************************************************/
void torture_play_sound(long door_id, TbBool state)
{
if ((door_id < 0) || (door_id >= TORTURE_DOORS_COUNT))
return;
if (state)
{
play_non_3d_sample(doors[door_id].smptbl_id);
door_sound_state[door_id].current_volume = 0;
door_sound_state[door_id].volume_step = FULL_LOUDNESS / 16;
}
else
{
door_sound_state[door_id].volume_step = -(FULL_LOUDNESS / 16);
}
}
long torture_door_over_point(long x,long y)
{
int units_per_px = min(units_per_pixel, units_per_pixel_min * 16 / 10);
const int img_width = 640;
const int img_height = 480;
int w = img_width * units_per_px / 16;
int h = img_height * units_per_px / 16;
// Starting point coords
int spx = (LbScreenWidth() - w) >> 1;
int spy = (LbScreenHeight() - h) >> 1;
for (long i = 0; i < torture_doors_available; i++)
{
struct DoorDesc* door = &doors[i];
if ((x >= spx + door->pos_x * units_per_px / 16) && (x < spx + door->pos_x * units_per_px / 16 + door->width * units_per_px / 16))
if ((y >= spy + door->pos_y * units_per_px / 16) && (y < spy + door->pos_y * units_per_px / 16 + door->height * units_per_px / 16))
return i;
}
return -1;
}
void fronttorture_unload(void)
{
for (int i = 0; i < TORTURE_DOORS_COUNT; ++i) {
free_spritesheet(&doors[i].sprites);
}
free_spritesheet(&fronttor_sprites);
memcpy(&frontend_palette, frontend_backup_palette, PALETTE_SIZE);
StopAllSamples();
// Clearing the space used for torture graphics
clear_light_system(&game.lish);
clear_computer();
clear_things_and_persons_data();
clear_mapmap();
clear_slabs();
clear_rooms();
clear_dungeons();
}
void fronttorture_load(void)
{
frontend_load_data_from_cd();
memcpy(frontend_backup_palette, &frontend_palette, PALETTE_SIZE);
// Texture blocks memory isn't used here, so reuse it instead of allocating
unsigned char* ptr = block_mem;
// Load RAW/PAL background
char* fname = prepare_file_path(FGrp_LoData, "torture.raw");
torture_background = ptr;
long i = LbFileLoadAt(fname, ptr);
ptr += i;
fname = prepare_file_path(FGrp_LoData,"torture.pal");
torture_palette = ptr;
i = LbFileLoadAt(fname, ptr);
// Load DAT/TAB sprites for doors
for (int idx = 0; idx < TORTURE_DOORS_COUNT; ++idx) {
char tab_name[2048];
char dat_name[2048];
strcpy(tab_name, prepare_file_fmtpath(FGrp_LoData,"door%02d.tab", idx + 1));
strcpy(dat_name, prepare_file_fmtpath(FGrp_LoData,"door%02d.dat", idx + 1));
doors[idx].sprites = load_spritesheet(dat_name, tab_name);
if (!doors[idx].sprites) ERRORLOG("Unable to load torture door %d", idx + 1);
}
fronttor_sprites = load_spritesheet("ldata/fronttor.dat", "ldata/fronttor.tab");
if (!fronttor_sprites) ERRORLOG("Unable to load torture sprites");
frontend_load_data_reset();
memcpy(&frontend_palette, torture_palette, PALETTE_SIZE);
torture_state.action = 0;
torture_door_selected = -1;
torture_end_sprite = -1;
torture_sprite_direction = 0;
memset(door_sound_state, 0, TORTURE_DOORS_COUNT*sizeof(struct DoorSoundState));
struct PlayerInfo* player = get_my_player();
if (player->victory_state == VicS_WonLevel)
{
LbMouseChangeSpriteAndHotspot(get_sprite(fronttor_sprites, 1), 0, 0);
} else
{
LbMouseChangeSpriteAndHotspot(0, 0, 0);
}
torture_left_button = 0;
}
TbBool fronttorture_draw(void)
{
const int img_width = 640;
const int img_height = 480;
// Only 8bpp supported for now
if (LbGraphicsScreenBPP() != 8)
return false;
int units_per_px = min(units_per_pixel, units_per_pixel_min * 16 / 10);
int w = img_width * units_per_px / 16;
int h = img_height * units_per_px / 16;
// Starting point coords
int spx = (LbScreenWidth() - w) >> 1;
int spy = (LbScreenHeight() - h) >> 1;
copy_raw8_image_buffer(lbDisplay.WScreen,LbGraphicsScreenWidth(),LbGraphicsScreenHeight(),
w,h,spx,spy,torture_background,img_width,img_height);
for (int i = 0; i < torture_doors_available; i++)
{
const struct TbSprite* spr;
if (i == torture_door_selected)
{
spr = get_sprite(doors[i].sprites, torture_sprite_frame);
} else
{
spr = get_sprite(doors[i].sprites, 1);
}
LbSpriteDrawResized(spx + doors[i].pos_spr_x*units_per_px/16, spy + doors[i].pos_spr_y*units_per_px/16, units_per_px, spr);
}
return true;
}
void fronttorture_clear_state(void)
{
torture_state.action = 0;
torture_door_selected = -1;
}
void fronttorture_input(void)
{
long x;
long y;
PlayerNumber plyr_idx;
clear_packets();
struct PlayerInfo* player = get_my_player();
struct Packet* pckt = get_packet(my_player_number);
// Get inputs and create packet
if (player->victory_state == VicS_WonLevel)
{
if (left_button_clicked)
{
torture_left_button = 1;
left_button_clicked = 0;
}
if ((lbKeyOn[KC_SPACE]) || (lbKeyOn[KC_RETURN]) || (lbKeyOn[KC_ESCAPE]))
{
lbKeyOn[KC_SPACE] = 0;
lbKeyOn[KC_RETURN] = 0;
lbKeyOn[KC_ESCAPE] = 0;
pckt->action |= 0x01;
}
if (torture_left_button)
pckt->action |= 0x02;
if (left_button_held)
pckt->action |= 0x04;
pckt->actn_par1 = GetMouseX();
pckt->actn_par2 = GetMouseY();
}
// Exchange packet with other players
if ((game.system_flags & GSF_NetworkActive) != 0)
{
if (LbNetwork_Exchange(pckt, game.packets, sizeof(struct Packet)))
ERRORLOG("LbNetwork_Exchange failed");
}
// Determine the controlling player and get his mouse coords
for (plyr_idx=0; plyr_idx < PLAYERS_COUNT; plyr_idx++)
{
player = get_player(plyr_idx);
pckt = get_packet(plyr_idx);
if ((pckt->action != 0) && (player->victory_state == VicS_WonLevel))
break;
}
if (plyr_idx < PLAYERS_COUNT)
{
x = pckt->actn_par1;
y = pckt->actn_par2;
} else
{
plyr_idx = my_player_number;
player = get_player(plyr_idx);
pckt = get_packet(plyr_idx);
x = 0;
y = 0;
}
if ((pckt->action & 0x01) != 0)
{
frontend_set_state(FeSt_LEVEL_STATS);
if ((game.system_flags & GSF_NetworkActive) != 0)
LbNetwork_Stop();
return;
}
// Get active door
long door_id = torture_door_over_point(x, y);
if ((torture_door_selected != -1) && (torture_door_selected != door_id))
door_id = -1;
// Make the action
if (door_id == -1)
torture_left_button = 0;
switch (torture_state.action)
{
case 0:
if (door_id != -1)
{
torture_state.action = 1;
torture_sprite_direction = 1;
torture_door_selected = door_id;
torture_sprite_frame = 3;
torture_end_sprite = 7;
}
break;
case 1:
if (torture_sprite_frame == torture_end_sprite)
{
if (door_id == -1)
{
torture_state.action = 2;
torture_sprite_frame = 8;
torture_end_sprite = 4;
torture_sprite_direction = -1;
} else
if ((pckt->action & (0x02|0x04)) != 0)
{
torture_state.action = 3;
torture_left_button = 0;
torture_sprite_frame = 7;
torture_end_sprite = 11;
torture_sprite_direction = 1;
torture_play_sound(torture_door_selected, true);
}
}
break;
case 2:
if (torture_sprite_frame == torture_end_sprite)
{
torture_state.action = 0;
torture_door_selected = -1;
}
break;
case 3:
if (torture_sprite_frame == torture_end_sprite)
{
if (((pckt->action & 0x04) == 0) || (door_id == -1))
{
torture_state.action = 4;
torture_sprite_frame = 12;
torture_end_sprite = 8;
torture_sprite_direction = -1;
torture_play_sound(torture_door_selected, false);
}
}
break;
case 4:
if (torture_sprite_frame == torture_end_sprite)
{
torture_state.action = 1;
torture_sprite_frame = 7;
torture_end_sprite = 7;
}
break;
}
}
void fronttorture_update(void)
{
if (torture_state.action != 0)
{
if ( torture_sprite_frame != torture_end_sprite )
torture_sprite_frame += torture_sprite_direction;
}
SoundEmitterID emit_id = get_emitter_id(S3DGetSoundEmitter(Non3DEmitter));
for (int i = 0; i < TORTURE_DOORS_COUNT; i++)
{
struct DoorDesc* door = &doors[i];
struct DoorSoundState* doorsnd = &door_sound_state[i];
if (doorsnd->volume_step != 0)
{
int volume = doorsnd->volume_step + doorsnd->current_volume;
if (volume <= 0)
{
volume = 0;
doorsnd->volume_step = 0;
stop_sample(emit_id, door->smptbl_id, 0);
} else
if (volume >= FULL_LOUDNESS)
{
volume = FULL_LOUDNESS;
doorsnd->volume_step = 0;
}
doorsnd->current_volume = volume;
if (volume > 0)
{
SetSampleVolume(emit_id, door->smptbl_id, (settings.sound_volume * volume) / FULL_LOUDNESS);
}
}
}
}
/******************************************************************************/
| 412 | 0.915753 | 1 | 0.915753 | game-dev | MEDIA | 0.793275 | game-dev | 0.692855 | 1 | 0.692855 |
1Remote/1Remote | 22,541 | Ui/Utils/PuTTY/Model/KittyConfig.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using _1RM.Service;
using _1RM.Utils.Tracing;
using Microsoft.Win32;
using Shawn.Utils;
namespace _1RM.Utils.PuTTY.Model
{
public class KittyConfig
{
public readonly List<PuttyConfigKeyValuePair> Options = new List<PuttyConfigKeyValuePair>();
public readonly string SessionId;
/// <summary>
/// read existed config files.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static List<PuttyConfigKeyValuePair> Read(string path)
{
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
return new List<PuttyConfigKeyValuePair>();
}
var lines = File.ReadAllLines(path);
var ret = new List<PuttyConfigKeyValuePair>(lines.Length);
foreach (var s in lines)
{
var line = s.Trim('\t', ' ');
var i0 = line.IndexOf(@"\", StringComparison.Ordinal);
if (line.EndsWith(@"\", StringComparison.Ordinal))
{
var para = line.Substring(0, i0);
var val = line.Substring(i0 + 1).TrimEnd('\\');
if (string.IsNullOrWhiteSpace(para) || string.IsNullOrWhiteSpace(val))
{
continue;
}
if (double.TryParse(val.Replace(',', '_'), out _))
{
ret.Add(new PuttyConfigKeyValuePair() { Key = para, Value = val, ValueKind = RegistryValueKind.DWord });
}
else
{
ret.Add(new PuttyConfigKeyValuePair() { Key = para, Value = val, ValueKind = RegistryValueKind.String });
}
}
}
return ret;
}
public KittyConfig(string sessionId)
{
SessionId = sessionId;
InitDefault();
// DISABLED ALT + F4
if (Options.Any(x => string.Equals(x.Key, EnumConfigKey.AltF4.ToString(), StringComparison.CurrentCultureIgnoreCase)))
{
var oldItem = Options.First(x => string.Equals(x.Key, EnumConfigKey.AltF4.ToString(), StringComparison.CurrentCultureIgnoreCase));
oldItem.Value = 0;
}
else
Set(EnumConfigKey.AltF4, 0x00000000); // DISABLED ALTF4
}
public void ApplyOverwriteSession(string? overwritePath = null)
{
if (!string.IsNullOrEmpty(overwritePath) && File.Exists(overwritePath))
{
var overWrite = Read(overwritePath!);
foreach (var item in overWrite)
{
if (Options.Any(x => string.Equals(x.Key, item.Key, StringComparison.CurrentCultureIgnoreCase)))
{
var oldItem = Options.First(x => string.Equals(x.Key, item.Key, StringComparison.CurrentCultureIgnoreCase));
oldItem.Value = item.Value;
oldItem.ValueKind = item.ValueKind;
}
else
{
Options.Add(item);
}
}
}
}
private void InitDefault()
{
Options.Clear();
#region Default
Set(EnumConfigKey.TerminalType, "xterm");
Set(EnumConfigKey.TerminalSpeed, "38400,38400");
Set(EnumConfigKey.TerminalModes, "INTR=A,QUIT=A,ERASE=A,KILL=A,EOF=A,EOL=A,EOL2=A,START=A,STOP=A,SUSP=A,DSUSP=A,REPRINT=A,WERASE=A,LNEXT=A,FLUSH=A,SWTCH=A,STATUS=A,DISCARD=A,IGNPAR=A,PARMRK=A,INPCK=A,ISTRIP=A,INLCR=A,IGNCR=A,ICRNL=A,IUCLC=A,IXON=A,IXANY=A,IXOFF=A,IMAXBEL=A,ISIG=A,ICANON=A,XCASE=A,ECHO=A,ECHOE=A,ECHOK=A,ECHONL=A,NOFLSH=A,TOSTOP=A,IEXTEN=A,ECHOCTL=A,ECHOKE=A,PENDIN=A,OPOST=A,OLCUC=A,ONLCR=A,OCRNL=A,ONOCR=A,ONLRET=A,CS7=A,CS8=A,PARENB=A,PARODD=A,");
Set(EnumConfigKey.ProxyExcludeList, "");
Set(EnumConfigKey.ProxyHost, "proxy");
Set(EnumConfigKey.ProxyUsername, "");
Set(EnumConfigKey.ProxyPassword, "");
Set(EnumConfigKey.ProxyTelnetCommand, "connect%20%25host%20%25port%5Cn");
Set(EnumConfigKey.Environment, "");
Set(EnumConfigKey.UserName, "");
Set(EnumConfigKey.LocalUserName, "");
Set(EnumConfigKey.Cipher, "aes,chacha20,3des,WARN,des,blowfish,arcfour");
Set(EnumConfigKey.KEX, "ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1");
Set(EnumConfigKey.RekeyBytes, "1G");
Set(EnumConfigKey.GSSLibs, "gssapi32,sspi,custom");
Set(EnumConfigKey.GSSCustom, "");
Set(EnumConfigKey.LogHost, "");
Set(EnumConfigKey.PublicKeyFile, "");
Set(EnumConfigKey.RemoteCommand, "");
Set(EnumConfigKey.Answerback, "KiTTY");
Set(EnumConfigKey.BellWaveFile, "");
Set(EnumConfigKey.WinTitle, "");
Set(EnumConfigKey.Colour0, "187,187,187");
Set(EnumConfigKey.Colour1, "255,255,255");
Set(EnumConfigKey.Colour2, "0,0,0");
Set(EnumConfigKey.Colour3, "85,85,85");
Set(EnumConfigKey.Colour4, "0,0,0");
Set(EnumConfigKey.Colour5, "0,255,0");
Set(EnumConfigKey.Colour6, "0,0,0");
Set(EnumConfigKey.Colour7, "85,85,85");
Set(EnumConfigKey.Colour8, "187,0,0");
Set(EnumConfigKey.Colour9, "255,85,85");
Set(EnumConfigKey.Colour10, "0,187,0");
Set(EnumConfigKey.Colour11, "85,255,85");
Set(EnumConfigKey.Colour12, "187,187,0");
Set(EnumConfigKey.Colour13, "255,255,85");
Set(EnumConfigKey.Colour14, "0,0,187");
Set(EnumConfigKey.Colour15, "85,85,255");
Set(EnumConfigKey.Colour16, "187,0,187");
Set(EnumConfigKey.Colour17, "255,85,255");
Set(EnumConfigKey.Colour18, "0,187,187");
Set(EnumConfigKey.Colour19, "85,255,255");
Set(EnumConfigKey.Colour20, "187,187,187");
Set(EnumConfigKey.Colour21, "255,255,255");
Set(EnumConfigKey.Wordness0, "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0");
Set(EnumConfigKey.Wordness32, "0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1");
Set(EnumConfigKey.Wordness64, "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2");
Set(EnumConfigKey.Wordness96, "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1");
Set(EnumConfigKey.Wordness128, "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1");
Set(EnumConfigKey.Wordness160, "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1");
Set(EnumConfigKey.Wordness192, "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2");
Set(EnumConfigKey.Wordness224, "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2");
Set(EnumConfigKey.LineCodePage, "");
Set(EnumConfigKey.Printer, "");
Set(EnumConfigKey.X11Display, "");
Set(EnumConfigKey.X11AuthFile, "");
Set(EnumConfigKey.PortForwardings, "");
Set(EnumConfigKey.BoldFont, "");
Set(EnumConfigKey.WideFont, "");
Set(EnumConfigKey.WideBoldFont, "");
Set(EnumConfigKey.SerialLine, "COM1");
Set(EnumConfigKey.WindowClass, "");
Set(EnumConfigKey.Present, 0x00000001);
Set(EnumConfigKey.LogType, 0x00000000);
Set(EnumConfigKey.LogFlush, 0x00000001);
Set(EnumConfigKey.SSHLogOmitPasswords, 0x00000001);
Set(EnumConfigKey.SSHLogOmitData, 0x00000000);
Set(EnumConfigKey.PortNumber, 0x00000016);
Set(EnumConfigKey.CloseOnExit, 0x00000001);
Set(EnumConfigKey.WarnOnClose, 0x00000000);
Set(EnumConfigKey.PingInterval, 0x00000000);
Set(EnumConfigKey.PingIntervalSecs, 0x0000003c);
Set(EnumConfigKey.TCPNoDelay, 0x00000001);
Set(EnumConfigKey.TCPKeepalives, 0x0000001E); // seconds between keepalives
Set(EnumConfigKey.AddressFamily, 0x00000000);
Set(EnumConfigKey.ProxyDNS, 0x00000001);
Set(EnumConfigKey.ProxyLocalhost, 0x00000000);
Set(EnumConfigKey.ProxyMethod, 0x00000000);
Set(EnumConfigKey.ProxyPort, 0x00000050);
Set(EnumConfigKey.UserNameFromEnvironment, 0x00000000);
Set(EnumConfigKey.NoPTY, 0x00000000);
Set(EnumConfigKey.Compression, 0x00000001);
Set(EnumConfigKey.TryAgent, 0x00000001);
Set(EnumConfigKey.AgentFwd, 0x00000000);
Set(EnumConfigKey.GssapiFwd, 0x00000000);
Set(EnumConfigKey.ChangeUsername, 0x00000000);
Set(EnumConfigKey.RekeyTime, 0x0000003c);
Set(EnumConfigKey.SshNoAuth, 0x00000000);
Set(EnumConfigKey.SshBanner, 0x00000001);
Set(EnumConfigKey.AuthTIS, 0x00000000);
Set(EnumConfigKey.AuthKI, 0x00000001);
Set(EnumConfigKey.AuthGSSAPI, 0x00000001);
Set(EnumConfigKey.SshNoShell, 0x00000000);
Set(EnumConfigKey.SshProt, 0x00000002);
Set(EnumConfigKey.SSH2DES, 0x00000000);
Set(EnumConfigKey.RFCEnviron, 0x00000000);
Set(EnumConfigKey.PassiveTelnet, 0x00000000);
Set(EnumConfigKey.BackspaceIsDelete, 0x00000001);
Set(EnumConfigKey.RXVTHomeEnd, 0x00000000);
Set(EnumConfigKey.LinuxFunctionKeys, 0x00000002);
Set(EnumConfigKey.NoApplicationKeys, 0x00000000);
Set(EnumConfigKey.NoApplicationCursors, 0x00000000);
Set(EnumConfigKey.NoMouseReporting, 0x00000000);
Set(EnumConfigKey.NoRemoteResize, 0x00000001);
Set(EnumConfigKey.NoAltScreen, 0x00000000);
Set(EnumConfigKey.NoRemoteWinTitle, 0x00000000);
Set(EnumConfigKey.RemoteQTitleAction, 0x00000001);
Set(EnumConfigKey.NoDBackspace, 0x00000000);
Set(EnumConfigKey.NoRemoteCharset, 0x00000000);
Set(EnumConfigKey.ApplicationCursorKeys, 0x00000000);
Set(EnumConfigKey.ApplicationKeypad, 0x00000000);
Set(EnumConfigKey.NetHackKeypad, 0x00000000);
Set(EnumConfigKey.AltSpace, 0x00000000);
Set(EnumConfigKey.AltOnly, 0x00000000);
Set(EnumConfigKey.ComposeKey, 0x00000000);
Set(EnumConfigKey.CtrlAltKeys, 0x00000001);
Set(EnumConfigKey.TelnetKey, 0x00000000);
Set(EnumConfigKey.TelnetRet, 0x00000001);
Set(EnumConfigKey.LocalEcho, 0x00000002);
Set(EnumConfigKey.LocalEdit, 0x00000002);
Set(EnumConfigKey.AlwaysOnTop, 0x00000000);
Set(EnumConfigKey.FullScreenOnAltEnter, 0x00000000);
Set(EnumConfigKey.HideMousePtr, 0x00000000);
Set(EnumConfigKey.SunkenEdge, 0x00000000);
Set(EnumConfigKey.WindowBorder, 0x00000000);
Set(EnumConfigKey.CurType, 0x00000000);
Set(EnumConfigKey.BlinkCur, 0x00000000);
Set(EnumConfigKey.Beep, 0x00000001);
Set(EnumConfigKey.BeepInd, 0x00000000);
Set(EnumConfigKey.BellOverload, 0x00000001);
Set(EnumConfigKey.BellOverloadN, 0x00000005);
Set(EnumConfigKey.BellOverloadT, 0x000007d0);
Set(EnumConfigKey.BellOverloadS, 0x00001388);
Set(EnumConfigKey.ScrollbackLines, 0x00002000);
Set(EnumConfigKey.DECOriginMode, 0x00000000);
Set(EnumConfigKey.AutoWrapMode, 0x00000001);
Set(EnumConfigKey.LFImpliesCR, 0x00000000);
Set(EnumConfigKey.CRImpliesLF, 0x00000000);
Set(EnumConfigKey.DisableArabicShaping, 0x00000000);
Set(EnumConfigKey.DisableBidi, 0x00000000);
Set(EnumConfigKey.WinNameAlways, 0x00000001);
Set(EnumConfigKey.TermWidth, 0x00000050);
Set(EnumConfigKey.TermHeight, 0x00000018);
Set(EnumConfigKey.FontIsBold, 0x00000000);
Set(EnumConfigKey.FontCharSet, 0x00000000);
Set(EnumConfigKey.Font, "Consolas");
Set(EnumConfigKey.FontHeight, 12);
Set(EnumConfigKey.FontCharSet, 0x00000000);
Set(EnumConfigKey.FontQuality, 0x00000000);
Set(EnumConfigKey.FontVTMode, 0x00000004);
Set(EnumConfigKey.UseSystemColours, 0x00000000);
Set(EnumConfigKey.TryPalette, 0x00000000);
Set(EnumConfigKey.ANSIColour, 0x00000001);
Set(EnumConfigKey.Xterm256Colour, 0x00000001);
Set(EnumConfigKey.BoldAsColour, 0x00000001);
Set(EnumConfigKey.RawCNP, 0x00000000);
Set(EnumConfigKey.PasteRTF, 0x00000000);
Set(EnumConfigKey.MouseIsXterm, 0x00000000);
Set(EnumConfigKey.MouseOverride, 0x00000001);
Set(EnumConfigKey.RectSelect, 0x00000000);
Set(EnumConfigKey.CJKAmbigWide, 0x00000000);
Set(EnumConfigKey.UTF8Override, 0x00000001);
Set(EnumConfigKey.CapsLockCyr, 0x00000000);
Set(EnumConfigKey.ScrollBar, 0x00000001); // ScrollBar在kitty终端中的作用是启用或禁用滚动条
Set(EnumConfigKey.ScrollBarFullScreen, 0x00000001);
Set(EnumConfigKey.ScrollOnKey, 0x00000000);
Set(EnumConfigKey.ScrollOnDisp, 0x00000f001);
Set(EnumConfigKey.ScrollbarOnLeft, 0x00000000);
Set(EnumConfigKey.EraseToScrollback, 0x00000001);
Set(EnumConfigKey.LockSize, 0x00000000);
Set(EnumConfigKey.BCE, 0x00000001);
Set(EnumConfigKey.BlinkText, 0x00000000);
Set(EnumConfigKey.X11Forward, 0x00000000);
Set(EnumConfigKey.X11AuthType, 0x00000001);
Set(EnumConfigKey.LocalPortAcceptAll, 0x00000000);
Set(EnumConfigKey.RemotePortAcceptAll, 0x00000000);
Set(EnumConfigKey.BugIgnore1, 0x00000000);
Set(EnumConfigKey.BugPlainPW1, 0x00000000);
Set(EnumConfigKey.BugRSA1, 0x00000000);
Set(EnumConfigKey.BugIgnore2, 0x00000000);
Set(EnumConfigKey.BugHMAC2, 0x00000000);
Set(EnumConfigKey.BugDeriveKey2, 0x00000000);
Set(EnumConfigKey.BugRSAPad2, 0x00000000);
Set(EnumConfigKey.BugPKSessID2, 0x00000000);
Set(EnumConfigKey.BugRekey2, 0x00000000);
Set(EnumConfigKey.BugMaxPkt2, 0x00000000);
Set(EnumConfigKey.StampUtmp, 0x00000001);
Set(EnumConfigKey.LoginShell, 0x00000001);
Set(EnumConfigKey.ShadowBold, 0x00000000);
Set(EnumConfigKey.ShadowBoldOffset, 0x00000001);
Set(EnumConfigKey.SerialSpeed, 0x00002580);
Set(EnumConfigKey.SerialDataBits, 0x00000008);
Set(EnumConfigKey.SerialStopHalfbits, 0x00000002);
Set(EnumConfigKey.SerialParity, 0x00000000);
Set(EnumConfigKey.SerialFlowControl, 0x00000001);
Set(EnumConfigKey.Autocommand, "");
#endregion Default
}
public void Set(EnumConfigKey key, int value)
{
Set(key, value.ToString());
}
public void Set(EnumConfigKey key, string value)
{
if (Options.Any(x => x.Key == key.ToString()))
{
var item = Options.First(x => x.Key == key.ToString());
item.Value = value;
}
else
{
Options.Add(PuttyConfigKeyValuePair.Create(key.ToString(), value));
}
}
/// <summary>
/// save to reg table
/// </summary>
public void SaveToPuttyRegistryTable()
{
string regPath = $"Software\\SimonTatham\\PuTTY\\Sessions\\{SessionId}";
using var regKey = Registry.CurrentUser.CreateSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree);
if (regKey == null) return;
foreach (var item in Options)
{
if (item.Value != null)
regKey.SetValue(item.Key, item.Value, item.ValueKind);
}
}
/// <summary>
/// del from reg table
/// </summary>
public void DelFromPuttyRegistryTable()
{
string regPath = $"Software\\SimonTatham\\PuTTY\\Sessions\\{SessionId}";
try
{
Registry.CurrentUser.DeleteSubKeyTree(regPath);
}
catch (Exception e)
{
SimpleLogHelper.Error(e);
}
}
/// <summary>
/// save to reg table
/// </summary>
private void SaveToKittyRegistryTable()
{
string regPath = $"Software\\9bis.com\\KiTTY\\Sessions\\{SessionId}";
try
{
using var regKey = Registry.CurrentUser.CreateSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree);
if (regKey == null) return;
foreach (var item in Options.Where(item => !string.IsNullOrWhiteSpace(item.Key) && item.Value != null))
{
try
{
regKey.SetValue(item.Key, item.Value, item.ValueKind);
}
catch (Exception e1)
{
SimpleLogHelper.Warning(e1, $"regKey.SetValue({item.Key}, {item.Value}, {item.ValueKind})");
}
}
}
catch (Exception e)
{
SimpleLogHelper.Warning(e);
}
}
public void SaveToKittyConfig(string kittyExePath)
{
SaveToKittyPortableConfig(kittyExePath, SessionId, Options);
SaveToKittyRegistryTable();
}
public void DelFromKittyConfig(string kittyPath)
{
DelFromKittyPortableConfig(kittyPath, SessionId);
DelFromKittyRegistryTable(SessionId);
}
/// <summary>
/// del from reg table
/// </summary>
private static void DelFromKittyRegistryTable(string sessionId)
{
string regPath = $"Software\\9bis.com\\KiTTY\\Sessions\\{sessionId}";
try
{
Registry.CurrentUser.DeleteSubKeyTree(regPath);
}
catch (Exception)
{
// ignored
}
}
private static void SaveToKittyPortableConfig(string kittyExePath, string sessionId, List<PuttyConfigKeyValuePair> options)
{
try
{
string configPath = Path.Combine(Path.GetDirectoryName(kittyExePath)!, "Sessions", sessionId.Replace(" ", "%20"));
var sb = new StringBuilder();
foreach (var item in options)
{
if (item.Value != null)
sb.AppendLine($@"{item.Key}\{item.Value}\");
}
var fi = new FileInfo(configPath);
if (fi?.Directory?.Exists == false)
fi.Directory.Create();
RetryHelper.Try(() =>
{
File.WriteAllText(configPath, sb.ToString(), Encoding.UTF8);
}, actionOnError: exception => UnifyTracing.Error(exception));
}
catch (Exception e)
{
SimpleLogHelper.Warning(e);
}
}
private static void DelFromKittyPortableConfig(string kittyPath, string sessionId)
{
try
{
string configPath = Path.Combine(kittyPath, "Sessions", sessionId.Replace(" ", "%20"));
if (File.Exists(configPath))
File.Delete(configPath);
}
catch (Exception e)
{
SimpleLogHelper.Warning(e);
}
}
public static void CleanUpOldConfig()
{
if (!Directory.Exists(AppPathHelper.Instance.KittyDirPath))
{
Directory.CreateDirectory(AppPathHelper.Instance.KittyDirPath);
return;
}
string configPath = Path.Combine(AppPathHelper.Instance.KittyDirPath, "Sessions");
var di = new DirectoryInfo(configPath);
if (di.Exists)
{
var fis = di.GetFiles();
foreach (var fi in fis)
{
try
{
var sessionId = fi.Name;
DelFromKittyPortableConfig(AppPathHelper.Instance.KittyDirPath, sessionId);
DelFromKittyRegistryTable(sessionId);
}
catch (Exception e)
{
SimpleLogHelper.Warning(e);
}
}
}
}
[Obsolete]
public static void WriteKittyDefaultConfig(string kittyFullName)
{
var fi = new FileInfo(kittyFullName);
if (fi?.Directory?.Exists == false)
fi.Directory.Create();
RetryHelper.Try(() =>
{
File.WriteAllText(Path.Combine(fi!.Directory!.FullName, "kitty.ini"),
@"
[Agent]
[ConfigBox]
dblclick=open
filter=yes
height=21
[KiTTY]
adb=yes
; antiidle: character string regularly sent to maintain the connection alive
antiidle=
; antiidledelay: time delay between two sending
antiidledelay=60
; autoreconnect: enable/disable the automatic reconnection feature
autoreconnect=yes
backgroundimage=no
capslock=no
conf=yes
ctrltab=no
cygterm=no
hyperlink=yes
icon=no
maxblinkingtime=5
mouseshortcuts=yes
paste=no
ReconnectDelay=5
size=no
transparency=yes
userpasssshnosave=no
winrol=yes
wintitle=yes
zmodem=yes
[Shortcuts]
;input=SHIFT+CONTROL+ALT+F11
;inputm=SHIFT+CONTROL+ALT+F12
;rollup=SHIFT+CONTROL+ALT+F10
[Print]
height=100
maxline=60
maxchar=85
[Launcher]
reload=yes
");
Thread.Sleep(50);
}, actionOnError: exception => UnifyTracing.Error(exception));
}
}
} | 412 | 0.733953 | 1 | 0.733953 | game-dev | MEDIA | 0.297481 | game-dev | 0.752359 | 1 | 0.752359 |
rolandoam/shinycocos | 3,821 | Chipmunk-5.1.0/include/chipmunk/cpVect.h | /* Copyright (c) 2007 Scott Lembcke
*
* 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.
*/
static const cpVect cpvzero={0.0f,0.0f};
static inline cpVect
cpv(const cpFloat x, const cpFloat y)
{
cpVect v = {x, y};
return v;
}
// non-inlined functions
cpFloat cpvlength(const cpVect v);
cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t);
cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a);
cpVect cpvforangle(const cpFloat a); // convert radians to a normalized vector
cpFloat cpvtoangle(const cpVect v); // convert a vector to radians
char *cpvstr(const cpVect v); // get a string representation of a vector
static inline cpVect
cpvadd(const cpVect v1, const cpVect v2)
{
return cpv(v1.x + v2.x, v1.y + v2.y);
}
static inline cpVect
cpvneg(const cpVect v)
{
return cpv(-v.x, -v.y);
}
static inline cpVect
cpvsub(const cpVect v1, const cpVect v2)
{
return cpv(v1.x - v2.x, v1.y - v2.y);
}
static inline cpVect
cpvmult(const cpVect v, const cpFloat s)
{
return cpv(v.x*s, v.y*s);
}
static inline cpFloat
cpvdot(const cpVect v1, const cpVect v2)
{
return v1.x*v2.x + v1.y*v2.y;
}
static inline cpFloat
cpvcross(const cpVect v1, const cpVect v2)
{
return v1.x*v2.y - v1.y*v2.x;
}
static inline cpVect
cpvperp(const cpVect v)
{
return cpv(-v.y, v.x);
}
static inline cpVect
cpvrperp(const cpVect v)
{
return cpv(v.y, -v.x);
}
static inline cpVect
cpvproject(const cpVect v1, const cpVect v2)
{
return cpvmult(v2, cpvdot(v1, v2)/cpvdot(v2, v2));
}
static inline cpVect
cpvrotate(const cpVect v1, const cpVect v2)
{
return cpv(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
}
static inline cpVect
cpvunrotate(const cpVect v1, const cpVect v2)
{
return cpv(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
}
static inline cpFloat
cpvlengthsq(const cpVect v)
{
return cpvdot(v, v);
}
static inline cpVect
cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t)
{
return cpvadd(cpvmult(v1, 1.0f - t), cpvmult(v2, t));
}
static inline cpVect
cpvnormalize(const cpVect v)
{
return cpvmult(v, 1.0f/cpvlength(v));
}
static inline cpVect
cpvnormalize_safe(const cpVect v)
{
return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v));
}
static inline cpVect
cpvclamp(const cpVect v, const cpFloat len)
{
return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v;
}
static inline cpVect
cpvlerpconst(cpVect v1, cpVect v2, cpFloat d)
{
return cpvadd(v1, cpvclamp(cpvsub(v2, v1), d));
}
static inline cpFloat
cpvdist(const cpVect v1, const cpVect v2)
{
return cpvlength(cpvsub(v1, v2));
}
static inline cpFloat
cpvdistsq(const cpVect v1, const cpVect v2)
{
return cpvlengthsq(cpvsub(v1, v2));
}
static inline int
cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist)
{
return cpvdistsq(v1, v2) < dist*dist;
}
| 412 | 0.723678 | 1 | 0.723678 | game-dev | MEDIA | 0.86456 | game-dev | 0.688291 | 1 | 0.688291 |
gmitch215/MobChip | 3,685 | nms/1_18_R1/src/main/java/me/gamercoder215/mobchip/abstraction/v1_18_R1/EntityController1_18_R1.java | package me.gamercoder215.mobchip.abstraction.v1_18_R1;
import me.gamercoder215.mobchip.ai.controller.EntityController;
import me.gamercoder215.mobchip.ai.controller.NaturalMoveType;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.entity.ai.control.JumpControl;
import net.minecraft.world.entity.ai.control.LookControl;
import net.minecraft.world.entity.ai.control.MoveControl;
import net.minecraft.world.phys.Vec3;
import org.bukkit.Location;
import org.bukkit.entity.Mob;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
final class EntityController1_18_R1 implements EntityController {
private final JumpControl jumpC;
private final MoveControl moveC;
private final LookControl lookC;
private final Mob m;
private final net.minecraft.world.entity.Mob nms;
public EntityController1_18_R1(Mob m) {
net.minecraft.world.entity.Mob nms = ChipUtil1_18_R1.toNMS(m);
this.lookC = nms.getLookControl();
this.moveC = nms.getMoveControl();
this.jumpC = nms.getJumpControl();
this.m = m;
this.nms = nms;
}
@Override
public EntityController jump() {
jumpC.jump();
jumpC.tick();
return this;
}
@Override
public boolean isLookingAtTarget() {
Vector dir = m.getLocation().getDirection();
int x = dir.getBlockX();
int y = dir.getBlockY();
int z = dir.getBlockZ();
return lookC.getWantedX() == x && lookC.getWantedY() == y && lookC.getWantedZ() == z;
}
@Override
public EntityController moveTo(double x, double y, double z, double speedMod) {
moveC.setWantedPosition(x, y, z, speedMod);
moveC.tick();
nms.getNavigation().moveTo(moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ(), moveC.getSpeedModifier());
nms.getNavigation().tick();
return this;
}
@Override
public EntityController naturalMoveTo(double x, double y, double z, NaturalMoveType type) {
Vec3 vec = new Vec3(x, y, z);
MoverType m = switch (type) {
default -> MoverType.SELF;
case PLAYER -> MoverType.PLAYER;
case PISTON -> MoverType.PISTON;
case SHULKER_BOX -> MoverType.SHULKER_BOX;
case SHULKER -> MoverType.SHULKER;
};
nms.move(m, vec);
return this;
}
@Override
public EntityController strafe(float fwd, float right) {
moveC.strafe(fwd, right);
moveC.tick();
nms.getNavigation().moveTo(moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ(), moveC.getSpeedModifier());
nms.getNavigation().tick();
return this;
}
@Override
public double getCurrentSpeedModifier() {
return moveC.getSpeedModifier();
}
@Override
public Location getTargetMoveLocation() {
return new Location(m.getWorld(), moveC.getWantedX(), moveC.getWantedY(), moveC.getWantedZ());
}
@Override
public Location getTargetLookLocation() {
return new Location(m.getWorld(), lookC.getWantedX(), lookC.getWantedY(), lookC.getWantedZ());
}
@Override
public EntityController lookAt(double x, double y, double z) {
lookC.setLookAt(x, y, z);
lookC.tick();
return this;
}
@Override
public @NotNull Vector getDeltaMovement() {
Vec3 delta = nms.getDeltaMovement();
return new Vector(delta.x, delta.y, delta.z);
}
@Override
public void setDeltaMovement(@NotNull Vector delta) {
Vec3 vec = new Vec3(delta.getX(), delta.getY(), delta.getZ());
nms.setDeltaMovement(vec);
}
}
| 412 | 0.885838 | 1 | 0.885838 | game-dev | MEDIA | 0.947535 | game-dev | 0.95978 | 1 | 0.95978 |
theraot/Theraot | 26,501 | Framework.Core/System/Threading/Tasks/ParallelLoopState.cs | #if LESSTHAN_NET40 || NETSTANDARD1_0
#pragma warning disable CA1815 // Override equals and operator equals on value types
#pragma warning disable MA0008 // Add StructLayoutAttribute
#pragma warning disable MA0048 // File name must match type name
// BASEDON: https://raw.githubusercontent.com/dotnet/corefx/e0ba7aa8026280ee3571179cc06431baf1dfaaac/src/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/ParallelLoopState.cs
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A non-generic and generic parallel state class, used by the Parallel helper class
// for parallel loop management.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
// Prevents compiler warnings/errors regarding the use of ref params in Interlocked methods
namespace System.Threading.Tasks
{
/// <summary>
/// Provides completion status on the execution of a <see cref="Parallel" /> loop.
/// </summary>
/// <remarks>
/// If <see cref="IsCompleted" /> returns true, then the loop ran to completion, such that all iterations
/// of the loop were executed. If <see cref="IsCompleted" /> returns false and
/// <see cref="LowestBreakIteration" /> returns null, a call to
/// <see cref="ParallelLoopState.Stop" /> was used to end the loop prematurely. If
/// <see cref="IsCompleted" /> returns false and <see cref="LowestBreakIteration" /> returns a non-null integral
/// value, <see cref="ParallelLoopState.Break()" /> was used to end the loop prematurely.
/// </remarks>
public struct ParallelLoopResult
{
/// <summary>
/// Gets whether the loop ran to completion, such that all iterations of the loop were executed
/// and the loop didn't receive a request to end prematurely.
/// </summary>
public bool IsCompleted
{
get;
internal set;
}
/// <summary>
/// Gets the index of the lowest iteration from which
/// <see cref="ParallelLoopState.Break()" />
/// was called.
/// </summary>
/// <remarks>
/// If <see cref="ParallelLoopState.Break()" /> was not employed, this property will
/// return null.
/// </remarks>
public long? LowestBreakIteration
{
get;
internal set;
}
}
/// <summary>
/// Enables iterations of <see cref="Parallel" /> loops to interact with
/// other iterations.
/// </summary>
[DebuggerDisplay("ShouldExitCurrentIteration = {" + nameof(ShouldExitCurrentIteration) + "}")]
public class ParallelLoopState
{
// Derived classes will track a ParallelStateFlags32 or ParallelStateFlags64.
// So this is slightly redundant, but it enables us to implement some
// methods in this base class.
private readonly ParallelLoopStateFlags _flagsBase;
internal ParallelLoopState(ParallelLoopStateFlags flagsBase)
{
_flagsBase = flagsBase;
}
/// <summary>
/// Gets whether any iteration of the loop has thrown an exception that went unhandled by that
/// iteration.
/// </summary>
public bool IsExceptional => (_flagsBase.LoopStateFlags & ParallelLoopStateFlags.ParallelLoopStateExceptional) != 0;
/// <summary>
/// Gets whether any iteration of the loop has called <see cref="Stop()" />.
/// </summary>
public bool IsStopped => (_flagsBase.LoopStateFlags & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0;
/// <summary>
/// Gets the lowest iteration of the loop from which <see cref="Break()" /> was called.
/// </summary>
/// <remarks>
/// If no iteration of the loop called <see cref="Break()" />, this property will return null.
/// </remarks>
public long? LowestBreakIteration => InternalLowestBreakIteration;
/// <summary>
/// Gets whether the current iteration of the loop should exit based
/// on requests made by this or other iterations.
/// </summary>
/// <remarks>
/// When an iteration of a loop calls <see cref="Break()" /> or <see cref="Stop()" />, or
/// when one throws an exception, or when the loop is canceled, the <see cref="Parallel" /> class will proactively
/// attempt to prohibit additional iterations of the loop from starting execution.
/// However, there may be cases where it is unable to prevent additional iterations from starting.
/// It may also be the case that a long-running iteration has already begun execution. In such
/// cases, iterations may explicitly check the <see cref="ShouldExitCurrentIteration" /> property and
/// cease execution if the property returns true.
/// </remarks>
public bool ShouldExitCurrentIteration => InternalShouldExitCurrentIteration;
/// <summary>
/// Internal/virtual support for LowestBreakIteration.
/// </summary>
internal virtual long? InternalLowestBreakIteration
{
get
{
DebugEx.Fail("This method is not supported.");
throw new NotSupportedException("This method is not supported.");
}
}
/// <summary>
/// Internal/virtual support for ShouldExitCurrentIteration.
/// </summary>
internal virtual bool InternalShouldExitCurrentIteration
{
get
{
DebugEx.Fail("This method is not supported.");
throw new NotSupportedException("This method is not supported.");
}
}
/// <summary>
/// Communicates that the <see cref="Parallel" /> loop should cease execution at the system's earliest
/// convenience of iterations beyond the current iteration.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="Stop()" /> method was previously called. <see cref="Break()" /> and <see cref="Stop()" />
/// may not be used in combination by iterations of the same loop.
/// </exception>
/// <remarks>
/// <para>
/// <see cref="Break()" /> may be used to communicate to the loop that no other iterations after the
/// current iteration need be run. For example, if <see cref="Break()" /> is called from the 100th
/// iteration of a for loop iterating in parallel from 0 to 1000, all iterations less than 100 should
/// still be run, but the iterations from 101 through to 1000 are not necessary.
/// </para>
/// <para>
/// For long-running iterations that may already be executing, <see cref="Break()" /> causes
/// <see cref="LowestBreakIteration" />
/// to be set to the current iteration's index if the current index is less than the current value of
/// <see cref="LowestBreakIteration" />.
/// </para>
/// <para>
/// <see cref="Break()" /> is typically employed in search-based algorithms where an ordering is
/// present in the data source.
/// </para>
/// </remarks>
public void Break()
{
InternalBreak();
}
/// <summary>
/// Communicates that the <see cref="Parallel" /> loop should cease execution at the system's earliest
/// convenience.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="Break()" /> method was previously called. <see cref="Break()" /> and
/// <see cref="Stop()" /> may not be used in combination by iterations of the same loop.
/// </exception>
/// <remarks>
/// <para>
/// <see cref="Stop()" /> may be used to communicate to the loop that no other iterations need be run.
/// For long-running iterations that may already be executing, <see cref="Stop()" /> causes
/// <see cref="IsStopped" />
/// to return true for all other iterations of the loop, such that another iteration may check
/// <see cref="IsStopped" /> and exit early if it's observed to be true.
/// </para>
/// <para>
/// <see cref="Stop()" /> is typically employed in search-based algorithms, where once a result is found,
/// no other iterations need be executed.
/// </para>
/// </remarks>
public void Stop()
{
_flagsBase.Stop();
}
// Helper method to avoid repeating Break() logic between ParallelState32 and ParallelState32<TLocal>
internal static void Break(int iteration, ParallelLoopStateFlags32 parallelFlags)
{
// Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
if
(
!parallelFlags.AtomicLoopStateUpdate
(
ParallelLoopStateFlags.ParallelLoopStateBroken,
ParallelLoopStateFlags.ParallelLoopStateStopped | ParallelLoopStateFlags.ParallelLoopStateExceptional | ParallelLoopStateFlags.ParallelLoopStateCanceled,
out var oldValue
)
)
{
// If we were already stopped, we have a problem
if ((oldValue & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0)
{
throw new InvalidOperationException
(
"SR.ParallelState_Break_InvalidOperationException_BreakAfterStop"
);
}
// Apparently we previously got cancelled or became exceptional. No action necessary
return;
}
// replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
// is less than LowestBreakIteration.
var lowestBreakIteration = parallelFlags.LowestBreakIterationInternal;
if (iteration >= lowestBreakIteration)
{
return;
}
var wait = new SpinWait();
while (Interlocked.CompareExchange(ref parallelFlags.LowestBreakIterationInternal, iteration, lowestBreakIteration) != lowestBreakIteration)
{
wait.SpinOnce();
lowestBreakIteration = parallelFlags.LowestBreakIterationInternal;
if (iteration > lowestBreakIteration)
{
break;
}
}
}
// Helper method to avoid repeating Break() logic between ParallelState64 and ParallelState64<TLocal>
internal static void Break(long iteration, ParallelLoopStateFlags64 parallelFlags)
{
// Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
if
(
!parallelFlags.AtomicLoopStateUpdate
(
ParallelLoopStateFlags.ParallelLoopStateBroken,
ParallelLoopStateFlags.ParallelLoopStateStopped | ParallelLoopStateFlags.ParallelLoopStateExceptional | ParallelLoopStateFlags.ParallelLoopStateCanceled,
out var oldValue
)
)
{
// If we were already stopped, we have a problem
if ((oldValue & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0)
{
throw new InvalidOperationException
(
"SR.ParallelState_Break_InvalidOperationException_BreakAfterStop"
);
}
// Apparently we previously got cancelled or became exceptional. No action necessary
return;
}
// replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
// is less than LowestBreakIteration.
var lowestBreakIteration = parallelFlags.LowestBreakIteration;
if (iteration >= lowestBreakIteration)
{
return;
}
var wait = new SpinWait();
while (Interlocked.CompareExchange(ref parallelFlags.LowestBreakIterationInternal, iteration, lowestBreakIteration) != lowestBreakIteration)
{
wait.SpinOnce();
lowestBreakIteration = parallelFlags.LowestBreakIteration;
if (iteration > lowestBreakIteration)
{
break;
}
}
}
// Internal/virtual support for Break().
internal virtual void InternalBreak()
{
DebugEx.Fail("This method is not supported.");
throw new NotSupportedException("This method is not supported.");
}
}
internal class ParallelLoopState32 : ParallelLoopState
{
private readonly ParallelLoopStateFlags32 _sharedParallelStateFlags;
/// <summary>
/// Internal constructor to ensure an instance isn't created by users.
/// </summary>
/// <param name="sharedParallelStateFlags">
/// A flag shared among all threads participating
/// in the execution of a certain loop.
/// </param>
internal ParallelLoopState32(ParallelLoopStateFlags32 sharedParallelStateFlags)
: base(sharedParallelStateFlags)
{
_sharedParallelStateFlags = sharedParallelStateFlags;
}
/// <summary>
/// Tracks the current loop iteration for the owning task.
/// This is used to compute whether or not the task should
/// terminate early due to a Break() call.
/// </summary>
internal int CurrentIteration { get; set; }
/// <summary>
/// Returns the lowest iteration at which Break() has been called, or
/// null if Break() has not yet been called.
/// </summary>
internal override long? InternalLowestBreakIteration => _sharedParallelStateFlags.NullableLowestBreakIteration;
/// <summary>
/// Returns true if we should be exiting from the current iteration
/// due to Stop(), Break() or exception.
/// </summary>
internal override bool InternalShouldExitCurrentIteration => _sharedParallelStateFlags.ShouldExitLoop(CurrentIteration);
/// <summary>
/// Communicates that parallel tasks should stop when they reach a specified iteration element.
/// (which is CurrentIteration of the caller).
/// </summary>
/// <exception cref="InvalidOperationException">Break() called after Stop().</exception>
/// <remarks>
/// This is shared with all other concurrent threads in the system which are participating in the
/// loop's execution. After calling Break(), no additional iterations will be executed on
/// the current thread, and other worker threads will execute once they get beyond the calling iteration.
/// </remarks>
internal override void InternalBreak()
{
Break(CurrentIteration, _sharedParallelStateFlags);
}
}
/// <summary>
/// Allows independent iterations of a parallel loop to interact with other iterations.
/// </summary>
internal class ParallelLoopState64 : ParallelLoopState
{
private readonly ParallelLoopStateFlags64 _sharedParallelStateFlags;
/// <summary>
/// Internal constructor to ensure an instance isn't created by users.
/// </summary>
/// <param name="sharedParallelStateFlags">
/// A flag shared among all threads participating
/// in the execution of a certain loop.
/// </param>
internal ParallelLoopState64(ParallelLoopStateFlags64 sharedParallelStateFlags)
: base(sharedParallelStateFlags)
{
_sharedParallelStateFlags = sharedParallelStateFlags;
}
/// <summary>
/// Tracks the current loop iteration for the owning task.
/// This is used to compute whether or not the task should
/// terminate early due to a Break() call.
/// </summary>
internal long CurrentIteration { get; set; }
/// <summary>
/// Returns the lowest iteration at which Break() has been called, or
/// null if Break() has not yet been called.
/// </summary>
internal override long? InternalLowestBreakIteration => _sharedParallelStateFlags.NullableLowestBreakIteration;
/// <summary>
/// Returns true if we should be exiting from the current iteration
/// due to Stop(), Break() or exception.
/// </summary>
internal override bool InternalShouldExitCurrentIteration => _sharedParallelStateFlags.ShouldExitLoop(CurrentIteration);
/// <summary>
/// Communicates that parallel tasks should stop when they reach a specified iteration element.
/// (which is CurrentIteration of the caller).
/// </summary>
/// <exception cref="InvalidOperationException">Break() called after Stop().</exception>
/// <remarks>
/// Atomically sets shared StoppedBroken flag to BROKEN, then atomically sets shared
/// LowestBreakIteration to CurrentIteration, but only if CurrentIteration is less than
/// LowestBreakIteration.
/// </remarks>
internal override void InternalBreak()
{
Break(CurrentIteration, _sharedParallelStateFlags);
}
}
/// <summary>
/// State information that is common between ParallelStateFlags class
/// and ParallelStateFlags64 class.
/// </summary>
internal class ParallelLoopStateFlags
{
internal const int ParallelLoopStateBroken = 2;
internal const int ParallelLoopStateCanceled = 8;
internal const int ParallelLoopStateExceptional = 1;
internal const int ParallelLoopStateNone = 0;
internal const int ParallelLoopStateStopped = 4;
private volatile int _loopStateFlags;
internal int LoopStateFlags => _loopStateFlags;
internal bool AtomicLoopStateUpdate(int newState, int illegalStates)
{
return AtomicLoopStateUpdate(newState, illegalStates, out _);
}
internal bool AtomicLoopStateUpdate(int newState, int illegalStates, out int oldState)
{
var sw = new SpinWait();
while (true)
{
oldState = _loopStateFlags;
if ((oldState & illegalStates) != 0)
{
return false;
}
if (Interlocked.CompareExchange(ref _loopStateFlags, oldState | newState, oldState) == oldState)
{
return true;
}
sw.SpinOnce();
}
}
internal void Cancel()
{
// we can set the canceled flag regardless of the state of other bits.
AtomicLoopStateUpdate(ParallelLoopStateCanceled, ParallelLoopStateNone);
}
internal void SetExceptional()
{
// we can set the exceptional flag regardless of the state of other bits.
AtomicLoopStateUpdate(ParallelLoopStateExceptional, ParallelLoopStateNone);
}
internal void Stop()
{
// disallow setting of ParallelLoopStateStopped bit only if ParallelLoopStateBroken was already set
if (!AtomicLoopStateUpdate(ParallelLoopStateStopped, ParallelLoopStateBroken))
{
throw new InvalidOperationException("SR.ParallelState_Stop_InvalidOperationException_StopAfterBreak");
}
}
}
/// <summary>
/// An internal class used to share accounting information in 32-bit versions
/// of For()/ForEach() loops.
/// </summary>
internal class ParallelLoopStateFlags32 : ParallelLoopStateFlags
{
// Records the lowest iteration at which a Break() has been called,
// or Int32.MaxValue if no break has been called. Used directly
// by Break().
internal volatile int LowestBreakIterationInternal = int.MaxValue;
// Not strictly necessary, but maintains consistency with ParallelStateFlags64
internal int LowestBreakIteration => LowestBreakIterationInternal;
// Does some processing to convert _lowestBreakIteration to a long?.
internal long? NullableLowestBreakIteration
{
get
{
if (LowestBreakIterationInternal == int.MaxValue)
{
return null;
}
// protect against torn read of 64-bit value
long result = LowestBreakIterationInternal;
return IntPtr.Size >= 8 ? result : Interlocked.Read(ref result);
}
}
/// <summary>
/// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
/// If this returns true, then exit the loop. Otherwise, keep going.
/// </summary>
/// <param name="callerIteration">
/// The caller's current iteration point
/// in the loop.
/// </param>
/// <remarks>
/// The loop should exit on any one of the following conditions:
/// (1) Stop() has been called by one or more tasks.
/// (2) An exception has been raised by one or more tasks.
/// (3) Break() has been called by one or more tasks, and
/// CallerIteration exceeds the (lowest) iteration at which
/// Break() was called.
/// (4) The loop was canceled.
/// </remarks>
internal bool ShouldExitLoop(int callerIteration)
{
var flags = LoopStateFlags;
return flags != ParallelLoopStateNone
&&
(
(flags & (ParallelLoopStateExceptional | ParallelLoopStateStopped | ParallelLoopStateCanceled)) != 0
|| ((flags & ParallelLoopStateBroken) != 0 && callerIteration > LowestBreakIteration)
);
}
// This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
// Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
internal bool ShouldExitLoop()
{
var flags = LoopStateFlags;
return flags != ParallelLoopStateNone && (flags & (ParallelLoopStateExceptional | ParallelLoopStateCanceled)) != 0;
}
}
/// <summary>
/// An internal class used to share accounting information in 64-bit versions
/// of For()/ForEach() loops.
/// </summary>
internal class ParallelLoopStateFlags64 : ParallelLoopStateFlags
{
// Records the lowest iteration at which a Break() has been called,
// or Int64.MaxValue if no break has been called. Used directly
// by Break().
internal long LowestBreakIterationInternal = long.MaxValue;
// Performs a conditionally interlocked read of _lowestBreakIteration.
internal long LowestBreakIteration => IntPtr.Size >= 8 ? LowestBreakIterationInternal : Interlocked.Read(ref LowestBreakIterationInternal);
// Does some processing to convert _lowestBreakIteration to a long?.
internal long? NullableLowestBreakIteration
{
get
{
if (LowestBreakIterationInternal == long.MaxValue)
{
return null;
}
return IntPtr.Size >= 8 ? LowestBreakIterationInternal : Interlocked.Read(ref LowestBreakIterationInternal);
}
}
/// <summary>
/// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
/// If this returns true, then exit the loop. Otherwise, keep going.
/// </summary>
/// <param name="callerIteration">
/// The caller's current iteration point
/// in the loop.
/// </param>
/// <remarks>
/// The loop should exit on any one of the following conditions:
/// (1) Stop() has been called by one or more tasks.
/// (2) An exception has been raised by one or more tasks.
/// (3) Break() has been called by one or more tasks, and
/// CallerIteration exceeds the (lowest) iteration at which
/// Break() was called.
/// (4) The loop has been canceled.
/// </remarks>
internal bool ShouldExitLoop(long callerIteration)
{
var flags = LoopStateFlags;
return flags != ParallelLoopStateNone
&&
(
(flags & (ParallelLoopStateExceptional | ParallelLoopStateStopped | ParallelLoopStateCanceled)) != 0
|| ((flags & ParallelLoopStateBroken) != 0 && callerIteration > LowestBreakIteration)
);
}
// This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
// Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
internal bool ShouldExitLoop()
{
var flags = LoopStateFlags;
return flags != ParallelLoopStateNone && (flags & (ParallelLoopStateExceptional | ParallelLoopStateCanceled)) != 0;
}
}
}
#endif | 412 | 0.710153 | 1 | 0.710153 | game-dev | MEDIA | 0.522078 | game-dev | 0.798559 | 1 | 0.798559 |
codefollower/Open-Source-Research | 31,261 | HotSpot1.7/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp | /*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "gc_implementation/parallelScavenge/cardTableExtension.hpp"
#include "gc_implementation/parallelScavenge/gcTaskManager.hpp"
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
#include "gc_implementation/parallelScavenge/psTasks.hpp"
#include "gc_implementation/parallelScavenge/psYoungGen.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oop.psgc.inline.hpp"
// Checks an individual oop for missing precise marks. Mark
// may be either dirty or newgen.
class CheckForUnmarkedOops : public OopClosure {
private:
PSYoungGen* _young_gen;
CardTableExtension* _card_table;
HeapWord* _unmarked_addr;
jbyte* _unmarked_card;
protected:
template <class T> void do_oop_work(T* p) {
oop obj = oopDesc::load_decode_heap_oop(p);
if (_young_gen->is_in_reserved(obj) &&
!_card_table->addr_is_marked_imprecise(p)) {
// Don't overwrite the first missing card mark
if (_unmarked_addr == NULL) {
_unmarked_addr = (HeapWord*)p;
_unmarked_card = _card_table->byte_for(p);
}
}
}
public:
CheckForUnmarkedOops(PSYoungGen* young_gen, CardTableExtension* card_table) :
_young_gen(young_gen), _card_table(card_table), _unmarked_addr(NULL) { }
virtual void do_oop(oop* p) { CheckForUnmarkedOops::do_oop_work(p); }
virtual void do_oop(narrowOop* p) { CheckForUnmarkedOops::do_oop_work(p); }
bool has_unmarked_oop() {
return _unmarked_addr != NULL;
}
};
// Checks all objects for the existance of some type of mark,
// precise or imprecise, dirty or newgen.
class CheckForUnmarkedObjects : public ObjectClosure {
private:
PSYoungGen* _young_gen;
CardTableExtension* _card_table;
public:
CheckForUnmarkedObjects() {
ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
_young_gen = heap->young_gen();
_card_table = (CardTableExtension*)heap->barrier_set();
// No point in asserting barrier set type here. Need to make CardTableExtension
// a unique barrier set type.
}
// Card marks are not precise. The current system can leave us with
// a mismash of precise marks and beginning of object marks. This means
// we test for missing precise marks first. If any are found, we don't
// fail unless the object head is also unmarked.
virtual void do_object(oop obj) {
CheckForUnmarkedOops object_check(_young_gen, _card_table);
obj->oop_iterate(&object_check);
if (object_check.has_unmarked_oop()) {
assert(_card_table->addr_is_marked_imprecise(obj), "Found unmarked young_gen object");
}
}
};
// Checks for precise marking of oops as newgen.
class CheckForPreciseMarks : public OopClosure {
private:
PSYoungGen* _young_gen;
CardTableExtension* _card_table;
protected:
template <class T> void do_oop_work(T* p) {
oop obj = oopDesc::load_decode_heap_oop_not_null(p);
if (_young_gen->is_in_reserved(obj)) {
assert(_card_table->addr_is_marked_precise(p), "Found unmarked precise oop");
_card_table->set_card_newgen(p);
}
}
public:
CheckForPreciseMarks( PSYoungGen* young_gen, CardTableExtension* card_table ) :
_young_gen(young_gen), _card_table(card_table) { }
virtual void do_oop(oop* p) { CheckForPreciseMarks::do_oop_work(p); }
virtual void do_oop(narrowOop* p) { CheckForPreciseMarks::do_oop_work(p); }
};
// We get passed the space_top value to prevent us from traversing into
// the old_gen promotion labs, which cannot be safely parsed.
void CardTableExtension::scavenge_contents(ObjectStartArray* start_array,
MutableSpace* sp,
HeapWord* space_top,
PSPromotionManager* pm)
{
assert(start_array != NULL && sp != NULL && pm != NULL, "Sanity");
assert(start_array->covered_region().contains(sp->used_region()),
"ObjectStartArray does not cover space");
if (sp->not_empty()) {
oop* sp_top = (oop*)space_top;
oop* prev_top = NULL;
jbyte* current_card = byte_for(sp->bottom());
jbyte* end_card = byte_for(sp_top - 1); // sp_top is exclusive
// scan card marking array
while (current_card <= end_card) {
jbyte value = *current_card;
// skip clean cards
if (card_is_clean(value)) {
current_card++;
} else {
// we found a non-clean card
jbyte* first_nonclean_card = current_card++;
oop* bottom = (oop*)addr_for(first_nonclean_card);
// find object starting on card
oop* bottom_obj = (oop*)start_array->object_start((HeapWord*)bottom);
// bottom_obj = (oop*)start_array->object_start((HeapWord*)bottom);
assert(bottom_obj <= bottom, "just checking");
// make sure we don't scan oops we already looked at
if (bottom < prev_top) bottom = prev_top;
// figure out when to stop scanning
jbyte* first_clean_card;
oop* top;
bool restart_scanning;
do {
restart_scanning = false;
// find a clean card
while (current_card <= end_card) {
value = *current_card;
if (card_is_clean(value)) break;
current_card++;
}
// check if we reached the end, if so we are done
if (current_card >= end_card) {
first_clean_card = end_card + 1;
current_card++;
top = sp_top;
} else {
// we have a clean card, find object starting on that card
first_clean_card = current_card++;
top = (oop*)addr_for(first_clean_card);
oop* top_obj = (oop*)start_array->object_start((HeapWord*)top);
// top_obj = (oop*)start_array->object_start((HeapWord*)top);
assert(top_obj <= top, "just checking");
if (oop(top_obj)->is_objArray() || oop(top_obj)->is_typeArray()) {
// an arrayOop is starting on the clean card - since we do exact store
// checks for objArrays we are done
} else {
// otherwise, it is possible that the object starting on the clean card
// spans the entire card, and that the store happened on a later card.
// figure out where the object ends
top = top_obj + oop(top_obj)->size();
jbyte* top_card = CardTableModRefBS::byte_for(top - 1); // top is exclusive
if (top_card > first_clean_card) {
// object ends a different card
current_card = top_card + 1;
if (card_is_clean(*top_card)) {
// the ending card is clean, we are done
first_clean_card = top_card;
} else {
// the ending card is not clean, continue scanning at start of do-while
restart_scanning = true;
}
} else {
// object ends on the clean card, we are done.
assert(first_clean_card == top_card, "just checking");
}
}
}
} while (restart_scanning);
// we know which cards to scan, now clear them
while (first_nonclean_card < first_clean_card) {
*first_nonclean_card++ = clean_card;
}
// scan oops in objects
do {
oop(bottom_obj)->push_contents(pm);
bottom_obj += oop(bottom_obj)->size();
assert(bottom_obj <= sp_top, "just checking");
} while (bottom_obj < top);
pm->drain_stacks_cond_depth();
// remember top oop* scanned
prev_top = top;
}
}
}
}
void CardTableExtension::scavenge_contents_parallel(ObjectStartArray* start_array,
MutableSpace* sp,
HeapWord* space_top,
PSPromotionManager* pm,
uint stripe_number,
uint stripe_total) {
int ssize = 128; // Naked constant! Work unit = 64k.
int dirty_card_count = 0;
oop* sp_top = (oop*)space_top;
jbyte* start_card = byte_for(sp->bottom());
jbyte* end_card = byte_for(sp_top - 1) + 1;
oop* last_scanned = NULL; // Prevent scanning objects more than once
// The width of the stripe ssize*stripe_total must be
// consistent with the number of stripes so that the complete slice
// is covered.
size_t slice_width = ssize * stripe_total;
for (jbyte* slice = start_card; slice < end_card; slice += slice_width) {
jbyte* worker_start_card = slice + stripe_number * ssize;
if (worker_start_card >= end_card)
return; // We're done.
jbyte* worker_end_card = worker_start_card + ssize;
if (worker_end_card > end_card)
worker_end_card = end_card;
// We do not want to scan objects more than once. In order to accomplish
// this, we assert that any object with an object head inside our 'slice'
// belongs to us. We may need to extend the range of scanned cards if the
// last object continues into the next 'slice'.
//
// Note! ending cards are exclusive!
HeapWord* slice_start = addr_for(worker_start_card);
HeapWord* slice_end = MIN2((HeapWord*) sp_top, addr_for(worker_end_card));
// If there are not objects starting within the chunk, skip it.
if (!start_array->object_starts_in_range(slice_start, slice_end)) {
continue;
}
// Update our beginning addr
HeapWord* first_object = start_array->object_start(slice_start);
debug_only(oop* first_object_within_slice = (oop*) first_object;)
if (first_object < slice_start) {
last_scanned = (oop*)(first_object + oop(first_object)->size());
debug_only(first_object_within_slice = last_scanned;)
worker_start_card = byte_for(last_scanned);
}
// Update the ending addr
if (slice_end < (HeapWord*)sp_top) {
// The subtraction is important! An object may start precisely at slice_end.
HeapWord* last_object = start_array->object_start(slice_end - 1);
slice_end = last_object + oop(last_object)->size();
// worker_end_card is exclusive, so bump it one past the end of last_object's
// covered span.
worker_end_card = byte_for(slice_end) + 1;
if (worker_end_card > end_card)
worker_end_card = end_card;
}
assert(slice_end <= (HeapWord*)sp_top, "Last object in slice crosses space boundary");
assert(is_valid_card_address(worker_start_card), "Invalid worker start card");
assert(is_valid_card_address(worker_end_card), "Invalid worker end card");
// Note that worker_start_card >= worker_end_card is legal, and happens when
// an object spans an entire slice.
assert(worker_start_card <= end_card, "worker start card beyond end card");
assert(worker_end_card <= end_card, "worker end card beyond end card");
jbyte* current_card = worker_start_card;
while (current_card < worker_end_card) {
// Find an unclean card.
while (current_card < worker_end_card && card_is_clean(*current_card)) {
current_card++;
}
jbyte* first_unclean_card = current_card;
// Find the end of a run of contiguous unclean cards
while (current_card < worker_end_card && !card_is_clean(*current_card)) {
while (current_card < worker_end_card && !card_is_clean(*current_card)) {
current_card++;
}
if (current_card < worker_end_card) {
// Some objects may be large enough to span several cards. If such
// an object has more than one dirty card, separated by a clean card,
// we will attempt to scan it twice. The test against "last_scanned"
// prevents the redundant object scan, but it does not prevent newly
// marked cards from being cleaned.
HeapWord* last_object_in_dirty_region = start_array->object_start(addr_for(current_card)-1);
size_t size_of_last_object = oop(last_object_in_dirty_region)->size();
HeapWord* end_of_last_object = last_object_in_dirty_region + size_of_last_object;
jbyte* ending_card_of_last_object = byte_for(end_of_last_object);
assert(ending_card_of_last_object <= worker_end_card, "ending_card_of_last_object is greater than worker_end_card");
if (ending_card_of_last_object > current_card) {
// This means the object spans the next complete card.
// We need to bump the current_card to ending_card_of_last_object
current_card = ending_card_of_last_object;
}
}
}
jbyte* following_clean_card = current_card;
if (first_unclean_card < worker_end_card) {
oop* p = (oop*) start_array->object_start(addr_for(first_unclean_card));
assert((HeapWord*)p <= addr_for(first_unclean_card), "checking");
// "p" should always be >= "last_scanned" because newly GC dirtied
// cards are no longer scanned again (see comment at end
// of loop on the increment of "current_card"). Test that
// hypothesis before removing this code.
// If this code is removed, deal with the first time through
// the loop when the last_scanned is the object starting in
// the previous slice.
assert((p >= last_scanned) ||
(last_scanned == first_object_within_slice),
"Should no longer be possible");
if (p < last_scanned) {
// Avoid scanning more than once; this can happen because
// newgen cards set by GC may a different set than the
// originally dirty set
p = last_scanned;
}
oop* to = (oop*)addr_for(following_clean_card);
// Test slice_end first!
if ((HeapWord*)to > slice_end) {
to = (oop*)slice_end;
} else if (to > sp_top) {
to = sp_top;
}
// we know which cards to scan, now clear them
if (first_unclean_card <= worker_start_card+1)
first_unclean_card = worker_start_card+1;
if (following_clean_card >= worker_end_card-1)
following_clean_card = worker_end_card-1;
while (first_unclean_card < following_clean_card) {
*first_unclean_card++ = clean_card;
}
const int interval = PrefetchScanIntervalInBytes;
// scan all objects in the range
if (interval != 0) {
while (p < to) {
Prefetch::write(p, interval);
oop m = oop(p);
assert(m->is_oop_or_null(), "check for header");
m->push_contents(pm);
p += m->size();
}
pm->drain_stacks_cond_depth();
} else {
while (p < to) {
oop m = oop(p);
assert(m->is_oop_or_null(), "check for header");
m->push_contents(pm);
p += m->size();
}
pm->drain_stacks_cond_depth();
}
last_scanned = p;
}
// "current_card" is still the "following_clean_card" or
// the current_card is >= the worker_end_card so the
// loop will not execute again.
assert((current_card == following_clean_card) ||
(current_card >= worker_end_card),
"current_card should only be incremented if it still equals "
"following_clean_card");
// Increment current_card so that it is not processed again.
// It may now be dirty because a old-to-young pointer was
// found on it an updated. If it is now dirty, it cannot be
// be safely cleaned in the next iteration.
current_card++;
}
}
}
// This should be called before a scavenge.
void CardTableExtension::verify_all_young_refs_imprecise() {
CheckForUnmarkedObjects check;
ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
PSOldGen* old_gen = heap->old_gen();
PSPermGen* perm_gen = heap->perm_gen();
old_gen->object_iterate(&check);
perm_gen->object_iterate(&check);
}
// This should be called immediately after a scavenge, before mutators resume.
void CardTableExtension::verify_all_young_refs_precise() {
ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
PSOldGen* old_gen = heap->old_gen();
PSPermGen* perm_gen = heap->perm_gen();
CheckForPreciseMarks check(heap->young_gen(), (CardTableExtension*)heap->barrier_set());
old_gen->oop_iterate(&check);
perm_gen->oop_iterate(&check);
verify_all_young_refs_precise_helper(old_gen->object_space()->used_region());
verify_all_young_refs_precise_helper(perm_gen->object_space()->used_region());
}
void CardTableExtension::verify_all_young_refs_precise_helper(MemRegion mr) {
CardTableExtension* card_table = (CardTableExtension*)Universe::heap()->barrier_set();
// FIX ME ASSERT HERE
jbyte* bot = card_table->byte_for(mr.start());
jbyte* top = card_table->byte_for(mr.end());
while(bot <= top) {
assert(*bot == clean_card || *bot == verify_card, "Found unwanted or unknown card mark");
if (*bot == verify_card)
*bot = youngergen_card;
bot++;
}
}
bool CardTableExtension::addr_is_marked_imprecise(void *addr) {
jbyte* p = byte_for(addr);
jbyte val = *p;
if (card_is_dirty(val))
return true;
if (card_is_newgen(val))
return true;
if (card_is_clean(val))
return false;
assert(false, "Found unhandled card mark type");
return false;
}
// Also includes verify_card
bool CardTableExtension::addr_is_marked_precise(void *addr) {
jbyte* p = byte_for(addr);
jbyte val = *p;
if (card_is_newgen(val))
return true;
if (card_is_verify(val))
return true;
if (card_is_clean(val))
return false;
if (card_is_dirty(val))
return false;
assert(false, "Found unhandled card mark type");
return false;
}
// Assumes that only the base or the end changes. This allows indentification
// of the region that is being resized. The
// CardTableModRefBS::resize_covered_region() is used for the normal case
// where the covered regions are growing or shrinking at the high end.
// The method resize_covered_region_by_end() is analogous to
// CardTableModRefBS::resize_covered_region() but
// for regions that grow or shrink at the low end.
void CardTableExtension::resize_covered_region(MemRegion new_region) {
for (int i = 0; i < _cur_covered_regions; i++) {
if (_covered[i].start() == new_region.start()) {
// Found a covered region with the same start as the
// new region. The region is growing or shrinking
// from the start of the region.
resize_covered_region_by_start(new_region);
return;
}
if (_covered[i].start() > new_region.start()) {
break;
}
}
int changed_region = -1;
for (int j = 0; j < _cur_covered_regions; j++) {
if (_covered[j].end() == new_region.end()) {
changed_region = j;
// This is a case where the covered region is growing or shrinking
// at the start of the region.
assert(changed_region != -1, "Don't expect to add a covered region");
assert(_covered[changed_region].byte_size() != new_region.byte_size(),
"The sizes should be different here");
resize_covered_region_by_end(changed_region, new_region);
return;
}
}
// This should only be a new covered region (where no existing
// covered region matches at the start or the end).
assert(_cur_covered_regions < _max_covered_regions,
"An existing region should have been found");
resize_covered_region_by_start(new_region);
}
void CardTableExtension::resize_covered_region_by_start(MemRegion new_region) {
CardTableModRefBS::resize_covered_region(new_region);
debug_only(verify_guard();)
}
void CardTableExtension::resize_covered_region_by_end(int changed_region,
MemRegion new_region) {
assert(SafepointSynchronize::is_at_safepoint(),
"Only expect an expansion at the low end at a GC");
debug_only(verify_guard();)
#ifdef ASSERT
for (int k = 0; k < _cur_covered_regions; k++) {
if (_covered[k].end() == new_region.end()) {
assert(changed_region == k, "Changed region is incorrect");
break;
}
}
#endif
// Commit new or uncommit old pages, if necessary.
if (resize_commit_uncommit(changed_region, new_region)) {
// Set the new start of the committed region
resize_update_committed_table(changed_region, new_region);
}
// Update card table entries
resize_update_card_table_entries(changed_region, new_region);
// Update the covered region
resize_update_covered_table(changed_region, new_region);
if (TraceCardTableModRefBS) {
int ind = changed_region;
gclog_or_tty->print_cr("CardTableModRefBS::resize_covered_region: ");
gclog_or_tty->print_cr(" "
" _covered[%d].start(): " INTPTR_FORMAT
" _covered[%d].last(): " INTPTR_FORMAT,
ind, _covered[ind].start(),
ind, _covered[ind].last());
gclog_or_tty->print_cr(" "
" _committed[%d].start(): " INTPTR_FORMAT
" _committed[%d].last(): " INTPTR_FORMAT,
ind, _committed[ind].start(),
ind, _committed[ind].last());
gclog_or_tty->print_cr(" "
" byte_for(start): " INTPTR_FORMAT
" byte_for(last): " INTPTR_FORMAT,
byte_for(_covered[ind].start()),
byte_for(_covered[ind].last()));
gclog_or_tty->print_cr(" "
" addr_for(start): " INTPTR_FORMAT
" addr_for(last): " INTPTR_FORMAT,
addr_for((jbyte*) _committed[ind].start()),
addr_for((jbyte*) _committed[ind].last()));
}
debug_only(verify_guard();)
}
bool CardTableExtension::resize_commit_uncommit(int changed_region,
MemRegion new_region) {
bool result = false;
// Commit new or uncommit old pages, if necessary.
MemRegion cur_committed = _committed[changed_region];
assert(_covered[changed_region].end() == new_region.end(),
"The ends of the regions are expected to match");
// Extend the start of this _committed region to
// to cover the start of any previous _committed region.
// This forms overlapping regions, but never interior regions.
HeapWord* min_prev_start = lowest_prev_committed_start(changed_region);
if (min_prev_start < cur_committed.start()) {
// Only really need to set start of "cur_committed" to
// the new start (min_prev_start) but assertion checking code
// below use cur_committed.end() so make it correct.
MemRegion new_committed =
MemRegion(min_prev_start, cur_committed.end());
cur_committed = new_committed;
}
#ifdef ASSERT
ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
assert(cur_committed.start() ==
(HeapWord*) align_size_up((uintptr_t) cur_committed.start(),
os::vm_page_size()),
"Starts should have proper alignment");
#endif
jbyte* new_start = byte_for(new_region.start());
// Round down because this is for the start address
HeapWord* new_start_aligned =
(HeapWord*)align_size_down((uintptr_t)new_start, os::vm_page_size());
// The guard page is always committed and should not be committed over.
// This method is used in cases where the generation is growing toward
// lower addresses but the guard region is still at the end of the
// card table. That still makes sense when looking for writes
// off the end of the card table.
if (new_start_aligned < cur_committed.start()) {
// Expand the committed region
//
// Case A
// |+ guard +|
// |+ cur committed +++++++++|
// |+ new committed +++++++++++++++++|
//
// Case B
// |+ guard +|
// |+ cur committed +|
// |+ new committed +++++++|
//
// These are not expected because the calculation of the
// cur committed region and the new committed region
// share the same end for the covered region.
// Case C
// |+ guard +|
// |+ cur committed +|
// |+ new committed +++++++++++++++++|
// Case D
// |+ guard +|
// |+ cur committed +++++++++++|
// |+ new committed +++++++|
HeapWord* new_end_for_commit =
MIN2(cur_committed.end(), _guard_region.start());
if(new_start_aligned < new_end_for_commit) {
MemRegion new_committed =
MemRegion(new_start_aligned, new_end_for_commit);
os::commit_memory_or_exit((char*)new_committed.start(),
new_committed.byte_size(), !ExecMem,
"card table expansion");
}
result = true;
} else if (new_start_aligned > cur_committed.start()) {
// Shrink the committed region
#if 0 // uncommitting space is currently unsafe because of the interactions
// of growing and shrinking regions. One region A can uncommit space
// that it owns but which is being used by another region B (maybe).
// Region B has not committed the space because it was already
// committed by region A.
MemRegion uncommit_region = committed_unique_to_self(changed_region,
MemRegion(cur_committed.start(), new_start_aligned));
if (!uncommit_region.is_empty()) {
if (!os::uncommit_memory((char*)uncommit_region.start(),
uncommit_region.byte_size())) {
// If the uncommit fails, ignore it. Let the
// committed table resizing go even though the committed
// table will over state the committed space.
}
}
#else
assert(!result, "Should be false with current workaround");
#endif
}
assert(_committed[changed_region].end() == cur_committed.end(),
"end should not change");
return result;
}
void CardTableExtension::resize_update_committed_table(int changed_region,
MemRegion new_region) {
jbyte* new_start = byte_for(new_region.start());
// Set the new start of the committed region
HeapWord* new_start_aligned =
(HeapWord*)align_size_down((uintptr_t)new_start,
os::vm_page_size());
MemRegion new_committed = MemRegion(new_start_aligned,
_committed[changed_region].end());
_committed[changed_region] = new_committed;
_committed[changed_region].set_start(new_start_aligned);
}
void CardTableExtension::resize_update_card_table_entries(int changed_region,
MemRegion new_region) {
debug_only(verify_guard();)
MemRegion original_covered = _covered[changed_region];
// Initialize the card entries. Only consider the
// region covered by the card table (_whole_heap)
jbyte* entry;
if (new_region.start() < _whole_heap.start()) {
entry = byte_for(_whole_heap.start());
} else {
entry = byte_for(new_region.start());
}
jbyte* end = byte_for(original_covered.start());
// If _whole_heap starts at the original covered regions start,
// this loop will not execute.
while (entry < end) { *entry++ = clean_card; }
}
void CardTableExtension::resize_update_covered_table(int changed_region,
MemRegion new_region) {
// Update the covered region
_covered[changed_region].set_start(new_region.start());
_covered[changed_region].set_word_size(new_region.word_size());
// reorder regions. There should only be at most 1 out
// of order.
for (int i = _cur_covered_regions-1 ; i > 0; i--) {
if (_covered[i].start() < _covered[i-1].start()) {
MemRegion covered_mr = _covered[i-1];
_covered[i-1] = _covered[i];
_covered[i] = covered_mr;
MemRegion committed_mr = _committed[i-1];
_committed[i-1] = _committed[i];
_committed[i] = committed_mr;
break;
}
}
#ifdef ASSERT
for (int m = 0; m < _cur_covered_regions-1; m++) {
assert(_covered[m].start() <= _covered[m+1].start(),
"Covered regions out of order");
assert(_committed[m].start() <= _committed[m+1].start(),
"Committed regions out of order");
}
#endif
}
// Returns the start of any committed region that is lower than
// the target committed region (index ind) and that intersects the
// target region. If none, return start of target region.
//
// -------------
// | |
// -------------
// ------------
// | target |
// ------------
// -------------
// | |
// -------------
// ^ returns this
//
// -------------
// | |
// -------------
// ------------
// | target |
// ------------
// -------------
// | |
// -------------
// ^ returns this
HeapWord* CardTableExtension::lowest_prev_committed_start(int ind) const {
assert(_cur_covered_regions >= 0, "Expecting at least on region");
HeapWord* min_start = _committed[ind].start();
for (int j = 0; j < ind; j++) {
HeapWord* this_start = _committed[j].start();
if ((this_start < min_start) &&
!(_committed[j].intersection(_committed[ind])).is_empty()) {
min_start = this_start;
}
}
return min_start;
}
| 412 | 0.989356 | 1 | 0.989356 | game-dev | MEDIA | 0.623593 | game-dev | 0.950568 | 1 | 0.950568 |
gryffon/ringteki | 2,107 | server/game/cards/09.3-JfS/ShinjoGunso.js | import { CardTypes } from '../../Constants.js';
const DrawCard = require('../../drawcard.js');
const { Locations } = require('../../Constants');
const AbilityDsl = require('../../abilitydsl.js');
class ShinjoGunso extends DrawCard {
setupCardAbilities() {
this.chosenCard = null;
this.reaction({
title: 'Put a character into play',
when: {
onCardPlayed: (event, context) =>
event.card === context.source &&
[Locations.ProvinceOne, Locations.ProvinceTwo, Locations.ProvinceThree, Locations.ProvinceFour].includes(event.originalLocation)
},
effect: 'search the top 5 cards of their dynasty deck for a character that costs 2 or less and put it into play',
gameAction: AbilityDsl.actions.cardMenu(context => ({
activePromptTitle: 'Choose a character that costs 2 or less',
cards: context.player.dynastyDeck.first(5),
cardCondition: card => card.type === CardTypes.Character && card.printedCost <= 2,
choices: ['Don\'t choose a character'],
handlers: [
function() {
context.player.dynastyDeck.first(5).forEach(card => {
context.player.moveCard(card, Locations.DynastyDiscardPile);
});
context.game.addMessage('{0} chooses not to put a character into play', context.player);
}
],
subActionProperties: card => ({ target: card }),
gameAction: AbilityDsl.actions.sequential([
AbilityDsl.actions.putIntoPlay(),
AbilityDsl.actions.moveCard((context) => ({
target: context.player.dynastyDeck.first(4),
faceup: true,
destination: Locations.DynastyDiscardPile
}))
])
}))
});
}
}
ShinjoGunso.id = 'shinjo-gunso';
module.exports = ShinjoGunso;
| 412 | 0.827009 | 1 | 0.827009 | game-dev | MEDIA | 0.853121 | game-dev | 0.959653 | 1 | 0.959653 |
magefree/mage | 3,850 | Mage.Sets/src/mage/cards/t/ThunderousOrator.java | package mage.cards.t;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.MageSingleton;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.*;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.filter.FilterPermanent;
import mage.filter.StaticFilters;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.filter.predicate.mageobject.AbilityPredicate;
import mage.game.Game;
import java.util.*;
/**
* @author TheElk801
*/
public final class ThunderousOrator extends CardImpl {
public ThunderousOrator(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}");
this.subtype.add(SubType.KOR);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Vigilance
this.addAbility(VigilanceAbility.getInstance());
// Whenever Thunderous Orator attacks, it gains flying until end of turn if you control a creature with flying. The same is true for first strike, double strike, deathtouch, indestructible, lifelink, menace, and trample.
this.addAbility(new AttacksTriggeredAbility(new ThunderousOratorEffect(), false));
}
private ThunderousOrator(final ThunderousOrator card) {
super(card);
}
@Override
public ThunderousOrator copy() {
return new ThunderousOrator(this);
}
}
class ThunderousOratorEffect extends OneShotEffect {
private static final FilterPermanent filter = new FilterControlledCreaturePermanent();
static {
filter.add(new AbilityPredicate(MenaceAbility.class));
}
private static final List<MageSingleton> keywords = Arrays.asList(
FlyingAbility.getInstance(),
FirstStrikeAbility.getInstance(),
DoubleStrikeAbility.getInstance(),
DeathtouchAbility.getInstance(),
IndestructibleAbility.getInstance(),
LifelinkAbility.getInstance(),
TrampleAbility.getInstance()
);
ThunderousOratorEffect() {
super(Outcome.Benefit);
staticText = "it gains flying until end of turn if you control a creature with flying. The same is true " +
"for first strike, double strike, deathtouch, indestructible, lifelink, menace, and trample";
}
private ThunderousOratorEffect(final ThunderousOratorEffect effect) {
super(effect);
}
@Override
public ThunderousOratorEffect copy() {
return new ThunderousOratorEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
List<Ability> abilities = new ArrayList<>();
if (game.getBattlefield().count(filter, source.getControllerId(), source, game) > 0) {
abilities.add(new MenaceAbility());
}
game.getBattlefield()
.getActivePermanents(
StaticFilters.FILTER_CONTROLLED_CREATURE,
source.getControllerId(), source, game
).stream()
.filter(Objects::nonNull)
.map(p -> p.getAbilities(game))
.flatMap(Collection::stream)
.filter(keywords::contains)
.distinct()
.forEach(abilities::add);
if (abilities.isEmpty()) {
return false;
}
for (Ability ability : abilities) {
game.addEffect(new GainAbilitySourceEffect(ability, Duration.EndOfTurn), source);
}
return true;
}
}
| 412 | 0.970679 | 1 | 0.970679 | game-dev | MEDIA | 0.990617 | game-dev | 0.999082 | 1 | 0.999082 |
corphish/NightLight | 1,546 | app/src/main/java/com/corphish/nightlight/engine/kcal/DummyKCALManager.kt | package com.corphish.nightlight.engine.kcal
/*
* Dummy KCAL manager to handle devices without KCAL support
*/
class DummyKCALManager : KCALAbstraction {
/**
* A function to determine whether the implementation is supported by device
*/
override fun isSupported(): Boolean = false
/**
* A function to determine whether KCAL is enabled or not
*/
override fun isEnabled() : Boolean = false
/**
* A function to turn on KCAL
*/
override fun turnOn() {
// Not supported
}
/**
* A function to adjust KCAL colors
*/
override fun setColors(red: Int, green: Int, blue: Int) : Boolean = false
/**
* A function get current KCAL color readings
*/
override fun getColorReadings(): IntArray {
return intArrayOf(0, 0, 0)
}
/**
* Function to determine whether saturation is supported
*/
override fun isSaturationSupported(): Boolean {
return false
}
/**
* Function to get saturation
*/
override fun getSaturation(): Int {
return 0
}
/**
* Function to set saturation
*/
override fun setSaturation(value: Int): Boolean {
return false
}
override fun getImplementationName() = "Dummy KCAL Manager"
override fun getImplementationSwitchPath() = "Not available"
override fun getImplementationFilePaths() = "Not available"
override fun getImplementationFormat() = "Not applicable"
override fun getSaturationPath() = "Not available"
} | 412 | 0.818712 | 1 | 0.818712 | game-dev | MEDIA | 0.229025 | game-dev | 0.501938 | 1 | 0.501938 |
tylercamp/palcalc | 12,775 | PalCalc.SaveReader/ISaveGame.cs | using PalCalc.Model;
using PalCalc.SaveReader.SaveFile;
using PalCalc.SaveReader.SaveFile.Virtual;
using PalCalc.SaveReader.SaveFile.Xbox;
using System.Net;
namespace PalCalc.SaveReader
{
public class SaveFileLocation
{
// path to use when displaying or storing in a ZIP; Xbox save files have UUID-like names on disk
public string NormalizedPath { get; set; }
// actual file path
public string ActualPath { get; set; }
}
public interface ISaveGame : IDisposable
{
string BasePath { get; }
string UserId { get; } // generally based on the parent ISavesLocation
string GameId { get; }
DateTime LastModified { get; }
LevelSaveFile Level { get; }
LevelMetaSaveFile LevelMeta { get; }
LocalDataSaveFile LocalData { get; }
WorldOptionSaveFile WorldOption { get; }
List<PlayersSaveFile> Players { get; }
IEnumerable<SaveFileLocation> RawFiles { get; }
// (don't check `WorldOption`, not present for linux-based server saves)
bool IsValid { get; }
// Flag to indicate if the save game is on the local file system (affects whether `Updated` get used)
bool IsLocal { get; }
// note: won't be invoked for changes to Global Pal Storage, which isn't tied to any specific save
event Action<ISaveGame> Updated;
}
public class StandardSaveGame : ISaveGame
{
private FileSystemWatcher folderWatcher;
public event Action<ISaveGame> Updated;
private bool MatchesPath(string fileFullName, string baseFullName)
{
var baseName = Path.GetFileNameWithoutExtension(baseFullName);
var baseExt = Path.GetExtension(baseFullName);
var fileName = Path.GetFileNameWithoutExtension(fileFullName);
char[] allowedChars = ['-', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return (
fileFullName.StartsWith(baseName) &&
Path.GetExtension(fileFullName) == baseExt &&
(
fileName == baseName ||
allowedChars.Contains(fileName[baseName.Length])
)
);
}
public StandardSaveGame(string basePath)
{
BasePath = basePath;
Level = new LevelSaveFile(new FilteredFileSource(basePath, f => MatchesPath(f, "Level.sav")));
LevelMeta = new LevelMetaSaveFile(new FilteredFileSource(basePath, f => MatchesPath(f, "LevelMeta.sav")));
LocalData = new LocalDataSaveFile(new FilteredFileSource(basePath, f => MatchesPath(f, "LocalData.sav")));
WorldOption = new WorldOptionSaveFile(new FilteredFileSource(basePath, f => MatchesPath(f, "WorldOption.sav")));
var playersPath = Path.Join(basePath, "Players");
if (Directory.Exists(playersPath))
{
Players = Directory
.EnumerateFiles(playersPath, "*.sav")
.Where(f => !Path.GetFileNameWithoutExtension(f).EndsWith("_dps"))
.Select(f =>
{
var baseName = Path.GetFileNameWithoutExtension(f);
var dpsPath = $"{playersPath}/{baseName}_dps.sav";
var dpsFile = File.Exists(dpsPath) ? new PlayersDpsSaveFile(new SingleFileSource(dpsPath)) : null;
return new PlayersSaveFile(new SingleFileSource(f), dpsFile);
})
.ToList();
}
else
{
Players = new List<PlayersSaveFile>();
}
if (Directory.Exists(basePath))
{
IsLocal = true;
if (new Uri(basePath).IsUnc)
{
try
{
IPAddress[] host;
// get host addresses
host = Dns.GetHostAddresses(basePath);
// get local addresses
IPAddress[] local = Dns.GetHostAddresses(Dns.GetHostName());
// check if local
if (!host.Any(hostAddress => IPAddress.IsLoopback(hostAddress) || local.Contains(hostAddress)))
{
IsLocal = false;
}
}
catch (Exception)
{
IsLocal = false;
}
}
folderWatcher = new FileSystemWatcher(basePath);
folderWatcher.Changed += FolderWatcher_Updated;
folderWatcher.Created += FolderWatcher_Updated;
folderWatcher.Deleted += FolderWatcher_Updated;
folderWatcher.Renamed += FolderWatcher_Updated;
folderWatcher.IncludeSubdirectories = true;
folderWatcher.EnableRaisingEvents = true;
}
else
{
IsLocal = false;
}
}
public void Dispose()
{
if (folderWatcher != null)
{
folderWatcher.Changed -= FolderWatcher_Updated;
folderWatcher.Created -= FolderWatcher_Updated;
folderWatcher.Deleted -= FolderWatcher_Updated;
folderWatcher.Renamed -= FolderWatcher_Updated;
folderWatcher.Dispose();
folderWatcher = null;
}
}
private void FolderWatcher_Updated(object sender, FileSystemEventArgs e)
{
Updated?.Invoke(this);
}
public string BasePath { get; private set; }
public string UserId => Path.GetFileName(Path.GetDirectoryName(BasePath));
public string GameId => Path.GetFileName(BasePath);
public string FolderName => Path.GetFileName(BasePath);
public DateTime LastModified => new List<DateTime>()
{
Directory.GetLastWriteTime(BasePath),
Level.Exists ? Level.LastModified : DateTime.MinValue,
LevelMeta.Exists ? LevelMeta.LastModified : DateTime.MinValue,
LocalData.Exists ? LocalData.LastModified : DateTime.MinValue,
WorldOption.Exists ? WorldOption.LastModified : DateTime.MinValue,
}.Concat(Players.Select(p => p.LastModified)).Max();
public LevelSaveFile Level { get; }
public LevelMetaSaveFile LevelMeta { get; }
public LocalDataSaveFile LocalData { get; }
public WorldOptionSaveFile WorldOption { get; }
public List<PlayersSaveFile> Players { get; }
public IEnumerable<SaveFileLocation> RawFiles => !Path.Exists(BasePath) ? [] : (
Directory
.EnumerateFiles(BasePath, "*.sav", SearchOption.AllDirectories)
.Where(p =>
{
return !p.Substring(BasePath.Length).Replace('\\', '/').StartsWith("/backup");
})
.Select(p => new SaveFileLocation() { ActualPath = p, NormalizedPath = p.Substring(BasePath.Length + 1) })
);
public bool IsValid => Level != null && Level.IsValid;
public bool IsLocal { get; private set; }
public override string ToString() => FolderName;
}
public class XboxSaveGame : ISaveGame
{
public event Action<ISaveGame> Updated;
private XboxSaveMonitor monitor;
private XboxWgsFolder wgsFolder;
public XboxSaveGame(
XboxWgsFolder wgsFolder,
string saveId
)
{
BasePath = wgsFolder.UserBasePath;
GameId = saveId;
this.wgsFolder = wgsFolder;
// note: no UNC path check, these should only be created for normal e.g. LocalAppData paths
IsLocal = true;
var filesByType = wgsFolder
.Entries
.Where(e => e.FileName.StartsWith($"{saveId}-"))
.GroupBy(f => f.FileName.Split('-')[1]).ToDictionary(g => g.Key, g => g.ToList());
if (filesByType.ContainsKey("Level"))
{
Level = new LevelSaveFile(new XboxGameFileSource(wgsFolder, saveId, f => f.Split("-").First() == "Level"));
}
if (filesByType.ContainsKey("LevelMeta"))
{
LevelMeta = new LevelMetaSaveFile(new XboxGameFileSource(wgsFolder, saveId, f => f.Split("-").First() == "LevelMeta"));
}
if (filesByType.ContainsKey("LocalData"))
{
LocalData = new LocalDataSaveFile(new XboxGameFileSource(wgsFolder, saveId, f => f.Split("-").First() == "LocalData"));
}
if (filesByType.ContainsKey("WorldOption"))
{
WorldOption = new WorldOptionSaveFile(new XboxGameFileSource(wgsFolder, saveId, f => f.Split("-").First() == "WorldOption"));
}
var playersFiles = filesByType.GetValueOrElse("Players", new List<XboxWgsEntry>());
Players = playersFiles
.Where(f => !f.FileName.EndsWith("_dps"))
.Select(f =>
{
var mainSource = new XboxGameFileSource(wgsFolder, saveId, nameWithoutSaveId => f.FileName == $"{saveId}-{nameWithoutSaveId}");
var dpsSource = new XboxGameFileSource(wgsFolder, saveId, nameWithoutSaveId => $"{f.FileName}_dps" == $"{saveId}-{nameWithoutSaveId}");
var dpsFile = dpsSource.Content.Any() ? new PlayersDpsSaveFile(dpsSource) : null;
return new PlayersSaveFile(mainSource, dpsFile);
})
.ToList();
monitor = wgsFolder.Monitor.GetSaveMonitor(saveId);
monitor.Updated += Monitor_Updated;
}
private void Monitor_Updated() => Updated?.Invoke(this);
public void Dispose() => this.monitor.Updated -= Monitor_Updated;
public string BasePath { get; }
public string UserId => Path.GetFileName(BasePath);
public string GameId { get; }
public DateTime LastModified => new ISaveFile[] { Level, LevelMeta, LocalData, WorldOption }.Concat(Players).Max(s => s?.LastModified ?? DateTime.MinValue);
public LevelSaveFile Level { get; }
public LevelMetaSaveFile LevelMeta { get; }
public LocalDataSaveFile LocalData { get; }
public WorldOptionSaveFile WorldOption { get; }
public List<PlayersSaveFile> Players { get; }
public IEnumerable<SaveFileLocation> RawFiles =>
new XboxGameFileSource(wgsFolder, GameId, _ => true)
.XboxContent
// "SlotX-..." files are backups
.Where(f => !f.FileName.Contains("Slot"))
.Select(f => new SaveFileLocation()
{
ActualPath = f.FilePath,
NormalizedPath = f.FileName.Replace($"{GameId}-", "") + ".sav"
});
public bool IsValid =>
Level != null && Level.IsValid; // don't check for `LevelMeta` - may be temporarily missing for files with "wrapper" header
public bool IsLocal { get; private set; }
}
/// <summary>
/// A fake save-game whose ISaveFiles don't return any data. Meant to be a placeholder for "fake" saves added in Pal Calc.
/// </summary>
public class VirtualSaveGame : ISaveGame
{
public VirtualSaveGame(
string userId,
string gameId,
VirtualLevelSaveFile level,
VirtualLevelMetaSaveFile levelMeta,
VirtualLocalDataSaveFile localData,
VirtualWorldOptionSaveFile worldOption
)
{
Level = level;
LevelMeta = levelMeta;
LocalData = localData;
WorldOption = worldOption;
Players = [];
UserId = userId;
GameId = gameId;
}
public void Dispose()
{
}
public string BasePath => null;
public string UserId { get; }
public string GameId { get; }
public DateTime LastModified { get; set; } = DateTime.Now;
public LevelSaveFile Level { get; }
public LevelMetaSaveFile LevelMeta { get; }
public LocalDataSaveFile LocalData { get; }
public WorldOptionSaveFile WorldOption { get; }
public List<PlayersSaveFile> Players { get; }
public IEnumerable<SaveFileLocation> RawFiles => [];
public bool IsValid => true;
public bool IsLocal => true;
public event Action<ISaveGame> Updated;
}
}
| 412 | 0.913341 | 1 | 0.913341 | game-dev | MEDIA | 0.406856 | game-dev,desktop-app | 0.954615 | 1 | 0.954615 |
DanceManiac/Advanced-X-Ray-Public | 2,559 | SourcesAXR/xrGameCS/ai/monsters/burer/burer_state_manager.cpp | #include "stdafx.h"
#include "burer.h"
#include "burer_state_manager.h"
#include "../control_animation_base.h"
#include "../control_direction_base.h"
#include "../control_movement_base.h"
#include "../control_path_builder_base.h"
#include "../states/monster_state_rest.h"
#include "../states/monster_state_panic.h"
#include "../states/monster_state_eat.h"
#include "../states/monster_state_hear_int_sound.h"
#include "../states/monster_state_hear_danger_sound.h"
#include "../states/monster_state_hitted.h"
#include "../states/state_custom_action.h"
#include "burer_state_attack.h"
CStateManagerBurer::CStateManagerBurer(CBurer *monster) : inherited(monster)
{
add_state(eStateRest, xr_new<CStateMonsterRest<CBurer> > (monster));
add_state(eStatePanic, xr_new<CStateMonsterPanic<CBurer> > (monster));
add_state(eStateAttack, xr_new<CStateBurerAttack<CBurer> > (monster));
add_state(eStateEat, xr_new<CStateMonsterEat<CBurer> > (monster));
add_state(eStateHearInterestingSound, xr_new<CStateMonsterHearInterestingSound<CBurer> > (monster));
add_state(eStateHearDangerousSound, xr_new<CStateMonsterHearDangerousSound<CBurer> > (monster));
add_state(eStateHitted, xr_new<CStateMonsterHitted<CBurer> > (monster));
add_state(eStateBurerScanning, xr_new<CStateMonsterCustomAction<CBurer> > (monster));
}
#define SCAN_STATE_TIME 4000
void CStateManagerBurer::execute()
{
u32 state = u32(-1);
if (object->EnemyMan.get_enemy()) {
switch (object->EnemyMan.get_danger_type()) {
case eStrong: state = eStatePanic; break;
case eWeak: state = eStateAttack; break;
}
} else if (object->HitMemory.is_hit() && (object->HitMemory.get_last_hit_time() + 10000 > Device.dwTimeGlobal))
state = eStateHitted;
else if (object->hear_interesting_sound)
state = eStateHearInterestingSound;
else if (object->hear_dangerous_sound )
state = eStateHearDangerousSound;
else if (object->time_last_scan + SCAN_STATE_TIME > Device.dwTimeGlobal)
state = eStateBurerScanning;
else if (can_eat())
state = eStateEat;
else state = eStateRest;
select_state(state);
//
get_state_current()->execute();
prev_substate = current_substate;
}
void CStateManagerBurer::setup_substates()
{
if (current_substate == eStateBurerScanning) {
SStateDataAction data;
data.action = ACT_LOOK_AROUND;
data.sound_type = MonsterSound::eMonsterSoundIdle;
data.sound_delay = object->db().m_dwIdleSndDelay;
get_state_current()->fill_data_with(&data, sizeof(SStateDataAction));
return;
}
}
| 412 | 0.870751 | 1 | 0.870751 | game-dev | MEDIA | 0.955778 | game-dev | 0.855257 | 1 | 0.855257 |
JHGuitarFreak/UQM-MegaMod | 4,858 | src/uqm/supermelee/meleesetup.h | /*
* 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.
*/
#ifndef MELEESETUP_H
#define MELEESETUP_H
typedef struct MeleeTeam MeleeTeam;
typedef struct MeleeSetup MeleeSetup;
#ifdef MELEESETUP_INTERNAL
# define MELEETEAM_INTERNAL
#endif /* MELEESETUP_INTERNAL */
#include "libs/compiler.h"
typedef COUNT FleetShipIndex;
#include "libs/uio.h"
#include "melee.h"
#include "meleeship.h"
#if defined(__cplusplus)
extern "C" {
#endif
#ifdef MELEETEAM_INTERNAL
struct MeleeTeam
{
MeleeShip ships[MELEE_FLEET_SIZE];
char name[MAX_TEAM_CHARS + 1 + 24];
/* The +1 is for the terminating \0; the +24 is in case some
* default name in starcon.txt is unknowingly mangled. */
// XXX: SvdB: Why would it be mangled? Why don't we just reject
// it if it is? Is this so that we have some space
// for multibyte UTF-8 chars?
};
#endif /* MELEETEAM_INTERNAL */
#ifdef MELEESETUP_INTERNAL
struct MeleeSetup
{
MeleeTeam teams[NUM_SIDES];
COUNT fleetValue[NUM_SIDES];
#ifdef NETPLAY
MeleeTeam sentTeams[NUM_SIDES];
// The last sent (parts of) teams.
// Used in the Update protocol. See doc/devel/netplay/protocol
// XXX: this may actually be deallocated when the battle starts.
bool haveSentTeamName[NUM_SIDES];
// Whether we have sent a team name this 'turn'.
// Used in the Update protocol. See doc/devel/netplay/protocol
// (also for the term 'turn').
#endif
};
#endif /* MELEESETUP_INTERNAL */
extern const size_t MeleeTeam_serialSize;
void MeleeTeam_init (MeleeTeam *team);
void MeleeTeam_uninit (MeleeTeam *team);
MeleeTeam *MeleeTeam_new (void);
void MeleeTeam_delete (MeleeTeam *team);
#ifdef NETPLAY
void MeleeSetup_resetSentTeams (MeleeSetup *setup);
#endif /* NETPLAY */
int MeleeTeam_serialize (const MeleeTeam *team, uio_Stream *stream);
int MeleeTeam_deserialize (MeleeTeam *team, uio_Stream *stream);
COUNT MeleeTeam_getValue (const MeleeTeam *team);
MeleeShip MeleeTeam_getShip (const MeleeTeam *team, FleetShipIndex slotNr);
void MeleeTeam_setShip (MeleeTeam *team, FleetShipIndex slotNr,
MeleeShip ship);
const MeleeShip *MeleeTeam_getFleet (const MeleeTeam *team);
const char *MeleeTeam_getTeamName (const MeleeTeam *team);
void MeleeTeam_setName (MeleeTeam *team, const char *name);
void MeleeTeam_copy (MeleeTeam *copy, const MeleeTeam *original);
#if 0
bool MeleeTeam_isEqual (const MeleeTeam *team1, const MeleeTeam *team2);
#endif
#ifdef NETPLAY
MeleeShip MeleeSetup_getSentShip (const MeleeSetup *setup, size_t teamNr,
FleetShipIndex slotNr);
const char *MeleeSetup_getSentTeamName (const MeleeSetup *setup,
size_t teamNr);
bool MeleeSetup_setSentShip (MeleeSetup *setup, size_t teamNr,
FleetShipIndex slotNr, MeleeShip ship);
bool MeleeSetup_setSentTeamName (MeleeSetup *setup, size_t teamNr,
const char *name);
#if 0
bool MeleeSetup_isTeamSent (MeleeSetup *setup, size_t teamNr);
#endif
#endif /* NETPLAY */
MeleeSetup *MeleeSetup_new (void);
void MeleeSetup_delete (MeleeSetup *setup);
bool MeleeSetup_setShip (MeleeSetup *setup, size_t teamNr,
FleetShipIndex slotNr, MeleeShip ship);
MeleeShip MeleeSetup_getShip (const MeleeSetup *setup, size_t teamNr,
FleetShipIndex slotNr);
bool MeleeSetup_setFleet (MeleeSetup *setup, size_t teamNr,
const MeleeShip *fleet);
const MeleeShip *MeleeSetup_getFleet (const MeleeSetup *setup, size_t teamNr);
bool MeleeSetup_setTeamName (MeleeSetup *setup, size_t teamNr,
const char *name);
const char *MeleeSetup_getTeamName (const MeleeSetup *setup,
size_t teamNr);
COUNT MeleeSetup_getFleetValue (const MeleeSetup *setup, size_t teamNr);
int MeleeSetup_deserializeTeam (MeleeSetup *setup, size_t teamNr,
uio_Stream *stream);
int MeleeSetup_serializeTeam (const MeleeSetup *setup, size_t teamNr,
uio_Stream *stream);
void MeleeState_setShip (MELEE_STATE *pMS, size_t teamNr,
FleetShipIndex slotNr, MeleeShip ship);
void MeleeState_setFleet (MELEE_STATE *pMS, size_t teamNr,
const MeleeShip *fleet);
void MeleeState_setTeamName (MELEE_STATE *pMS, size_t teamNr,
const char *name);
void MeleeState_setTeam (MELEE_STATE *pMS, size_t teamNr,
const MeleeTeam *team);
#if defined(__cplusplus)
}
#endif
#endif /* MELEESETUP_H */
| 412 | 0.955498 | 1 | 0.955498 | game-dev | MEDIA | 0.942208 | game-dev | 0.789787 | 1 | 0.789787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.