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
jsgroth/jgenesis
25,105
backend/gb-core/src/ppu.rs
//! Game Boy PPU (picture processing unit) mod debug; mod fifo; mod registers; use crate::HardwareMode; use crate::cgb::{CgbRegisters, CpuSpeed}; use crate::dma::DmaUnit; use crate::interrupts::InterruptRegisters; use crate::ppu::fifo::PixelFifo; use crate::ppu::registers::{CgbPaletteRam, Registers}; use crate::sm83::InterruptType; use bincode::{Decode, Encode}; use jgenesis_common::frontend::FrameSize; use jgenesis_common::num::GetBit; use jgenesis_proc_macros::{FakeDecode, FakeEncode}; use std::ops::{Deref, DerefMut, Range}; const SCREEN_WIDTH: usize = 160; const SCREEN_HEIGHT: usize = 144; pub const FRAME_BUFFER_LEN: usize = SCREEN_WIDTH * SCREEN_HEIGHT; pub const FRAME_SIZE: FrameSize = FrameSize { width: SCREEN_WIDTH as u32, height: SCREEN_HEIGHT as u32 }; // 144 rendered lines + 10 VBlank lines pub const LINES_PER_FRAME: u8 = 154; pub const DOTS_PER_LINE: u16 = 456; const OAM_SCAN_DOTS: u16 = 80; const MAX_SPRITES_PER_LINE: usize = 10; const VRAM_LEN: usize = 16 * 1024; const OAM_LEN: usize = 160; type Vram = [u8; VRAM_LEN]; type Oam = [u8; OAM_LEN]; #[derive(Debug, Clone, FakeEncode, FakeDecode)] pub struct PpuFrameBuffer(Box<[u16; FRAME_BUFFER_LEN]>); impl PpuFrameBuffer { pub fn iter(&self) -> impl Iterator<Item = u16> + '_ { self.0.iter().copied() } fn set(&mut self, line: u8, pixel: u8, color: u16) { self[(line as usize) * SCREEN_WIDTH + (pixel as usize)] = color; } } impl Default for PpuFrameBuffer { fn default() -> Self { Self(vec![0; FRAME_BUFFER_LEN].into_boxed_slice().try_into().unwrap()) } } impl Deref for PpuFrameBuffer { type Target = [u16; FRAME_BUFFER_LEN]; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for PpuFrameBuffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub enum PpuMode { // Mode 1 VBlank, // Mode 0 HBlank, // Mode 2 ScanningOam, // Glitched mode 2 that occurs after re-enabling the PPU ScanningOamGlitched, // Mode 3 Rendering, } impl PpuMode { fn to_bits(self) -> u8 { match self { Self::HBlank => 0, Self::VBlank => 1, Self::ScanningOam | Self::ScanningOamGlitched => 2, Self::Rendering => 3, } } fn is_scanning_oam(self) -> bool { matches!(self, Self::ScanningOam | Self::ScanningOamGlitched) } } #[derive(Debug, Clone, Encode, Decode)] struct State { scanline: u8, dot: u16, mode: PpuMode, prev_stat_interrupt_line: bool, stat_interrupt_pending: bool, previously_enabled: bool, // LY=LYC bit in STAT does not change while PPU is disabled, per: // https://gbdev.gg8.se/wiki/articles/Tricky-to-emulate_games frozen_ly_lyc_bit: bool, skip_next_frame: bool, frame_complete: bool, powered_off_dots: u32, } impl State { fn new() -> Self { Self { scanline: 0, dot: 0, mode: PpuMode::ScanningOam, prev_stat_interrupt_line: false, stat_interrupt_pending: false, previously_enabled: true, frozen_ly_lyc_bit: false, skip_next_frame: true, frame_complete: false, powered_off_dots: 0, } } fn ly(&self) -> u8 { if self.scanline == LINES_PER_FRAME - 1 && self.dot >= 4 { // LY=0 starts 4 dots into the final scanline. Kirby's Dream Land 2 and Wario Land 2 depend on this for // minor top-of-screen effects 0 } else { self.scanline } } fn ly_for_compare(&self, cpu_speed: CpuSpeed) -> u8 { // This handles two edge cases for LY=LYC interrupts: // // 1. HBlank interrupts should not block LY=LYC interrupts; Ken Griffey Jr.'s Slugfest // depends on this // // 2. When LYC=0, the LY=LYC interrupt should not trigger before dot 9 in single speed // or before dot 13 in CGB double speed. The demo Mental Respirator depends on this for the // "gin & tonic trick" effect match self.scanline { 0 => 0, line @ 1..=152 => { if self.dot != 0 { line } else { line - 1 } } 153 => match (self.dot, cpu_speed) { (0, _) => 152, (1..=8, _) | (9..=12, CpuSpeed::Double) => 153, _ => 0, }, _ => panic!("Invalid scanline in state: {}", self.scanline), } } } #[derive(Debug, Clone, Copy, Encode, Decode)] struct SpriteData { oam_index: u8, x: u8, y: u8, tile_number: u8, vram_bank: u8, palette: u8, horizontal_flip: bool, vertical_flip: bool, low_priority: bool, } #[derive(Debug, Clone, Encode, Decode)] pub struct Ppu { hardware_mode: HardwareMode, frame_buffer: PpuFrameBuffer, vram: Box<Vram>, oam: Box<Oam>, registers: Registers, bg_palette_ram: CgbPaletteRam, sprite_palette_ram: CgbPaletteRam, state: State, sprite_buffer: Vec<SpriteData>, fifo: PixelFifo, } impl Ppu { pub fn new(hardware_mode: HardwareMode, rom: &[u8], boot_rom_present: bool) -> Self { let mut vram = vec![0; VRAM_LEN]; if !boot_rom_present { initialize_vram(hardware_mode, rom, &mut vram); } Self { hardware_mode, frame_buffer: PpuFrameBuffer::default(), vram: vram.into_boxed_slice().try_into().unwrap(), oam: vec![0; OAM_LEN].into_boxed_slice().try_into().unwrap(), registers: Registers::new(boot_rom_present), bg_palette_ram: CgbPaletteRam::new_bg(), sprite_palette_ram: CgbPaletteRam::new_obj(), state: State::new(), sprite_buffer: Vec::with_capacity(MAX_SPRITES_PER_LINE), fifo: PixelFifo::new(hardware_mode), } } pub fn tick_dot( &mut self, cgb_registers: CgbRegisters, dma_unit: &DmaUnit, interrupt_registers: &mut InterruptRegisters, ) { if !self.registers.ppu_enabled { if self.state.previously_enabled { // Disabling PPU freezes the LY=LYC bit until it's re-enabled, per: // https://gbdev.gg8.se/wiki/articles/Tricky-to-emulate_games self.state.frozen_ly_lyc_bit = self.state.scanline == self.registers.ly_compare; // Disabling the PPU moves it to line 0 + mode 0 and clears the display self.state.scanline = 0; self.state.dot = 0; self.state.mode = PpuMode::HBlank; self.sprite_buffer.clear(); self.fifo.reset_window_state(); self.fifo.start_new_line(0, &self.registers, &[]); self.state.previously_enabled = false; self.state.stat_interrupt_pending = false; self.state.prev_stat_interrupt_line = false; self.state.powered_off_dots = 0; } self.state.powered_off_dots += 1; if self.state.powered_off_dots == u32::from(LINES_PER_FRAME) * u32::from(DOTS_PER_LINE) { // Force a blank frame render if the PPU is powered off for a full frame's worth of cycles self.clear_frame_buffer(); self.state.frame_complete = true; self.state.powered_off_dots = 0; } // Unlike TV-based systems, the PPU does not process at all when display is disabled return; } else if !self.state.previously_enabled { self.state.previously_enabled = true; // Restarting the PPU at dot 4 instead of 0 fixes graphical glitches in GBVideoPlayer2 self.state.dot = 4; // When the PPU is re-enabled, the next frame is not displayed self.state.skip_next_frame = true; self.state.mode = PpuMode::ScanningOamGlitched; } // STAT interrupts don't seem to fire during the first 4 dots of line 0 if self.state.stat_interrupt_pending && (self.state.scanline != 0 || self.state.dot >= 4) { log::trace!( "Generating STAT interrupt at line {} dot {}", self.state.scanline, self.state.dot ); interrupt_registers.set_flag(InterruptType::LcdStatus); self.state.stat_interrupt_pending = false; } if self.state.mode == PpuMode::Rendering { let frame_buffer = (!self.state.skip_next_frame).then_some(&mut self.frame_buffer); self.fifo.tick( &self.vram, &self.registers, cgb_registers, &self.bg_palette_ram, &self.sprite_palette_ram, frame_buffer, ); if self.fifo.done_with_line() { log::trace!( "Pixel FIFO finished line {} after dot {}", self.state.scanline, self.state.dot ); self.state.mode = PpuMode::HBlank; } } self.state.dot += 1; if self.state.dot == DOTS_PER_LINE { // Check the window Y condition again before moving to the next line. // The fairylake.gb test ROM depends on this because it enables the window during mode 3 // with WY==LY self.fifo.check_window_y(self.state.scanline, &self.registers); self.state.dot = 0; self.state.scanline += 1; if self.state.scanline == LINES_PER_FRAME { self.state.scanline = 0; self.fifo.reset_window_state(); } if self.state.scanline < SCREEN_HEIGHT as u8 { self.state.mode = PpuMode::ScanningOam; self.sprite_buffer.clear(); // PPU cannot read OAM while an OAM DMA is in progress // TODO does anything depend on partial OAM scan when an OAM DMA finishes during mode 2? if !dma_unit.oam_dma_in_progress() { scan_oam( self.hardware_mode, cgb_registers.dmg_compatibility, self.state.scanline, self.registers.double_height_sprites, &self.oam, &mut self.sprite_buffer, ); } } else { self.state.mode = PpuMode::VBlank; } } else if self.state.scanline < SCREEN_HEIGHT as u8 && self.state.dot == OAM_SCAN_DOTS { self.fifo.start_new_line(self.state.scanline, &self.registers, &self.sprite_buffer); self.state.mode = PpuMode::Rendering; } // TODO timing if self.state.scanline == SCREEN_HEIGHT as u8 && self.state.dot == 1 { interrupt_registers.set_flag(InterruptType::VBlank); if self.state.skip_next_frame { self.state.skip_next_frame = false; } else { self.state.frame_complete = true; } // Obscure behavior: If the mode 2 STAT interrupt is enabled, it will trigger a STAT // interrupt on line 144 around the same time that VBlank starts. // // GB Video Player (https://github.com/LIJI32/GBVideoPlayer) depends on this because // it uses the Mode 2 STAT interrupt and expects it to trigger 145 times per frame, not 144 if !self.state.prev_stat_interrupt_line && self.registers.mode_2_interrupt_enabled { interrupt_registers.set_flag(InterruptType::LcdStatus); } } let stat_interrupt_line = self.stat_interrupt_line(cgb_registers.speed); if !self.state.prev_stat_interrupt_line && stat_interrupt_line { self.state.stat_interrupt_pending = true; log::trace!( "Setting STAT pending: LY={}, LYC={}, mode={:?}", self.state.ly(), self.registers.ly_compare, self.state.mode ); } self.state.prev_stat_interrupt_line = stat_interrupt_line; } fn clear_frame_buffer(&mut self) { log::trace!("Clearing PPU frame buffer"); // Disabling display makes the entire display white, which is color 0 on DMG // and color 31/31/31 ($7FFF) on CGB let fill_color = match self.hardware_mode { HardwareMode::Dmg => 0, HardwareMode::Cgb => 0b11111_11111_11111, }; self.frame_buffer.fill(fill_color); // Signal that the frame should be displayed self.state.frame_complete = true; } fn stat_interrupt_line(&self, cpu_speed: CpuSpeed) -> bool { let lyc_interrupt_enabled = self.registers.lyc_interrupt_enabled; let mode_2_interrupt_enabled = self.registers.mode_2_interrupt_enabled; let mode_1_interrupt_enabled = self.registers.mode_1_interrupt_enabled; let mode_0_interrupt_enabled = self.registers.mode_0_interrupt_enabled; (lyc_interrupt_enabled && self.state.ly_for_compare(cpu_speed) == self.registers.ly_compare) || (mode_2_interrupt_enabled && self.state.mode.is_scanning_oam()) || (mode_1_interrupt_enabled && self.state.mode == PpuMode::VBlank) || (mode_0_interrupt_enabled && self.state.mode == PpuMode::HBlank) } pub fn frame_buffer(&self) -> &PpuFrameBuffer { &self.frame_buffer } pub fn frame_complete(&self) -> bool { self.state.frame_complete } pub fn clear_frame_complete(&mut self) { self.state.frame_complete = false; } pub fn read_vram(&self, address: u16) -> u8 { if self.cpu_can_access_vram() { let vram_addr = map_vram_address(address, self.registers.vram_bank); self.vram[vram_addr as usize] } else { 0xFF } } pub fn write_vram(&mut self, address: u16, value: u8) { if self.cpu_can_access_vram() { let vram_addr = map_vram_address(address, self.registers.vram_bank); self.vram[vram_addr as usize] = value; } } pub fn read_oam(&self, address: u16) -> u8 { if self.cpu_can_access_oam() { self.oam[(address & 0xFF) as usize] } else { 0xFF } } pub fn write_oam(&mut self, address: u16, value: u8) { if self.cpu_can_access_oam() { self.oam[(address & 0xFF) as usize] = value; } } // OAM DMA can write to OAM at any time, even during Modes 2 and 3 pub fn write_oam_for_dma(&mut self, address: u16, value: u8) { self.oam[(address & 0xFF) as usize] = value; } fn cpu_can_access_oam(&self) -> bool { !matches!(self.state.mode, PpuMode::ScanningOam | PpuMode::Rendering) } fn cpu_can_access_vram(&self) -> bool { // Allow access even during mode 3 if dot <= 84. // Because of how the CPU and PPU are executed, a write at dot == 80 would have occurred // on dot 78 (single-speed) or dot 79 (double-speed) on actual hardware and would not have // been blocked. // Allowing writes on dots 81-84 (probably 81-83 in actual hardware) is a hack to fix // what seems to be a timing issue elsewhere, possibly interrupt-related. The Stunt Race FX // demo depends on allowing these through self.state.mode != PpuMode::Rendering || self.state.dot <= OAM_SCAN_DOTS + 4 } pub fn mode(&self) -> PpuMode { self.state.mode } pub fn read_register(&self, address: u16, cgb_registers: CgbRegisters) -> u8 { match address & 0xFF { 0x40 => self.registers.read_lcdc(), 0x41 => self.registers.read_stat(&self.state, cgb_registers.speed), 0x42 => self.registers.bg_y_scroll, 0x43 => self.registers.bg_x_scroll, // LY: Line number 0x44 => self.state.ly(), 0x45 => self.registers.ly_compare, 0x47 => self.registers.read_bgp(), 0x48 => self.registers.read_obp0(), 0x49 => self.registers.read_obp1(), 0x4A => self.registers.window_y, 0x4B => self.registers.window_x, 0x4F => self.registers.read_vbk(), 0x68 => self.bg_palette_ram.read_data_port_address(), 0x69 => self.bg_palette_ram.read_data_port(self.cpu_can_access_vram()), 0x6A => self.sprite_palette_ram.read_data_port_address(), 0x6B => self.sprite_palette_ram.read_data_port(self.cpu_can_access_vram()), _ => { log::warn!("PPU register read {address:04X}"); 0xFF } } } pub fn write_register( &mut self, address: u16, value: u8, speed: CpuSpeed, interrupt_registers: &mut InterruptRegisters, ) { log::trace!( "PPU register write on line {} dot {}: {address:04X} set to {value:02X}", self.state.scanline, self.state.dot ); match address & 0xFF { 0x40 => self.registers.write_lcdc(value), 0x41 => self.write_stat(value, interrupt_registers), 0x42 => self.registers.write_scy(value), 0x43 => self.registers.write_scx(value), // LY, not writable 0x44 => {} 0x45 => self.write_lyc(value, speed), 0x47 => self.registers.write_bgp(value), 0x48 => self.registers.write_obp0(value), 0x49 => self.registers.write_obp1(value), 0x4A => self.registers.write_wy(value), 0x4B => self.registers.write_wx(value), 0x4F => self.registers.write_vbk(value), 0x68 => self.bg_palette_ram.write_data_port_address(value), 0x69 => self.bg_palette_ram.write_data_port(value, self.cpu_can_access_vram()), 0x6A => self.sprite_palette_ram.write_data_port_address(value), 0x6B => self.sprite_palette_ram.write_data_port(value, self.cpu_can_access_vram()), _ => log::warn!("PPU register write {address:04X} {value:02X}"), } } fn write_stat(&mut self, value: u8, interrupt_registers: &mut InterruptRegisters) { if self.hardware_mode == HardwareMode::Dmg && self.registers.ppu_enabled { // DMG STAT bug: If STAT is written while any of the 4 STAT conditions are true, the // hardware behaves as if all 4 STAT interrupts are enabled for a single M-cycle. // Road Rash (GB version) and Zerd no Densetsu depend on this let dmg_stat_bug_triggered = self.state.mode != PpuMode::Rendering || self.state.ly_for_compare(CpuSpeed::Normal) == self.registers.ly_compare; if dmg_stat_bug_triggered { // It seems that the DMG STAT bug does not trigger if HBlank interrupts were previously // enabled and the current mode is 2 (OAM scan). This doesn't really make sense, but // this fixes Initial D Gaiden and doesn't break Road Rash or Zerd no Densetsu let suppress_oam_interrupts = self.registers.mode_0_interrupt_enabled && self.state.mode == PpuMode::ScanningOam; let bugged_stat_write = !(u8::from(suppress_oam_interrupts) << 5); self.registers.write_stat(bugged_stat_write); let stat_interrupt_line = self.stat_interrupt_line(CpuSpeed::Normal); if !self.state.prev_stat_interrupt_line && stat_interrupt_line { interrupt_registers.set_flag(InterruptType::LcdStatus); } self.state.prev_stat_interrupt_line = stat_interrupt_line; } } self.registers.write_stat(value); } fn write_lyc(&mut self, value: u8, speed: CpuSpeed) { self.registers.write_lyc(value); // If changing LYC would cause the STAT interrupt line to go from high to low, immediately // pull it low. // This fixes graphical glitches in SQRKZ, where it sometimes changes LYC from 141 to 142 // on line=142 dot=0, and the LY=LYC STAT interrupt should trigger almost immediately. // TODO timing around the LY=LYC interrupt is iffy in general - improve this if value == self.state.scanline && self.state.dot == 0 { let stat_interrupt_line = self.stat_interrupt_line(speed); self.state.prev_stat_interrupt_line &= stat_interrupt_line; } } } fn map_vram_address(address: u16, vram_bank: u8) -> u16 { (u16::from(vram_bank) << 13) | (address & 0x1FFF) } fn scan_oam( hardware_mode: HardwareMode, cgb_dmg_compatibility: bool, scanline: u8, double_height_sprites: bool, oam: &Oam, sprite_buffer: &mut Vec<SpriteData>, ) { let sprite_height = if double_height_sprites { 16 } else { 8 }; for oam_idx in 0..OAM_LEN / 4 { let oam_addr = 4 * oam_idx; let y = oam[oam_addr]; // Check if sprite overlaps current line let sprite_top = i16::from(y) - 16; let sprite_bottom = sprite_top + sprite_height; if !(sprite_top..sprite_bottom).contains(&scanline.into()) { continue; } let x = oam[oam_addr + 1]; let tile_number = oam[oam_addr + 2]; let attributes = oam[oam_addr + 3]; let horizontal_flip = attributes.bit(5); let vertical_flip = attributes.bit(6); let low_priority = attributes.bit(7); // VRAM bank is only valid in CGB mode, and palette is read from different bits let (vram_bank, palette) = match (hardware_mode, cgb_dmg_compatibility) { (HardwareMode::Dmg, _) | (HardwareMode::Cgb, true) => (0, attributes.bit(4).into()), (HardwareMode::Cgb, false) => (attributes.bit(3).into(), attributes & 0x07), }; sprite_buffer.push(SpriteData { oam_index: oam_idx as u8, x, y, tile_number, vram_bank, palette, horizontal_flip, vertical_flip, low_priority, }); if sprite_buffer.len() == MAX_SPRITES_PER_LINE { break; } } sprite_buffer.sort_by(|a, b| a.x.cmp(&b.x).then(a.oam_index.cmp(&b.oam_index))); } const NINTENDO_LOGO_ADDR: Range<usize> = 0x0104..0x0134; const LOGO_TILE_DATA_ADDR: usize = 0x0010; const TRADEMARK_TILE_DATA_ADDR: usize = 0x0190; const TRADEMARK_SYMBOL: [u8; 16] = [ 0x3C, 0x00, 0x42, 0x00, 0xB9, 0x00, 0xA5, 0x00, 0xB9, 0x00, 0xA5, 0x00, 0x42, 0x00, 0x3C, 0x00, ]; // Initialize VRAM the way that the DMG boot ROM would. The Nintendo logo is copied out of the // cartridge header. // Some games depend on this by assuming that VRAM initially contains the Nintendo logo and a // trademark symbol, e.g. X for its intro animation fn initialize_vram(hardware_mode: HardwareMode, rom: &[u8], vram: &mut [u8]) { if hardware_mode != HardwareMode::Dmg { // Only write the logo to VRAM on DMG return; } if rom.len() < NINTENDO_LOGO_ADDR.end { // Invalid ROM; don't try to initialize VRAM return; } // Write logo to tile data area let logo = &rom[NINTENDO_LOGO_ADDR]; for (i, logo_byte) in logo.iter().copied().enumerate() { for nibble_idx in 0..2 { let nibble = logo_byte >> (4 * (1 - nibble_idx)); // Duplicate pixels horizontally let vram_byte = ((nibble & 8) << 4) | ((nibble & 8) << 3) | ((nibble & 4) << 3) | ((nibble & 4) << 2) | ((nibble & 2) << 2) | ((nibble & 2) << 1) | ((nibble & 1) << 1) | (nibble & 1); // Duplicate pixels vertically let vram_addr = LOGO_TILE_DATA_ADDR + 4 * (2 * i + nibble_idx); vram[vram_addr] = vram_byte; vram[vram_addr + 2] = vram_byte; } } // Write trademark to tile data area vram[TRADEMARK_TILE_DATA_ADDR..TRADEMARK_TILE_DATA_ADDR + TRADEMARK_SYMBOL.len()] .copy_from_slice(&TRADEMARK_SYMBOL); // Populate tile map // The upscaled logo is 12x2 tiles and should be centered, ranging from (X=4, Y=8) to (X=16, Y=10) for tile_row in 0..2 { for tile_col in 0..12 { let vram_addr = 0x1800 + (8 + tile_row) * 32 + (4 + tile_col); vram[vram_addr] = (1 + (12 * tile_row) + tile_col) as u8; } } // Trademark symbol should be in the top row just to the right of the logo, at (X=16, Y=8) vram[0x1800 + 8 * 32 + 16] = (TRADEMARK_TILE_DATA_ADDR / 16) as u8; }
0
0.888989
1
0.888989
game-dev
MEDIA
0.454063
game-dev,embedded-firmware
0.576352
1
0.576352
brunomikoski/Animation-Sequencer
13,565
Scripts/Runtime/Core/AnimationSequencerController.cs
#if DOTWEEN_ENABLED using System; using System.Collections; using System.Collections.Generic; #if UNITASK_ENABLED using System.Threading; using Cysharp.Threading.Tasks; #endif using DG.Tweening; using UnityEngine; using UnityEngine.Events; namespace BrunoMikoski.AnimationSequencer { [DisallowMultipleComponent] [AddComponentMenu("UI/Animation Sequencer Controller", 200)] public class AnimationSequencerController : MonoBehaviour { public enum PlayType { Forward, Backward } public enum AutoplayType { Awake, OnEnable, Nothing } [SerializeReference] private AnimationStepBase[] animationSteps = Array.Empty<AnimationStepBase>(); public AnimationStepBase[] AnimationSteps => animationSteps; [SerializeField] private UpdateType updateType = UpdateType.Normal; [SerializeField] private bool timeScaleIndependent = false; [SerializeField] private AutoplayType autoplayMode = AutoplayType.Awake; [SerializeField] protected bool startPaused; [SerializeField] private float playbackSpeed = 1f; public float PlaybackSpeed => playbackSpeed; [SerializeField] protected PlayType playType = PlayType.Forward; [SerializeField] private int loops = 0; [SerializeField] private LoopType loopType = LoopType.Restart; [SerializeField] private bool autoKill = true; [SerializeField] private UnityEvent onStartEvent = new UnityEvent(); public UnityEvent OnStartEvent { get => onStartEvent; protected set => onStartEvent = value; } [SerializeField] private UnityEvent onFinishedEvent = new UnityEvent(); public UnityEvent OnFinishedEvent { get => onFinishedEvent; protected set => onFinishedEvent = value; } [SerializeField] private UnityEvent onProgressEvent = new UnityEvent(); public UnityEvent OnProgressEvent => onProgressEvent; private Sequence playingSequence; public Sequence PlayingSequence => playingSequence; private PlayType playTypeInternal = PlayType.Forward; #if UNITY_EDITOR private bool requiresReset = false; #endif public bool IsPlaying => playingSequence != null && playingSequence.IsActive() && playingSequence.IsPlaying(); public bool IsPaused => playingSequence != null && playingSequence.IsActive() && !playingSequence.IsPlaying(); [SerializeField, Range(0, 1)] private float progress = -1; protected virtual void Awake() { progress = -1; if (autoplayMode != AutoplayType.Awake) return; Autoplay(); } protected virtual void OnEnable() { if (autoplayMode != AutoplayType.OnEnable) return; Autoplay(); } private void Autoplay() { Play(); if (startPaused) playingSequence.Pause(); } protected virtual void OnDisable() { if (autoplayMode != AutoplayType.OnEnable) return; if (playingSequence == null) return; ClearPlayingSequence(); // Reset the object to its initial state so that if it is re-enabled the start values are correct for // regenerating the Sequence. ResetToInitialState(); } protected virtual void OnDestroy() { ClearPlayingSequence(); } public virtual void Play() { Play(null); } public virtual void Play(Action onCompleteCallback) { playTypeInternal = playType; ClearPlayingSequence(); if (onCompleteCallback != null) onFinishedEvent.AddListener(onCompleteCallback.Invoke); playingSequence = GenerateSequence(); switch (playTypeInternal) { case PlayType.Backward: playingSequence.PlayBackwards(); break; case PlayType.Forward: playingSequence.PlayForward(); break; default: playingSequence.Play(); break; } } public virtual void PlayForward(bool resetFirst = true, Action onCompleteCallback = null) { if (playingSequence == null) Play(); playTypeInternal = PlayType.Forward; if (onCompleteCallback != null) onFinishedEvent.AddListener(onCompleteCallback.Invoke); if (resetFirst) SetProgress(0); playingSequence.PlayForward(); } public virtual void PlayBackwards(bool completeFirst = true, Action onCompleteCallback = null) { if (playingSequence == null) Play(); playTypeInternal = PlayType.Backward; if (onCompleteCallback != null) onFinishedEvent.AddListener(onCompleteCallback.Invoke); if (completeFirst) SetProgress(1); playingSequence.PlayBackwards(); } public virtual void SetTime(float seconds, bool andPlay = true) { if (playingSequence == null) Play(); playingSequence.Goto(seconds, andPlay); } public virtual void SetProgress(float targetProgress, bool andPlay = true) { if (playingSequence == null) Play(); targetProgress = Mathf.Clamp01(targetProgress); float duration = playingSequence.Duration(); float finalTime = targetProgress * duration; SetTime(finalTime, andPlay); } public virtual void TogglePause() { if (playingSequence == null) return; playingSequence.TogglePause(); } public virtual void Pause() { if (!IsPlaying) return; playingSequence.Pause(); } public virtual void Resume() { if (playingSequence == null) return; playingSequence.Play(); } public virtual void Complete(bool withCallbacks = true) { if (playingSequence == null) return; playingSequence.Complete(withCallbacks); } public virtual void Rewind(bool includeDelay = true) { if (playingSequence == null) return; playingSequence.Rewind(includeDelay); } public virtual void Kill(bool complete = false) { if (!IsPlaying) return; playingSequence.Kill(complete); } public virtual IEnumerator PlayEnumerator() { Play(); yield return playingSequence.WaitForCompletion(); } public virtual Sequence GenerateSequence() { Sequence sequence = DOTween.Sequence(); // Various edge cases exists with OnStart() and OnComplete(), some of which can be solved with OnRewind(), // but it still leaves callbacks unfired when reversing direction after natural completion of the animation. // Rather than using the in-built callbacks, we simply bookend the Sequence with AppendCallback to ensure // a Start and Finish callback is always fired. sequence.AppendCallback(() => { if (playTypeInternal == PlayType.Forward) { onStartEvent.Invoke(); } else { onFinishedEvent.Invoke(); } }); for (int i = 0; i < animationSteps.Length; i++) { AnimationStepBase animationStepBase = animationSteps[i]; animationStepBase.AddTweenToSequence(sequence); } sequence.SetTarget(this); sequence.SetAutoKill(autoKill); sequence.SetUpdate(updateType, timeScaleIndependent); sequence.OnUpdate(() => { onProgressEvent.Invoke(); }); // See comment above regarding bookending via AppendCallback. sequence.AppendCallback(() => { if (playTypeInternal == PlayType.Forward) { onFinishedEvent.Invoke(); } else { onStartEvent.Invoke(); } }); int targetLoops = loops; if (!Application.isPlaying) { if (loops == -1) { targetLoops = 10; Debug.LogWarning("Infinity sequences on editor can cause issues, using 10 loops while on editor."); } } sequence.SetLoops(targetLoops, loopType); sequence.timeScale = playbackSpeed; return sequence; } public virtual void ResetToInitialState() { progress = -1.0f; for (int i = animationSteps.Length - 1; i >= 0; i--) { animationSteps[i].ResetToInitialState(); } } public void ClearPlayingSequence() { DOTween.Kill(this); DOTween.Kill(playingSequence); playingSequence = null; } public void SetAutoplayMode(AutoplayType autoplayType) { autoplayMode = autoplayType; } public void SetPlayOnAwake(bool targetPlayOnAwake) { } public void SetPauseOnAwake(bool targetPauseOnAwake) { startPaused = targetPauseOnAwake; } public void SetTimeScaleIndependent(bool targetTimeScaleIndependent) { timeScaleIndependent = targetTimeScaleIndependent; } public void SetPlayType(PlayType targetPlayType) { playType = targetPlayType; } public void SetUpdateType(UpdateType targetUpdateType) { updateType = targetUpdateType; } public void SetAutoKill(bool targetAutoKill) { autoKill = targetAutoKill; } public void SetLoops(int targetLoops) { loops = targetLoops; } private void Update() { if (progress == -1.0f) return; SetProgress(progress); } #if UNITY_EDITOR // Unity Event Function called when component is added or reset. private void Reset() { requiresReset = true; } // Used by the CustomEditor so it knows when to reset to the defaults. public bool IsResetRequired() { return requiresReset; } // Called by the CustomEditor once the reset has been completed public void ResetComplete() { requiresReset = false; } #endif public bool TryGetStepAtIndex<T>(int index, out T result) where T : AnimationStepBase { if (index < 0 || index > animationSteps.Length - 1) { result = null; return false; } result = animationSteps[index] as T; return result != null; } public void ReplaceTarget<T>(GameObject targetGameObject) where T : GameObjectAnimationStep { for (int i = animationSteps.Length - 1; i >= 0; i--) { AnimationStepBase animationStepBase = animationSteps[i]; if (animationStepBase == null) continue; if (animationStepBase is not T gameObjectAnimationStep) continue; gameObjectAnimationStep.SetTarget(targetGameObject); } } public void ReplaceTargets(params (GameObject original, GameObject target)[] replacements) { for (int i = 0; i < replacements.Length; i++) { (GameObject original, GameObject target) replacement = replacements[i]; ReplaceTargets(replacement.original, replacement.target); } } public void ReplaceTargets(GameObject originalTarget, GameObject newTarget) { for (int i = animationSteps.Length - 1; i >= 0; i--) { AnimationStepBase animationStepBase = animationSteps[i]; if (animationStepBase == null) continue; if(animationStepBase is not GameObjectAnimationStep gameObjectAnimationStep) continue; if (gameObjectAnimationStep.Target == originalTarget) gameObjectAnimationStep.SetTarget(newTarget); } } #if UNITASK_ENABLED public async UniTask PlayAsync() { await PlayEnumerator().ToUniTask(this); } #endif } } #endif
0
0.86758
1
0.86758
game-dev
MEDIA
0.813498
game-dev
0.943491
1
0.943491
chstetco/virtualradar
19,520
Library/PackageCache/com.unity.timeline@1.2.15/Editor/Recording/TimelineRecording.cs
using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Timeline; using UnityEngine.Playables; namespace UnityEditor.Timeline { // Handles Undo animated properties on Monobehaviours to create track clips static partial class TimelineRecording { static readonly List<PropertyModification> s_TempPropertyModifications = new List<PropertyModification>(6); internal static UndoPropertyModification[] ProcessUndoModification(UndoPropertyModification[] modifications, WindowState state) { if (HasAnyPlayableAssetModifications(modifications)) return ProcessPlayableAssetModification(modifications, state); return ProcessMonoBehaviourModification(modifications, state); } static UnityEngine.Object GetTarget(UndoPropertyModification undo) { if (undo.currentValue != null) return undo.currentValue.target; if (undo.previousValue != null) return undo.previousValue.target; return null; } // Gets the appropriate track for a given game object static TrackAsset GetTrackForGameObject(GameObject gameObject, WindowState state) { if (gameObject == null) return null; var director = state.editSequence.director; if (director == null) return null; var level = int.MaxValue; TrackAsset result = null; // search the output tracks var outputTracks = state.editSequence.asset.flattenedTracks; foreach (var track in outputTracks) { if (track.GetType() != typeof(AnimationTrack)) continue; if (!state.IsTrackRecordable(track)) continue; var obj = TimelineUtility.GetSceneGameObject(director, track); if (obj != null) { // checks if the effected gameobject is our child var childLevel = GetChildLevel(obj, gameObject); if (childLevel != -1 && childLevel < level) { result = track; level = childLevel; } } } // the resulting track is not armed. checking here avoids accidentally recording objects with their own // tracks if (result && !state.IsTrackRecordable(result)) { result = null; } return result; } // Gets the track this property would record to. // Returns null if there is a track, but it's not currently active for recording public static TrackAsset GetRecordingTrack(SerializedProperty property, WindowState state) { var serializedObject = property.serializedObject; var component = serializedObject.targetObject as Component; if (component == null) return null; var gameObject = component.gameObject; return GetTrackForGameObject(gameObject, state); } // Given a serialized property, gathers all animatable properties static void GatherModifications(SerializedProperty property, List<PropertyModification> modifications) { // handles child properties (Vector3 is 3 recordable properties) if (property.hasChildren) { var iter = property.Copy(); var end = property.GetEndProperty(false); // recurse over all children properties while (iter.Next(true) && !SerializedProperty.EqualContents(iter, end)) { GatherModifications(iter, modifications); } } var isObject = property.propertyType == SerializedPropertyType.ObjectReference; var isFloat = property.propertyType == SerializedPropertyType.Float || property.propertyType == SerializedPropertyType.Boolean || property.propertyType == SerializedPropertyType.Integer; if (isObject || isFloat) { var serializedObject = property.serializedObject; var modification = new PropertyModification(); modification.target = serializedObject.targetObject; modification.propertyPath = property.propertyPath; if (isObject) { modification.value = string.Empty; modification.objectReference = property.objectReferenceValue; } else { modification.value = TimelineUtility.PropertyToString(property); } // Path for monobehaviour based - better to grab the component to get the curvebinding to allow validation if (serializedObject.targetObject is Component) { EditorCurveBinding temp; var go = ((Component)serializedObject.targetObject).gameObject; if (AnimationUtility.PropertyModificationToEditorCurveBinding(modification, go, out temp) != null) { modifications.Add(modification); } } else { modifications.Add(modification); } } } public static bool CanRecord(SerializedProperty property, WindowState state) { if (IsPlayableAssetProperty(property)) return AnimatedParameterUtility.IsTypeAnimatable(property.propertyType); if (GetRecordingTrack(property, state) == null) return false; s_TempPropertyModifications.Clear(); GatherModifications(property, s_TempPropertyModifications); return s_TempPropertyModifications.Any(); } public static void AddKey(SerializedProperty prop, WindowState state) { s_TempPropertyModifications.Clear(); GatherModifications(prop, s_TempPropertyModifications); if (s_TempPropertyModifications.Any()) { AddKey(s_TempPropertyModifications, state); } } public static void AddKey(IEnumerable<PropertyModification> modifications, WindowState state) { var undos = modifications.Select(PropertyModificationToUndoPropertyModification).ToArray(); ProcessUndoModification(undos, state); } static UndoPropertyModification PropertyModificationToUndoPropertyModification(PropertyModification prop) { return new UndoPropertyModification { previousValue = prop, currentValue = new PropertyModification { objectReference = prop.objectReference, propertyPath = prop.propertyPath, target = prop.target, value = prop.value }, keepPrefabOverride = true }; } // Given an animation track, return the clip that we are currently recording to static AnimationClip GetRecordingClip(TrackAsset asset, WindowState state, out double startTime, out double timeScale) { startTime = 0; timeScale = 1; TimelineClip displayBackground = null; asset.FindRecordingClipAtTime(state.editSequence.time, out displayBackground); var animClip = asset.FindRecordingAnimationClipAtTime(state.editSequence.time); if (displayBackground != null) { startTime = displayBackground.start; timeScale = displayBackground.timeScale; } return animClip; } // Helper that finds the animation clip we are recording and the relative time to that clip static bool GetClipAndRelativeTime(UnityEngine.Object target, WindowState state, out AnimationClip outClip, out double keyTime, out bool keyInRange) { const float floatToDoubleError = 0.00001f; outClip = null; keyTime = 0; keyInRange = false; double startTime = 0; double timeScale = 1; AnimationClip clip = null; IPlayableAsset playableAsset = target as IPlayableAsset; Component component = target as Component; // Handle recordable playable assets if (playableAsset != null) { var curvesOwner = AnimatedParameterUtility.ToCurvesOwner(playableAsset, state.editSequence.asset); if (curvesOwner != null && state.IsTrackRecordable(curvesOwner.targetTrack)) { if (curvesOwner.curves == null) curvesOwner.CreateCurves(curvesOwner.GetUniqueRecordedClipName()); clip = curvesOwner.curves; var timelineClip = curvesOwner as TimelineClip; if (timelineClip != null) { startTime = timelineClip.start; timeScale = timelineClip.timeScale; } } } // Handle recording components, including infinite clip else if (component != null) { var asset = GetTrackForGameObject(component.gameObject, state); if (asset != null) { clip = GetRecordingClip(asset, state, out startTime, out timeScale); } } if (clip == null) return false; keyTime = (state.editSequence.time - startTime) * timeScale; outClip = clip; keyInRange = keyTime >= 0 && keyTime <= (clip.length * timeScale + floatToDoubleError); return true; } public static bool HasCurve(IEnumerable<PropertyModification> modifications, UnityEngine.Object target, WindowState state) { return GetKeyTimes(target, modifications, state).Any(); } public static bool HasKey(IEnumerable<PropertyModification> modifications, UnityEngine.Object target, WindowState state) { AnimationClip clip; double keyTime; bool inRange; if (!GetClipAndRelativeTime(target, state, out clip, out keyTime, out inRange)) return false; return GetKeyTimes(target, modifications, state).Any(t => (CurveEditUtility.KeyCompare((float)state.editSequence.time, (float)t, clip.frameRate) == 0)); } // Checks if a key already exists for this property static bool HasBinding(UnityEngine.Object target, PropertyModification modification, AnimationClip clip, out EditorCurveBinding binding) { var component = target as Component; var playableAsset = target as IPlayableAsset; if (component != null) { var type = AnimationUtility.PropertyModificationToEditorCurveBinding(modification, component.gameObject, out binding); binding = RotationCurveInterpolation.RemapAnimationBindingForRotationCurves(binding, clip); return type != null; } if (playableAsset != null) { binding = EditorCurveBinding.FloatCurve(string.Empty, target.GetType(), AnimatedParameterUtility.GetAnimatedParameterBindingName(target, modification.propertyPath)); } else { binding = new EditorCurveBinding(); return false; } return true; } public static void RemoveKey(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { AnimationClip clip; double keyTime; bool inRange; if (!GetClipAndRelativeTime(target, state, out clip, out keyTime, out inRange) || !inRange) return; var refreshPreview = false; TimelineUndo.PushUndo(clip, "Remove Key"); foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, clip, out temp)) { if (temp.isPPtrCurve) { CurveEditUtility.RemoveObjectKey(clip, temp, keyTime); if (CurveEditUtility.GetObjectKeyCount(clip, temp) == 0) { refreshPreview = true; } } else { AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, temp); if (curve != null) { CurveEditUtility.RemoveKeyFrameFromCurve(curve, (float)keyTime, clip.frameRate); AnimationUtility.SetEditorCurve(clip, temp, curve); if (curve.length == 0) { AnimationUtility.SetEditorCurve(clip, temp, null); refreshPreview = true; } } } } } if (refreshPreview) { state.ResetPreviewMode(); } } static HashSet<double> GetKeyTimes(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { var keyTimes = new HashSet<double>(); AnimationClip animationClip; double keyTime; bool inRange; GetClipAndRelativeTime(target, state, out animationClip, out keyTime, out inRange); if (animationClip == null) return keyTimes; var component = target as Component; var playableAsset = target as IPlayableAsset; var info = AnimationClipCurveCache.Instance.GetCurveInfo(animationClip); TimelineClip clip = null; if (component != null) { GetTrackForGameObject(component.gameObject, state).FindRecordingClipAtTime(state.editSequence.time, out clip); } else if (playableAsset != null) { clip = FindClipWithAsset(state.editSequence.asset, playableAsset); } foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, animationClip, out temp)) { IEnumerable<double> keys = new HashSet<double>(); if (temp.isPPtrCurve) { var curve = info.GetObjectCurveForBinding(temp); if (curve != null) { keys = curve.Select(x => (double)x.time); } } else { var curve = info.GetCurveForBinding(temp); if (curve != null) { keys = curve.keys.Select(x => (double)x.time); } } // Transform the times in to 'global' space using the clip if (clip != null) { foreach (var k in keys) { var time = clip.FromLocalTimeUnbound(k); const double eps = 1e-5; if (time >= clip.start - eps && time <= clip.end + eps) { keyTimes.Add(time); } } } // infinite clip mode, global == local space else { keyTimes.UnionWith(keys); } } } return keyTimes; } public static void NextKey(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { const double eps = 1e-5; var keyTimes = GetKeyTimes(target, modifications, state); if (keyTimes.Count == 0) return; var nextKeys = keyTimes.Where(x => x > state.editSequence.time + eps); if (nextKeys.Any()) { state.editSequence.time = nextKeys.Min(); } } public static void PrevKey(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { const double eps = 1e-5; var keyTimes = GetKeyTimes(target, modifications, state); if (keyTimes.Count == 0) return; var prevKeys = keyTimes.Where(x => x < state.editSequence.time - eps); if (prevKeys.Any()) { state.editSequence.time = prevKeys.Max(); } } public static void RemoveCurve(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { AnimationClip clip = null; double keyTime = 0; var inRange = false; // not used for curves if (!GetClipAndRelativeTime(target, state, out clip, out keyTime, out inRange)) return; TimelineUndo.PushUndo(clip, "Remove Curve"); foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, clip, out temp)) { if (temp.isPPtrCurve) AnimationUtility.SetObjectReferenceCurve(clip, temp, null); else AnimationUtility.SetEditorCurve(clip, temp, null); } } state.ResetPreviewMode(); } public static IEnumerable<GameObject> GetRecordableGameObjects(WindowState state) { if (state == null || state.editSequence.asset == null || state.editSequence.director == null) yield break; var outputTracks = state.editSequence.asset.GetOutputTracks(); foreach (var track in outputTracks) { if (track.GetType() != typeof(AnimationTrack)) continue; if (!state.IsTrackRecordable(track) && !track.GetChildTracks().Any(state.IsTrackRecordable)) continue; var obj = TimelineUtility.GetSceneGameObject(state.editSequence.director, track); if (obj != null) { yield return obj; } } } } }
0
0.897027
1
0.897027
game-dev
MEDIA
0.98305
game-dev
0.876193
1
0.876193
Syomus/ProceduralToolkit
1,203
Runtime/Visitors/Visitor4.cs
using UnityEngine; namespace ProceduralToolkit { /// <summary> /// Visits four cells orthogonally surrounding the center cell /// </summary> /// <remarks> /// https://en.wikipedia.org/wiki/Von_Neumann_neighborhood /// </remarks> public struct Visitor4<TVisitAction> where TVisitAction : struct, IVisitAction { public TVisitAction action; public int lengthX; public int lengthY; public Visitor4(int lengthX, int lengthY, TVisitAction action) { this.lengthX = lengthX; this.lengthY = lengthY; this.action = action; } public void Visit4(Vector2Int center) { Visit4(center.x, center.y); } public void Visit4(int x, int y) { if (x > 0) { action.Visit(x - 1, y); } if (x + 1 < lengthX) { action.Visit(x + 1, y); } if (y > 0) { action.Visit(x, y - 1); } if (y + 1 < lengthY) { action.Visit(x, y + 1); } } } }
0
0.783825
1
0.783825
game-dev
MEDIA
0.315752
game-dev
0.809782
1
0.809782
mono/opentk
160,013
Source/Compatibility/Tao/OpenGl/GLCore.cs
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // 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. // #endregion namespace Tao.OpenGl { using System; using System.Runtime.InteropServices; #pragma warning disable 3019 #pragma warning disable 1591 partial class Gl { internal static partial class Imports { [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNewList", ExactSpelling = true)] internal extern static void NewList(UInt32 list, int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEndList", ExactSpelling = true)] internal extern static void EndList(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCallList", ExactSpelling = true)] internal extern static void CallList(UInt32 list); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCallLists", ExactSpelling = true)] internal extern static void CallLists(Int32 n, int type, IntPtr lists); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteLists", ExactSpelling = true)] internal extern static void DeleteLists(UInt32 list, Int32 range); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGenLists", ExactSpelling = true)] internal extern static Int32 GenLists(Int32 range); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glListBase", ExactSpelling = true)] internal extern static void ListBase(UInt32 @base); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBegin", ExactSpelling = true)] internal extern static void Begin(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBitmap", ExactSpelling = true)] internal extern static unsafe void Bitmap(Int32 width, Int32 height, Single xorig, Single yorig, Single xmove, Single ymove, Byte* bitmap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3b", ExactSpelling = true)] internal extern static void Color3b(SByte red, SByte green, SByte blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3bv", ExactSpelling = true)] internal extern static unsafe void Color3bv(SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3d", ExactSpelling = true)] internal extern static void Color3d(Double red, Double green, Double blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3dv", ExactSpelling = true)] internal extern static unsafe void Color3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3f", ExactSpelling = true)] internal extern static void Color3f(Single red, Single green, Single blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3fv", ExactSpelling = true)] internal extern static unsafe void Color3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3i", ExactSpelling = true)] internal extern static void Color3i(Int32 red, Int32 green, Int32 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3iv", ExactSpelling = true)] internal extern static unsafe void Color3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3s", ExactSpelling = true)] internal extern static void Color3s(Int16 red, Int16 green, Int16 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3sv", ExactSpelling = true)] internal extern static unsafe void Color3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3ub", ExactSpelling = true)] internal extern static void Color3ub(Byte red, Byte green, Byte blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3ubv", ExactSpelling = true)] internal extern static unsafe void Color3ubv(Byte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3ui", ExactSpelling = true)] internal extern static void Color3ui(UInt32 red, UInt32 green, UInt32 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3uiv", ExactSpelling = true)] internal extern static unsafe void Color3uiv(UInt32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3us", ExactSpelling = true)] internal extern static void Color3us(UInt16 red, UInt16 green, UInt16 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor3usv", ExactSpelling = true)] internal extern static unsafe void Color3usv(UInt16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4b", ExactSpelling = true)] internal extern static void Color4b(SByte red, SByte green, SByte blue, SByte alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4bv", ExactSpelling = true)] internal extern static unsafe void Color4bv(SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4d", ExactSpelling = true)] internal extern static void Color4d(Double red, Double green, Double blue, Double alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4dv", ExactSpelling = true)] internal extern static unsafe void Color4dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4f", ExactSpelling = true)] internal extern static void Color4f(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4fv", ExactSpelling = true)] internal extern static unsafe void Color4fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4i", ExactSpelling = true)] internal extern static void Color4i(Int32 red, Int32 green, Int32 blue, Int32 alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4iv", ExactSpelling = true)] internal extern static unsafe void Color4iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4s", ExactSpelling = true)] internal extern static void Color4s(Int16 red, Int16 green, Int16 blue, Int16 alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4sv", ExactSpelling = true)] internal extern static unsafe void Color4sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4ub", ExactSpelling = true)] internal extern static void Color4ub(Byte red, Byte green, Byte blue, Byte alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4ubv", ExactSpelling = true)] internal extern static unsafe void Color4ubv(Byte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4ui", ExactSpelling = true)] internal extern static void Color4ui(UInt32 red, UInt32 green, UInt32 blue, UInt32 alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4uiv", ExactSpelling = true)] internal extern static unsafe void Color4uiv(UInt32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4us", ExactSpelling = true)] internal extern static void Color4us(UInt16 red, UInt16 green, UInt16 blue, UInt16 alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColor4usv", ExactSpelling = true)] internal extern static unsafe void Color4usv(UInt16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEdgeFlag", ExactSpelling = true)] internal extern static void EdgeFlag(Int32 flag); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEdgeFlagv", ExactSpelling = true)] internal extern static unsafe void EdgeFlagv(Int32* flag); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEnd", ExactSpelling = true)] internal extern static void End(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexd", ExactSpelling = true)] internal extern static void Indexd(Double c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexdv", ExactSpelling = true)] internal extern static unsafe void Indexdv(Double* c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexf", ExactSpelling = true)] internal extern static void Indexf(Single c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexfv", ExactSpelling = true)] internal extern static unsafe void Indexfv(Single* c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexi", ExactSpelling = true)] internal extern static void Indexi(Int32 c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexiv", ExactSpelling = true)] internal extern static unsafe void Indexiv(Int32* c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexs", ExactSpelling = true)] internal extern static void Indexs(Int16 c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexsv", ExactSpelling = true)] internal extern static unsafe void Indexsv(Int16* c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3b", ExactSpelling = true)] internal extern static void Normal3b(SByte nx, SByte ny, SByte nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3bv", ExactSpelling = true)] internal extern static unsafe void Normal3bv(SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3d", ExactSpelling = true)] internal extern static void Normal3d(Double nx, Double ny, Double nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3dv", ExactSpelling = true)] internal extern static unsafe void Normal3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3f", ExactSpelling = true)] internal extern static void Normal3f(Single nx, Single ny, Single nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3fv", ExactSpelling = true)] internal extern static unsafe void Normal3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3i", ExactSpelling = true)] internal extern static void Normal3i(Int32 nx, Int32 ny, Int32 nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3iv", ExactSpelling = true)] internal extern static unsafe void Normal3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3s", ExactSpelling = true)] internal extern static void Normal3s(Int16 nx, Int16 ny, Int16 nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormal3sv", ExactSpelling = true)] internal extern static unsafe void Normal3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2d", ExactSpelling = true)] internal extern static void RasterPos2d(Double x, Double y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2dv", ExactSpelling = true)] internal extern static unsafe void RasterPos2dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2f", ExactSpelling = true)] internal extern static void RasterPos2f(Single x, Single y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2fv", ExactSpelling = true)] internal extern static unsafe void RasterPos2fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2i", ExactSpelling = true)] internal extern static void RasterPos2i(Int32 x, Int32 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2iv", ExactSpelling = true)] internal extern static unsafe void RasterPos2iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2s", ExactSpelling = true)] internal extern static void RasterPos2s(Int16 x, Int16 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos2sv", ExactSpelling = true)] internal extern static unsafe void RasterPos2sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3d", ExactSpelling = true)] internal extern static void RasterPos3d(Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3dv", ExactSpelling = true)] internal extern static unsafe void RasterPos3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3f", ExactSpelling = true)] internal extern static void RasterPos3f(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3fv", ExactSpelling = true)] internal extern static unsafe void RasterPos3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3i", ExactSpelling = true)] internal extern static void RasterPos3i(Int32 x, Int32 y, Int32 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3iv", ExactSpelling = true)] internal extern static unsafe void RasterPos3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3s", ExactSpelling = true)] internal extern static void RasterPos3s(Int16 x, Int16 y, Int16 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos3sv", ExactSpelling = true)] internal extern static unsafe void RasterPos3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4d", ExactSpelling = true)] internal extern static void RasterPos4d(Double x, Double y, Double z, Double w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4dv", ExactSpelling = true)] internal extern static unsafe void RasterPos4dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4f", ExactSpelling = true)] internal extern static void RasterPos4f(Single x, Single y, Single z, Single w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4fv", ExactSpelling = true)] internal extern static unsafe void RasterPos4fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4i", ExactSpelling = true)] internal extern static void RasterPos4i(Int32 x, Int32 y, Int32 z, Int32 w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4iv", ExactSpelling = true)] internal extern static unsafe void RasterPos4iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4s", ExactSpelling = true)] internal extern static void RasterPos4s(Int16 x, Int16 y, Int16 z, Int16 w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRasterPos4sv", ExactSpelling = true)] internal extern static unsafe void RasterPos4sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectd", ExactSpelling = true)] internal extern static void Rectd(Double x1, Double y1, Double x2, Double y2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectdv", ExactSpelling = true)] internal extern static unsafe void Rectdv(Double* v1, Double* v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectf", ExactSpelling = true)] internal extern static void Rectf(Single x1, Single y1, Single x2, Single y2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectfv", ExactSpelling = true)] internal extern static unsafe void Rectfv(Single* v1, Single* v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRecti", ExactSpelling = true)] internal extern static void Recti(Int32 x1, Int32 y1, Int32 x2, Int32 y2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectiv", ExactSpelling = true)] internal extern static unsafe void Rectiv(Int32* v1, Int32* v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRects", ExactSpelling = true)] internal extern static void Rects(Int16 x1, Int16 y1, Int16 x2, Int16 y2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRectsv", ExactSpelling = true)] internal extern static unsafe void Rectsv(Int16* v1, Int16* v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1d", ExactSpelling = true)] internal extern static void TexCoord1d(Double s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1dv", ExactSpelling = true)] internal extern static unsafe void TexCoord1dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1f", ExactSpelling = true)] internal extern static void TexCoord1f(Single s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1fv", ExactSpelling = true)] internal extern static unsafe void TexCoord1fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1i", ExactSpelling = true)] internal extern static void TexCoord1i(Int32 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1iv", ExactSpelling = true)] internal extern static unsafe void TexCoord1iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1s", ExactSpelling = true)] internal extern static void TexCoord1s(Int16 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord1sv", ExactSpelling = true)] internal extern static unsafe void TexCoord1sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2d", ExactSpelling = true)] internal extern static void TexCoord2d(Double s, Double t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2dv", ExactSpelling = true)] internal extern static unsafe void TexCoord2dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2f", ExactSpelling = true)] internal extern static void TexCoord2f(Single s, Single t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2fv", ExactSpelling = true)] internal extern static unsafe void TexCoord2fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2i", ExactSpelling = true)] internal extern static void TexCoord2i(Int32 s, Int32 t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2iv", ExactSpelling = true)] internal extern static unsafe void TexCoord2iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2s", ExactSpelling = true)] internal extern static void TexCoord2s(Int16 s, Int16 t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord2sv", ExactSpelling = true)] internal extern static unsafe void TexCoord2sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3d", ExactSpelling = true)] internal extern static void TexCoord3d(Double s, Double t, Double r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3dv", ExactSpelling = true)] internal extern static unsafe void TexCoord3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3f", ExactSpelling = true)] internal extern static void TexCoord3f(Single s, Single t, Single r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3fv", ExactSpelling = true)] internal extern static unsafe void TexCoord3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3i", ExactSpelling = true)] internal extern static void TexCoord3i(Int32 s, Int32 t, Int32 r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3iv", ExactSpelling = true)] internal extern static unsafe void TexCoord3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3s", ExactSpelling = true)] internal extern static void TexCoord3s(Int16 s, Int16 t, Int16 r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord3sv", ExactSpelling = true)] internal extern static unsafe void TexCoord3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4d", ExactSpelling = true)] internal extern static void TexCoord4d(Double s, Double t, Double r, Double q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4dv", ExactSpelling = true)] internal extern static unsafe void TexCoord4dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4f", ExactSpelling = true)] internal extern static void TexCoord4f(Single s, Single t, Single r, Single q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4fv", ExactSpelling = true)] internal extern static unsafe void TexCoord4fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4i", ExactSpelling = true)] internal extern static void TexCoord4i(Int32 s, Int32 t, Int32 r, Int32 q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4iv", ExactSpelling = true)] internal extern static unsafe void TexCoord4iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4s", ExactSpelling = true)] internal extern static void TexCoord4s(Int16 s, Int16 t, Int16 r, Int16 q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoord4sv", ExactSpelling = true)] internal extern static unsafe void TexCoord4sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2d", ExactSpelling = true)] internal extern static void Vertex2d(Double x, Double y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2dv", ExactSpelling = true)] internal extern static unsafe void Vertex2dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2f", ExactSpelling = true)] internal extern static void Vertex2f(Single x, Single y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2fv", ExactSpelling = true)] internal extern static unsafe void Vertex2fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2i", ExactSpelling = true)] internal extern static void Vertex2i(Int32 x, Int32 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2iv", ExactSpelling = true)] internal extern static unsafe void Vertex2iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2s", ExactSpelling = true)] internal extern static void Vertex2s(Int16 x, Int16 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex2sv", ExactSpelling = true)] internal extern static unsafe void Vertex2sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3d", ExactSpelling = true)] internal extern static void Vertex3d(Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3dv", ExactSpelling = true)] internal extern static unsafe void Vertex3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3f", ExactSpelling = true)] internal extern static void Vertex3f(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3fv", ExactSpelling = true)] internal extern static unsafe void Vertex3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3i", ExactSpelling = true)] internal extern static void Vertex3i(Int32 x, Int32 y, Int32 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3iv", ExactSpelling = true)] internal extern static unsafe void Vertex3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3s", ExactSpelling = true)] internal extern static void Vertex3s(Int16 x, Int16 y, Int16 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex3sv", ExactSpelling = true)] internal extern static unsafe void Vertex3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4d", ExactSpelling = true)] internal extern static void Vertex4d(Double x, Double y, Double z, Double w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4dv", ExactSpelling = true)] internal extern static unsafe void Vertex4dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4f", ExactSpelling = true)] internal extern static void Vertex4f(Single x, Single y, Single z, Single w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4fv", ExactSpelling = true)] internal extern static unsafe void Vertex4fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4i", ExactSpelling = true)] internal extern static void Vertex4i(Int32 x, Int32 y, Int32 z, Int32 w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4iv", ExactSpelling = true)] internal extern static unsafe void Vertex4iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4s", ExactSpelling = true)] internal extern static void Vertex4s(Int16 x, Int16 y, Int16 z, Int16 w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertex4sv", ExactSpelling = true)] internal extern static unsafe void Vertex4sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClipPlane", ExactSpelling = true)] internal extern static unsafe void ClipPlane(int plane, Double* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorMaterial", ExactSpelling = true)] internal extern static void ColorMaterial(int face, int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCullFace", ExactSpelling = true)] internal extern static void CullFace(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogf", ExactSpelling = true)] internal extern static void Fogf(int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogfv", ExactSpelling = true)] internal extern static unsafe void Fogfv(int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogi", ExactSpelling = true)] internal extern static void Fogi(int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogiv", ExactSpelling = true)] internal extern static unsafe void Fogiv(int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFrontFace", ExactSpelling = true)] internal extern static void FrontFace(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glHint", ExactSpelling = true)] internal extern static void Hint(int target, int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightf", ExactSpelling = true)] internal extern static void Lightf(int light, int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightfv", ExactSpelling = true)] internal extern static unsafe void Lightfv(int light, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLighti", ExactSpelling = true)] internal extern static void Lighti(int light, int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightiv", ExactSpelling = true)] internal extern static unsafe void Lightiv(int light, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightModelf", ExactSpelling = true)] internal extern static void LightModelf(int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightModelfv", ExactSpelling = true)] internal extern static unsafe void LightModelfv(int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightModeli", ExactSpelling = true)] internal extern static void LightModeli(int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLightModeliv", ExactSpelling = true)] internal extern static unsafe void LightModeliv(int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLineStipple", ExactSpelling = true)] internal extern static void LineStipple(Int32 factor, UInt16 pattern); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLineWidth", ExactSpelling = true)] internal extern static void LineWidth(Single width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMaterialf", ExactSpelling = true)] internal extern static void Materialf(int face, int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMaterialfv", ExactSpelling = true)] internal extern static unsafe void Materialfv(int face, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMateriali", ExactSpelling = true)] internal extern static void Materiali(int face, int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMaterialiv", ExactSpelling = true)] internal extern static unsafe void Materialiv(int face, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPointSize", ExactSpelling = true)] internal extern static void PointSize(Single size); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPolygonMode", ExactSpelling = true)] internal extern static void PolygonMode(int face, int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPolygonStipple", ExactSpelling = true)] internal extern static unsafe void PolygonStipple(Byte* mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glScissor", ExactSpelling = true)] internal extern static void Scissor(Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glShadeModel", ExactSpelling = true)] internal extern static void ShadeModel(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexParameterf", ExactSpelling = true)] internal extern static void TexParameterf(int target, int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexParameterfv", ExactSpelling = true)] internal extern static unsafe void TexParameterfv(int target, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexParameteri", ExactSpelling = true)] internal extern static void TexParameteri(int target, int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexParameteriv", ExactSpelling = true)] internal extern static unsafe void TexParameteriv(int target, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexImage1D", ExactSpelling = true)] internal extern static void TexImage1D(int target, Int32 level, int internalformat, Int32 width, Int32 border, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexImage2D", ExactSpelling = true)] internal extern static void TexImage2D(int target, Int32 level, int internalformat, Int32 width, Int32 height, Int32 border, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexEnvf", ExactSpelling = true)] internal extern static void TexEnvf(int target, int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexEnvfv", ExactSpelling = true)] internal extern static unsafe void TexEnvfv(int target, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexEnvi", ExactSpelling = true)] internal extern static void TexEnvi(int target, int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexEnviv", ExactSpelling = true)] internal extern static unsafe void TexEnviv(int target, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGend", ExactSpelling = true)] internal extern static void TexGend(int coord, int pname, Double param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGendv", ExactSpelling = true)] internal extern static unsafe void TexGendv(int coord, int pname, Double* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGenf", ExactSpelling = true)] internal extern static void TexGenf(int coord, int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGenfv", ExactSpelling = true)] internal extern static unsafe void TexGenfv(int coord, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGeni", ExactSpelling = true)] internal extern static void TexGeni(int coord, int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexGeniv", ExactSpelling = true)] internal extern static unsafe void TexGeniv(int coord, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFeedbackBuffer", ExactSpelling = true)] internal extern static unsafe void FeedbackBuffer(Int32 size, int type, [Out] Single* buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSelectBuffer", ExactSpelling = true)] internal extern static unsafe void SelectBuffer(Int32 size, [Out] UInt32* buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRenderMode", ExactSpelling = true)] internal extern static Int32 RenderMode(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glInitNames", ExactSpelling = true)] internal extern static void InitNames(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadName", ExactSpelling = true)] internal extern static void LoadName(UInt32 name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPassThrough", ExactSpelling = true)] internal extern static void PassThrough(Single token); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPopName", ExactSpelling = true)] internal extern static void PopName(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPushName", ExactSpelling = true)] internal extern static void PushName(UInt32 name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawBuffer", ExactSpelling = true)] internal extern static void DrawBuffer(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClear", ExactSpelling = true)] internal extern static void Clear(int mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClearAccum", ExactSpelling = true)] internal extern static void ClearAccum(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClearIndex", ExactSpelling = true)] internal extern static void ClearIndex(Single c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClearColor", ExactSpelling = true)] internal extern static void ClearColor(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClearStencil", ExactSpelling = true)] internal extern static void ClearStencil(Int32 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClearDepth", ExactSpelling = true)] internal extern static void ClearDepth(Double depth); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilMask", ExactSpelling = true)] internal extern static void StencilMask(UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorMask", ExactSpelling = true)] internal extern static void ColorMask(Int32 red, Int32 green, Int32 blue, Int32 alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDepthMask", ExactSpelling = true)] internal extern static void DepthMask(Int32 flag); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexMask", ExactSpelling = true)] internal extern static void IndexMask(UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glAccum", ExactSpelling = true)] internal extern static void Accum(int op, Single value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDisable", ExactSpelling = true)] internal extern static void Disable(int cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEnable", ExactSpelling = true)] internal extern static void Enable(int cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFinish", ExactSpelling = true)] internal extern static void Finish(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFlush", ExactSpelling = true)] internal extern static void Flush(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPopAttrib", ExactSpelling = true)] internal extern static void PopAttrib(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPushAttrib", ExactSpelling = true)] internal extern static void PushAttrib(int mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMap1d", ExactSpelling = true)] internal extern static unsafe void Map1d(int target, Double u1, Double u2, Int32 stride, Int32 order, Double* points); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMap1f", ExactSpelling = true)] internal extern static unsafe void Map1f(int target, Single u1, Single u2, Int32 stride, Int32 order, Single* points); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMap2d", ExactSpelling = true)] internal extern static unsafe void Map2d(int target, Double u1, Double u2, Int32 ustride, Int32 uorder, Double v1, Double v2, Int32 vstride, Int32 vorder, Double* points); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMap2f", ExactSpelling = true)] internal extern static unsafe void Map2f(int target, Single u1, Single u2, Int32 ustride, Int32 uorder, Single v1, Single v2, Int32 vstride, Int32 vorder, Single* points); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMapGrid1d", ExactSpelling = true)] internal extern static void MapGrid1d(Int32 un, Double u1, Double u2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMapGrid1f", ExactSpelling = true)] internal extern static void MapGrid1f(Int32 un, Single u1, Single u2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMapGrid2d", ExactSpelling = true)] internal extern static void MapGrid2d(Int32 un, Double u1, Double u2, Int32 vn, Double v1, Double v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMapGrid2f", ExactSpelling = true)] internal extern static void MapGrid2f(Int32 un, Single u1, Single u2, Int32 vn, Single v1, Single v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord1d", ExactSpelling = true)] internal extern static void EvalCoord1d(Double u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord1dv", ExactSpelling = true)] internal extern static unsafe void EvalCoord1dv(Double* u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord1f", ExactSpelling = true)] internal extern static void EvalCoord1f(Single u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord1fv", ExactSpelling = true)] internal extern static unsafe void EvalCoord1fv(Single* u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord2d", ExactSpelling = true)] internal extern static void EvalCoord2d(Double u, Double v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord2dv", ExactSpelling = true)] internal extern static unsafe void EvalCoord2dv(Double* u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord2f", ExactSpelling = true)] internal extern static void EvalCoord2f(Single u, Single v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalCoord2fv", ExactSpelling = true)] internal extern static unsafe void EvalCoord2fv(Single* u); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalMesh1", ExactSpelling = true)] internal extern static void EvalMesh1(int mode, Int32 i1, Int32 i2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalPoint1", ExactSpelling = true)] internal extern static void EvalPoint1(Int32 i); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalMesh2", ExactSpelling = true)] internal extern static void EvalMesh2(int mode, Int32 i1, Int32 i2, Int32 j1, Int32 j2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEvalPoint2", ExactSpelling = true)] internal extern static void EvalPoint2(Int32 i, Int32 j); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glAlphaFunc", ExactSpelling = true)] internal extern static void AlphaFunc(int func, Single @ref); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBlendFunc", ExactSpelling = true)] internal extern static void BlendFunc(int sfactor, int dfactor); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLogicOp", ExactSpelling = true)] internal extern static void LogicOp(int opcode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilFunc", ExactSpelling = true)] internal extern static void StencilFunc(int func, Int32 @ref, UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilOp", ExactSpelling = true)] internal extern static void StencilOp(int fail, int zfail, int zpass); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDepthFunc", ExactSpelling = true)] internal extern static void DepthFunc(int func); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelZoom", ExactSpelling = true)] internal extern static void PixelZoom(Single xfactor, Single yfactor); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelTransferf", ExactSpelling = true)] internal extern static void PixelTransferf(int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelTransferi", ExactSpelling = true)] internal extern static void PixelTransferi(int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelStoref", ExactSpelling = true)] internal extern static void PixelStoref(int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelStorei", ExactSpelling = true)] internal extern static void PixelStorei(int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelMapfv", ExactSpelling = true)] internal extern static unsafe void PixelMapfv(int map, Int32 mapsize, Single* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelMapuiv", ExactSpelling = true)] internal extern static unsafe void PixelMapuiv(int map, Int32 mapsize, UInt32* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPixelMapusv", ExactSpelling = true)] internal extern static unsafe void PixelMapusv(int map, Int32 mapsize, UInt16* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glReadBuffer", ExactSpelling = true)] internal extern static void ReadBuffer(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyPixels", ExactSpelling = true)] internal extern static void CopyPixels(Int32 x, Int32 y, Int32 width, Int32 height, int type); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glReadPixels", ExactSpelling = true)] internal extern static void ReadPixels(Int32 x, Int32 y, Int32 width, Int32 height, int format, int type, [Out] IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawPixels", ExactSpelling = true)] internal extern static void DrawPixels(Int32 width, Int32 height, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetBooleanv", ExactSpelling = true)] internal extern static unsafe void GetBooleanv(int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetClipPlane", ExactSpelling = true)] internal extern static unsafe void GetClipPlane(int plane, [Out] Double* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetDoublev", ExactSpelling = true)] internal extern static unsafe void GetDoublev(int pname, [Out] Double* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetError", ExactSpelling = true)] internal extern static int GetError(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetFloatv", ExactSpelling = true)] internal extern static unsafe void GetFloatv(int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetIntegerv", ExactSpelling = true)] internal extern static unsafe void GetIntegerv(int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetLightfv", ExactSpelling = true)] internal extern static unsafe void GetLightfv(int light, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetLightiv", ExactSpelling = true)] internal extern static unsafe void GetLightiv(int light, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMapdv", ExactSpelling = true)] internal extern static unsafe void GetMapdv(int target, int query, [Out] Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMapfv", ExactSpelling = true)] internal extern static unsafe void GetMapfv(int target, int query, [Out] Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMapiv", ExactSpelling = true)] internal extern static unsafe void GetMapiv(int target, int query, [Out] Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMaterialfv", ExactSpelling = true)] internal extern static unsafe void GetMaterialfv(int face, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMaterialiv", ExactSpelling = true)] internal extern static unsafe void GetMaterialiv(int face, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetPixelMapfv", ExactSpelling = true)] internal extern static unsafe void GetPixelMapfv(int map, [Out] Single* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetPixelMapuiv", ExactSpelling = true)] internal extern static unsafe void GetPixelMapuiv(int map, [Out] UInt32* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetPixelMapusv", ExactSpelling = true)] internal extern static unsafe void GetPixelMapusv(int map, [Out] UInt16* values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetPolygonStipple", ExactSpelling = true)] internal extern static unsafe void GetPolygonStipple([Out] Byte* mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetString", ExactSpelling = true)] internal extern static IntPtr GetString(int name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexEnvfv", ExactSpelling = true)] internal extern static unsafe void GetTexEnvfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexEnviv", ExactSpelling = true)] internal extern static unsafe void GetTexEnviv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexGendv", ExactSpelling = true)] internal extern static unsafe void GetTexGendv(int coord, int pname, [Out] Double* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexGenfv", ExactSpelling = true)] internal extern static unsafe void GetTexGenfv(int coord, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexGeniv", ExactSpelling = true)] internal extern static unsafe void GetTexGeniv(int coord, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexImage", ExactSpelling = true)] internal extern static void GetTexImage(int target, Int32 level, int format, int type, [Out] IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexParameterfv", ExactSpelling = true)] internal extern static unsafe void GetTexParameterfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexParameteriv", ExactSpelling = true)] internal extern static unsafe void GetTexParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexLevelParameterfv", ExactSpelling = true)] internal extern static unsafe void GetTexLevelParameterfv(int target, Int32 level, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetTexLevelParameteriv", ExactSpelling = true)] internal extern static unsafe void GetTexLevelParameteriv(int target, Int32 level, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsEnabled", ExactSpelling = true)] internal extern static Int32 IsEnabled(int cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsList", ExactSpelling = true)] internal extern static Int32 IsList(UInt32 list); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDepthRange", ExactSpelling = true)] internal extern static void DepthRange(Double near, Double far); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFrustum", ExactSpelling = true)] internal extern static void Frustum(Double left, Double right, Double bottom, Double top, Double zNear, Double zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadIdentity", ExactSpelling = true)] internal extern static void LoadIdentity(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadMatrixf", ExactSpelling = true)] internal extern static unsafe void LoadMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadMatrixd", ExactSpelling = true)] internal extern static unsafe void LoadMatrixd(Double* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMatrixMode", ExactSpelling = true)] internal extern static void MatrixMode(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultMatrixf", ExactSpelling = true)] internal extern static unsafe void MultMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultMatrixd", ExactSpelling = true)] internal extern static unsafe void MultMatrixd(Double* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glOrtho", ExactSpelling = true)] internal extern static void Ortho(Double left, Double right, Double bottom, Double top, Double zNear, Double zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPopMatrix", ExactSpelling = true)] internal extern static void PopMatrix(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPushMatrix", ExactSpelling = true)] internal extern static void PushMatrix(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRotated", ExactSpelling = true)] internal extern static void Rotated(Double angle, Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glRotatef", ExactSpelling = true)] internal extern static void Rotatef(Single angle, Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glScaled", ExactSpelling = true)] internal extern static void Scaled(Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glScalef", ExactSpelling = true)] internal extern static void Scalef(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTranslated", ExactSpelling = true)] internal extern static void Translated(Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTranslatef", ExactSpelling = true)] internal extern static void Translatef(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glViewport", ExactSpelling = true)] internal extern static void Viewport(Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glArrayElement", ExactSpelling = true)] internal extern static void ArrayElement(Int32 i); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorPointer", ExactSpelling = true)] internal extern static void ColorPointer(Int32 size, int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDisableClientState", ExactSpelling = true)] internal extern static void DisableClientState(int array); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawArrays", ExactSpelling = true)] internal extern static void DrawArrays(int mode, Int32 first, Int32 count); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawElements", ExactSpelling = true)] internal extern static void DrawElements(int mode, Int32 count, int type, IntPtr indices); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEdgeFlagPointer", ExactSpelling = true)] internal extern static void EdgeFlagPointer(Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEnableClientState", ExactSpelling = true)] internal extern static void EnableClientState(int array); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetPointerv", ExactSpelling = true)] internal extern static void GetPointerv(int pname, [Out] IntPtr @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexPointer", ExactSpelling = true)] internal extern static void IndexPointer(int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glInterleavedArrays", ExactSpelling = true)] internal extern static void InterleavedArrays(int format, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glNormalPointer", ExactSpelling = true)] internal extern static void NormalPointer(int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexCoordPointer", ExactSpelling = true)] internal extern static void TexCoordPointer(Int32 size, int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexPointer", ExactSpelling = true)] internal extern static void VertexPointer(Int32 size, int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPolygonOffset", ExactSpelling = true)] internal extern static void PolygonOffset(Single factor, Single units); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyTexImage1D", ExactSpelling = true)] internal extern static void CopyTexImage1D(int target, Int32 level, int internalformat, Int32 x, Int32 y, Int32 width, Int32 border); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyTexImage2D", ExactSpelling = true)] internal extern static void CopyTexImage2D(int target, Int32 level, int internalformat, Int32 x, Int32 y, Int32 width, Int32 height, Int32 border); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyTexSubImage1D", ExactSpelling = true)] internal extern static void CopyTexSubImage1D(int target, Int32 level, Int32 xoffset, Int32 x, Int32 y, Int32 width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyTexSubImage2D", ExactSpelling = true)] internal extern static void CopyTexSubImage2D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexSubImage1D", ExactSpelling = true)] internal extern static void TexSubImage1D(int target, Int32 level, Int32 xoffset, Int32 width, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexSubImage2D", ExactSpelling = true)] internal extern static void TexSubImage2D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glAreTexturesResident", ExactSpelling = true)] internal extern static unsafe Int32 AreTexturesResident(Int32 n, UInt32* textures, [Out] Int32* residences); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBindTexture", ExactSpelling = true)] internal extern static void BindTexture(int target, UInt32 texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteTextures", ExactSpelling = true)] internal extern static unsafe void DeleteTextures(Int32 n, UInt32* textures); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGenTextures", ExactSpelling = true)] internal extern static unsafe void GenTextures(Int32 n, [Out] UInt32* textures); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsTexture", ExactSpelling = true)] internal extern static Int32 IsTexture(UInt32 texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPrioritizeTextures", ExactSpelling = true)] internal extern static unsafe void PrioritizeTextures(Int32 n, UInt32* textures, Single* priorities); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexub", ExactSpelling = true)] internal extern static void Indexub(Byte c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIndexubv", ExactSpelling = true)] internal extern static unsafe void Indexubv(Byte* c); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPopClientAttrib", ExactSpelling = true)] internal extern static void PopClientAttrib(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPushClientAttrib", ExactSpelling = true)] internal extern static void PushClientAttrib(int mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBlendColor", ExactSpelling = true)] internal extern static void BlendColor(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBlendEquation", ExactSpelling = true)] internal extern static void BlendEquation(int mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawRangeElements", ExactSpelling = true)] internal extern static void DrawRangeElements(int mode, UInt32 start, UInt32 end, Int32 count, int type, IntPtr indices); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorTable", ExactSpelling = true)] internal extern static void ColorTable(int target, int internalformat, Int32 width, int format, int type, IntPtr table); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorTableParameterfv", ExactSpelling = true)] internal extern static unsafe void ColorTableParameterfv(int target, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorTableParameteriv", ExactSpelling = true)] internal extern static unsafe void ColorTableParameteriv(int target, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyColorTable", ExactSpelling = true)] internal extern static void CopyColorTable(int target, int internalformat, Int32 x, Int32 y, Int32 width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetColorTable", ExactSpelling = true)] internal extern static void GetColorTable(int target, int format, int type, [Out] IntPtr table); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetColorTableParameterfv", ExactSpelling = true)] internal extern static unsafe void GetColorTableParameterfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetColorTableParameteriv", ExactSpelling = true)] internal extern static unsafe void GetColorTableParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glColorSubTable", ExactSpelling = true)] internal extern static void ColorSubTable(int target, Int32 start, Int32 count, int format, int type, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyColorSubTable", ExactSpelling = true)] internal extern static void CopyColorSubTable(int target, Int32 start, Int32 x, Int32 y, Int32 width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionFilter1D", ExactSpelling = true)] internal extern static void ConvolutionFilter1D(int target, int internalformat, Int32 width, int format, int type, IntPtr image); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionFilter2D", ExactSpelling = true)] internal extern static void ConvolutionFilter2D(int target, int internalformat, Int32 width, Int32 height, int format, int type, IntPtr image); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionParameterf", ExactSpelling = true)] internal extern static void ConvolutionParameterf(int target, int pname, Single @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionParameterfv", ExactSpelling = true)] internal extern static unsafe void ConvolutionParameterfv(int target, int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionParameteri", ExactSpelling = true)] internal extern static void ConvolutionParameteri(int target, int pname, Int32 @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glConvolutionParameteriv", ExactSpelling = true)] internal extern static unsafe void ConvolutionParameteriv(int target, int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyConvolutionFilter1D", ExactSpelling = true)] internal extern static void CopyConvolutionFilter1D(int target, int internalformat, Int32 x, Int32 y, Int32 width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyConvolutionFilter2D", ExactSpelling = true)] internal extern static void CopyConvolutionFilter2D(int target, int internalformat, Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetConvolutionFilter", ExactSpelling = true)] internal extern static void GetConvolutionFilter(int target, int format, int type, [Out] IntPtr image); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetConvolutionParameterfv", ExactSpelling = true)] internal extern static unsafe void GetConvolutionParameterfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetConvolutionParameteriv", ExactSpelling = true)] internal extern static unsafe void GetConvolutionParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetSeparableFilter", ExactSpelling = true)] internal extern static void GetSeparableFilter(int target, int format, int type, [Out] IntPtr row, [Out] IntPtr column, [Out] IntPtr span); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSeparableFilter2D", ExactSpelling = true)] internal extern static void SeparableFilter2D(int target, int internalformat, Int32 width, Int32 height, int format, int type, IntPtr row, IntPtr column); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetHistogram", ExactSpelling = true)] internal extern static void GetHistogram(int target, Int32 reset, int format, int type, [Out] IntPtr values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetHistogramParameterfv", ExactSpelling = true)] internal extern static unsafe void GetHistogramParameterfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetHistogramParameteriv", ExactSpelling = true)] internal extern static unsafe void GetHistogramParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMinmax", ExactSpelling = true)] internal extern static void GetMinmax(int target, Int32 reset, int format, int type, [Out] IntPtr values); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMinmaxParameterfv", ExactSpelling = true)] internal extern static unsafe void GetMinmaxParameterfv(int target, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetMinmaxParameteriv", ExactSpelling = true)] internal extern static unsafe void GetMinmaxParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glHistogram", ExactSpelling = true)] internal extern static void Histogram(int target, Int32 width, int internalformat, Int32 sink); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMinmax", ExactSpelling = true)] internal extern static void Minmax(int target, int internalformat, Int32 sink); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glResetHistogram", ExactSpelling = true)] internal extern static void ResetHistogram(int target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glResetMinmax", ExactSpelling = true)] internal extern static void ResetMinmax(int target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexImage3D", ExactSpelling = true)] internal extern static void TexImage3D(int target, Int32 level, int internalformat, Int32 width, Int32 height, Int32 depth, Int32 border, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glTexSubImage3D", ExactSpelling = true)] internal extern static void TexSubImage3D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 zoffset, Int32 width, Int32 height, Int32 depth, int format, int type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCopyTexSubImage3D", ExactSpelling = true)] internal extern static void CopyTexSubImage3D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 zoffset, Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glActiveTexture", ExactSpelling = true)] internal extern static void ActiveTexture(int texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glClientActiveTexture", ExactSpelling = true)] internal extern static void ClientActiveTexture(int texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1d", ExactSpelling = true)] internal extern static void MultiTexCoord1d(int target, Double s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1dv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord1dv(int target, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1f", ExactSpelling = true)] internal extern static void MultiTexCoord1f(int target, Single s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1fv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord1fv(int target, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1i", ExactSpelling = true)] internal extern static void MultiTexCoord1i(int target, Int32 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1iv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord1iv(int target, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1s", ExactSpelling = true)] internal extern static void MultiTexCoord1s(int target, Int16 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord1sv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord1sv(int target, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2d", ExactSpelling = true)] internal extern static void MultiTexCoord2d(int target, Double s, Double t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2dv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord2dv(int target, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2f", ExactSpelling = true)] internal extern static void MultiTexCoord2f(int target, Single s, Single t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2fv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord2fv(int target, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2i", ExactSpelling = true)] internal extern static void MultiTexCoord2i(int target, Int32 s, Int32 t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2iv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord2iv(int target, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2s", ExactSpelling = true)] internal extern static void MultiTexCoord2s(int target, Int16 s, Int16 t); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord2sv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord2sv(int target, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3d", ExactSpelling = true)] internal extern static void MultiTexCoord3d(int target, Double s, Double t, Double r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3dv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord3dv(int target, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3f", ExactSpelling = true)] internal extern static void MultiTexCoord3f(int target, Single s, Single t, Single r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3fv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord3fv(int target, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3i", ExactSpelling = true)] internal extern static void MultiTexCoord3i(int target, Int32 s, Int32 t, Int32 r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3iv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord3iv(int target, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3s", ExactSpelling = true)] internal extern static void MultiTexCoord3s(int target, Int16 s, Int16 t, Int16 r); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord3sv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord3sv(int target, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4d", ExactSpelling = true)] internal extern static void MultiTexCoord4d(int target, Double s, Double t, Double r, Double q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4dv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord4dv(int target, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4f", ExactSpelling = true)] internal extern static void MultiTexCoord4f(int target, Single s, Single t, Single r, Single q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4fv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord4fv(int target, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4i", ExactSpelling = true)] internal extern static void MultiTexCoord4i(int target, Int32 s, Int32 t, Int32 r, Int32 q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4iv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord4iv(int target, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4s", ExactSpelling = true)] internal extern static void MultiTexCoord4s(int target, Int16 s, Int16 t, Int16 r, Int16 q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiTexCoord4sv", ExactSpelling = true)] internal extern static unsafe void MultiTexCoord4sv(int target, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadTransposeMatrixf", ExactSpelling = true)] internal extern static unsafe void LoadTransposeMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLoadTransposeMatrixd", ExactSpelling = true)] internal extern static unsafe void LoadTransposeMatrixd(Double* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultTransposeMatrixf", ExactSpelling = true)] internal extern static unsafe void MultTransposeMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultTransposeMatrixd", ExactSpelling = true)] internal extern static unsafe void MultTransposeMatrixd(Double* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSampleCoverage", ExactSpelling = true)] internal extern static void SampleCoverage(Single value, Int32 invert); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexImage3D", ExactSpelling = true)] internal extern static void CompressedTexImage3D(int target, Int32 level, int internalformat, Int32 width, Int32 height, Int32 depth, Int32 border, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexImage2D", ExactSpelling = true)] internal extern static void CompressedTexImage2D(int target, Int32 level, int internalformat, Int32 width, Int32 height, Int32 border, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexImage1D", ExactSpelling = true)] internal extern static void CompressedTexImage1D(int target, Int32 level, int internalformat, Int32 width, Int32 border, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexSubImage3D", ExactSpelling = true)] internal extern static void CompressedTexSubImage3D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 zoffset, Int32 width, Int32 height, Int32 depth, int format, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexSubImage2D", ExactSpelling = true)] internal extern static void CompressedTexSubImage2D(int target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, int format, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompressedTexSubImage1D", ExactSpelling = true)] internal extern static void CompressedTexSubImage1D(int target, Int32 level, Int32 xoffset, Int32 width, int format, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetCompressedTexImage", ExactSpelling = true)] internal extern static void GetCompressedTexImage(int target, Int32 level, [Out] IntPtr img); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBlendFuncSeparate", ExactSpelling = true)] internal extern static void BlendFuncSeparate(int sfactorRGB, int dfactorRGB, int sfactorAlpha, int dfactorAlpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogCoordf", ExactSpelling = true)] internal extern static void FogCoordf(Single coord); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogCoordfv", ExactSpelling = true)] internal extern static unsafe void FogCoordfv(Single* coord); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogCoordd", ExactSpelling = true)] internal extern static void FogCoordd(Double coord); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogCoorddv", ExactSpelling = true)] internal extern static unsafe void FogCoorddv(Double* coord); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glFogCoordPointer", ExactSpelling = true)] internal extern static void FogCoordPointer(int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiDrawArrays", ExactSpelling = true)] internal extern static unsafe void MultiDrawArrays(int mode, [Out] Int32* first, [Out] Int32* count, Int32 primcount); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMultiDrawElements", ExactSpelling = true)] internal extern static unsafe void MultiDrawElements(int mode, Int32* count, int type, IntPtr indices, Int32 primcount); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPointParameterf", ExactSpelling = true)] internal extern static void PointParameterf(int pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPointParameterfv", ExactSpelling = true)] internal extern static unsafe void PointParameterfv(int pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPointParameteri", ExactSpelling = true)] internal extern static void PointParameteri(int pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glPointParameteriv", ExactSpelling = true)] internal extern static unsafe void PointParameteriv(int pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3b", ExactSpelling = true)] internal extern static void SecondaryColor3b(SByte red, SByte green, SByte blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3bv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3bv(SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3d", ExactSpelling = true)] internal extern static void SecondaryColor3d(Double red, Double green, Double blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3dv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3f", ExactSpelling = true)] internal extern static void SecondaryColor3f(Single red, Single green, Single blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3fv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3i", ExactSpelling = true)] internal extern static void SecondaryColor3i(Int32 red, Int32 green, Int32 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3iv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3s", ExactSpelling = true)] internal extern static void SecondaryColor3s(Int16 red, Int16 green, Int16 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3sv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3ub", ExactSpelling = true)] internal extern static void SecondaryColor3ub(Byte red, Byte green, Byte blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3ubv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3ubv(Byte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3ui", ExactSpelling = true)] internal extern static void SecondaryColor3ui(UInt32 red, UInt32 green, UInt32 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3uiv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3uiv(UInt32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3us", ExactSpelling = true)] internal extern static void SecondaryColor3us(UInt16 red, UInt16 green, UInt16 blue); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColor3usv", ExactSpelling = true)] internal extern static unsafe void SecondaryColor3usv(UInt16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glSecondaryColorPointer", ExactSpelling = true)] internal extern static void SecondaryColorPointer(Int32 size, int type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2d", ExactSpelling = true)] internal extern static void WindowPos2d(Double x, Double y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2dv", ExactSpelling = true)] internal extern static unsafe void WindowPos2dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2f", ExactSpelling = true)] internal extern static void WindowPos2f(Single x, Single y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2fv", ExactSpelling = true)] internal extern static unsafe void WindowPos2fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2i", ExactSpelling = true)] internal extern static void WindowPos2i(Int32 x, Int32 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2iv", ExactSpelling = true)] internal extern static unsafe void WindowPos2iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2s", ExactSpelling = true)] internal extern static void WindowPos2s(Int16 x, Int16 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos2sv", ExactSpelling = true)] internal extern static unsafe void WindowPos2sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3d", ExactSpelling = true)] internal extern static void WindowPos3d(Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3dv", ExactSpelling = true)] internal extern static unsafe void WindowPos3dv(Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3f", ExactSpelling = true)] internal extern static void WindowPos3f(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3fv", ExactSpelling = true)] internal extern static unsafe void WindowPos3fv(Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3i", ExactSpelling = true)] internal extern static void WindowPos3i(Int32 x, Int32 y, Int32 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3iv", ExactSpelling = true)] internal extern static unsafe void WindowPos3iv(Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3s", ExactSpelling = true)] internal extern static void WindowPos3s(Int16 x, Int16 y, Int16 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glWindowPos3sv", ExactSpelling = true)] internal extern static unsafe void WindowPos3sv(Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGenQueries", ExactSpelling = true)] internal extern static unsafe void GenQueries(Int32 n, [Out] UInt32* ids); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteQueries", ExactSpelling = true)] internal extern static unsafe void DeleteQueries(Int32 n, UInt32* ids); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsQuery", ExactSpelling = true)] internal extern static Int32 IsQuery(UInt32 id); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBeginQuery", ExactSpelling = true)] internal extern static void BeginQuery(int target, UInt32 id); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEndQuery", ExactSpelling = true)] internal extern static void EndQuery(int target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetQueryiv", ExactSpelling = true)] internal extern static unsafe void GetQueryiv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetQueryObjectiv", ExactSpelling = true)] internal extern static unsafe void GetQueryObjectiv(UInt32 id, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetQueryObjectuiv", ExactSpelling = true)] internal extern static unsafe void GetQueryObjectuiv(UInt32 id, int pname, [Out] UInt32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBindBuffer", ExactSpelling = true)] internal extern static void BindBuffer(int target, UInt32 buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteBuffers", ExactSpelling = true)] internal extern static unsafe void DeleteBuffers(Int32 n, UInt32* buffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGenBuffers", ExactSpelling = true)] internal extern static unsafe void GenBuffers(Int32 n, [Out] UInt32* buffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsBuffer", ExactSpelling = true)] internal extern static Int32 IsBuffer(UInt32 buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBufferData", ExactSpelling = true)] internal extern static void BufferData(int target, IntPtr size, IntPtr data, int usage); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBufferSubData", ExactSpelling = true)] internal extern static void BufferSubData(int target, IntPtr offset, IntPtr size, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetBufferSubData", ExactSpelling = true)] internal extern static void GetBufferSubData(int target, IntPtr offset, IntPtr size, [Out] IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glMapBuffer", ExactSpelling = true)] internal extern static unsafe IntPtr MapBuffer(int target, int access); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUnmapBuffer", ExactSpelling = true)] internal extern static Int32 UnmapBuffer(int target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetBufferParameteriv", ExactSpelling = true)] internal extern static unsafe void GetBufferParameteriv(int target, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetBufferPointerv", ExactSpelling = true)] internal extern static void GetBufferPointerv(int target, int pname, [Out] IntPtr @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBlendEquationSeparate", ExactSpelling = true)] internal extern static void BlendEquationSeparate(int modeRGB, int modeAlpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDrawBuffers", ExactSpelling = true)] internal extern static unsafe void DrawBuffers(Int32 n, int* bufs); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilOpSeparate", ExactSpelling = true)] internal extern static void StencilOpSeparate(int face, int sfail, int dpfail, int dppass); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilFuncSeparate", ExactSpelling = true)] internal extern static void StencilFuncSeparate(int frontfunc, int backfunc, Int32 @ref, UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glStencilMaskSeparate", ExactSpelling = true)] internal extern static void StencilMaskSeparate(int face, UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glAttachShader", ExactSpelling = true)] internal extern static void AttachShader(UInt32 program, UInt32 shader); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glBindAttribLocation", ExactSpelling = true)] internal extern static void BindAttribLocation(UInt32 program, UInt32 index, System.String name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCompileShader", ExactSpelling = true)] internal extern static void CompileShader(UInt32 shader); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCreateProgram", ExactSpelling = true)] internal extern static Int32 CreateProgram(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glCreateShader", ExactSpelling = true)] internal extern static Int32 CreateShader(int type); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteProgram", ExactSpelling = true)] internal extern static void DeleteProgram(UInt32 program); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDeleteShader", ExactSpelling = true)] internal extern static void DeleteShader(UInt32 shader); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDetachShader", ExactSpelling = true)] internal extern static void DetachShader(UInt32 program, UInt32 shader); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glDisableVertexAttribArray", ExactSpelling = true)] internal extern static void DisableVertexAttribArray(UInt32 index); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glEnableVertexAttribArray", ExactSpelling = true)] internal extern static void EnableVertexAttribArray(UInt32 index); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetActiveAttrib", ExactSpelling = true)] internal extern static unsafe void GetActiveAttrib(UInt32 program, UInt32 index, Int32 bufSize, [Out] Int32* length, [Out] Int32* size, [Out] int* type, [Out] System.Text.StringBuilder name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetActiveUniform", ExactSpelling = true)] internal extern static unsafe void GetActiveUniform(UInt32 program, UInt32 index, Int32 bufSize, [Out] Int32* length, [Out] Int32* size, [Out] int* type, [Out] System.Text.StringBuilder name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetAttachedShaders", ExactSpelling = true)] internal extern static unsafe void GetAttachedShaders(UInt32 program, Int32 maxCount, [Out] Int32* count, [Out] UInt32* obj); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetAttribLocation", ExactSpelling = true)] internal extern static Int32 GetAttribLocation(UInt32 program, System.String name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetProgramiv", ExactSpelling = true)] internal extern static unsafe void GetProgramiv(UInt32 program, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetProgramInfoLog", ExactSpelling = true)] internal extern static unsafe void GetProgramInfoLog(UInt32 program, Int32 bufSize, [Out] Int32* length, [Out] System.Text.StringBuilder infoLog); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetShaderiv", ExactSpelling = true)] internal extern static unsafe void GetShaderiv(UInt32 shader, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetShaderInfoLog", ExactSpelling = true)] internal extern static unsafe void GetShaderInfoLog(UInt32 shader, Int32 bufSize, [Out] Int32* length, [Out] System.Text.StringBuilder infoLog); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetShaderSource", ExactSpelling = true)] internal extern static unsafe void GetShaderSource(UInt32 shader, Int32 bufSize, [Out] Int32* length, [Out] System.Text.StringBuilder[] source); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetUniformLocation", ExactSpelling = true)] internal extern static Int32 GetUniformLocation(UInt32 program, System.String name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetUniformfv", ExactSpelling = true)] internal extern static unsafe void GetUniformfv(UInt32 program, Int32 location, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetUniformiv", ExactSpelling = true)] internal extern static unsafe void GetUniformiv(UInt32 program, Int32 location, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetVertexAttribdv", ExactSpelling = true)] internal extern static unsafe void GetVertexAttribdv(UInt32 index, int pname, [Out] Double* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetVertexAttribfv", ExactSpelling = true)] internal extern static unsafe void GetVertexAttribfv(UInt32 index, int pname, [Out] Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetVertexAttribiv", ExactSpelling = true)] internal extern static unsafe void GetVertexAttribiv(UInt32 index, int pname, [Out] Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glGetVertexAttribPointerv", ExactSpelling = true)] internal extern static void GetVertexAttribPointerv(UInt32 index, int pname, [Out] IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsProgram", ExactSpelling = true)] internal extern static Int32 IsProgram(UInt32 program); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glIsShader", ExactSpelling = true)] internal extern static Int32 IsShader(UInt32 shader); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glLinkProgram", ExactSpelling = true)] internal extern static void LinkProgram(UInt32 program); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glShaderSource", ExactSpelling = true)] internal extern static unsafe void ShaderSource(UInt32 shader, Int32 count, System.String[] @string, Int32* length); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUseProgram", ExactSpelling = true)] internal extern static void UseProgram(UInt32 program); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform1f", ExactSpelling = true)] internal extern static void Uniform1f(Int32 location, Single v0); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform2f", ExactSpelling = true)] internal extern static void Uniform2f(Int32 location, Single v0, Single v1); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform3f", ExactSpelling = true)] internal extern static void Uniform3f(Int32 location, Single v0, Single v1, Single v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform4f", ExactSpelling = true)] internal extern static void Uniform4f(Int32 location, Single v0, Single v1, Single v2, Single v3); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform1i", ExactSpelling = true)] internal extern static void Uniform1i(Int32 location, Int32 v0); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform2i", ExactSpelling = true)] internal extern static void Uniform2i(Int32 location, Int32 v0, Int32 v1); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform3i", ExactSpelling = true)] internal extern static void Uniform3i(Int32 location, Int32 v0, Int32 v1, Int32 v2); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform4i", ExactSpelling = true)] internal extern static void Uniform4i(Int32 location, Int32 v0, Int32 v1, Int32 v2, Int32 v3); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform1fv", ExactSpelling = true)] internal extern static unsafe void Uniform1fv(Int32 location, Int32 count, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform2fv", ExactSpelling = true)] internal extern static unsafe void Uniform2fv(Int32 location, Int32 count, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform3fv", ExactSpelling = true)] internal extern static unsafe void Uniform3fv(Int32 location, Int32 count, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform4fv", ExactSpelling = true)] internal extern static unsafe void Uniform4fv(Int32 location, Int32 count, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform1iv", ExactSpelling = true)] internal extern static unsafe void Uniform1iv(Int32 location, Int32 count, Int32* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform2iv", ExactSpelling = true)] internal extern static unsafe void Uniform2iv(Int32 location, Int32 count, Int32* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform3iv", ExactSpelling = true)] internal extern static unsafe void Uniform3iv(Int32 location, Int32 count, Int32* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniform4iv", ExactSpelling = true)] internal extern static unsafe void Uniform4iv(Int32 location, Int32 count, Int32* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix2fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix2fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix3fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix3fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix4fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix4fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glValidateProgram", ExactSpelling = true)] internal extern static void ValidateProgram(UInt32 program); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1d", ExactSpelling = true)] internal extern static void VertexAttrib1d(UInt32 index, Double x); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1dv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib1dv(UInt32 index, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1f", ExactSpelling = true)] internal extern static void VertexAttrib1f(UInt32 index, Single x); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1fv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib1fv(UInt32 index, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1s", ExactSpelling = true)] internal extern static void VertexAttrib1s(UInt32 index, Int16 x); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib1sv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib1sv(UInt32 index, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2d", ExactSpelling = true)] internal extern static void VertexAttrib2d(UInt32 index, Double x, Double y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2dv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib2dv(UInt32 index, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2f", ExactSpelling = true)] internal extern static void VertexAttrib2f(UInt32 index, Single x, Single y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2fv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib2fv(UInt32 index, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2s", ExactSpelling = true)] internal extern static void VertexAttrib2s(UInt32 index, Int16 x, Int16 y); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib2sv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib2sv(UInt32 index, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3d", ExactSpelling = true)] internal extern static void VertexAttrib3d(UInt32 index, Double x, Double y, Double z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3dv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib3dv(UInt32 index, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3f", ExactSpelling = true)] internal extern static void VertexAttrib3f(UInt32 index, Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3fv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib3fv(UInt32 index, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3s", ExactSpelling = true)] internal extern static void VertexAttrib3s(UInt32 index, Int16 x, Int16 y, Int16 z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib3sv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib3sv(UInt32 index, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nbv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Nbv(UInt32 index, SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Niv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Niv(UInt32 index, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nsv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Nsv(UInt32 index, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nub", ExactSpelling = true)] internal extern static void VertexAttrib4Nub(UInt32 index, Byte x, Byte y, Byte z, Byte w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nubv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Nubv(UInt32 index, Byte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nuiv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Nuiv(UInt32 index, UInt32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4Nusv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4Nusv(UInt32 index, UInt16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4bv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4bv(UInt32 index, SByte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4d", ExactSpelling = true)] internal extern static void VertexAttrib4d(UInt32 index, Double x, Double y, Double z, Double w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4dv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4dv(UInt32 index, Double* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4f", ExactSpelling = true)] internal extern static void VertexAttrib4f(UInt32 index, Single x, Single y, Single z, Single w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4fv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4fv(UInt32 index, Single* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4iv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4iv(UInt32 index, Int32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4s", ExactSpelling = true)] internal extern static void VertexAttrib4s(UInt32 index, Int16 x, Int16 y, Int16 z, Int16 w); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4sv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4sv(UInt32 index, Int16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4ubv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4ubv(UInt32 index, Byte* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4uiv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4uiv(UInt32 index, UInt32* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttrib4usv", ExactSpelling = true)] internal extern static unsafe void VertexAttrib4usv(UInt32 index, UInt16* v); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glVertexAttribPointer", ExactSpelling = true)] internal extern static void VertexAttribPointer(UInt32 index, Int32 size, int type, Int32 normalized, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix2x3fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix2x3fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix3x2fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix3x2fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix2x4fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix2x4fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix4x2fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix4x2fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix3x4fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix3x4fv(Int32 location, Int32 count, Int32 transpose, Single* value); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(Gl.Library, EntryPoint = "glUniformMatrix4x3fv", ExactSpelling = true)] internal extern static unsafe void UniformMatrix4x3fv(Int32 location, Int32 count, Int32 transpose, Single* value); } } }
0
0.751272
1
0.751272
game-dev
MEDIA
0.364362
game-dev
0.577111
1
0.577111
magefree/mage
1,712
Mage.Sets/src/mage/cards/p/PlunderingBarbarian.java
package mage.cards.p; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.game.permanent.token.TreasureToken; import mage.target.common.TargetArtifactPermanent; import java.util.UUID; /** * @author TheElk801 */ public final class PlunderingBarbarian extends CardImpl { public PlunderingBarbarian(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}"); this.subtype.add(SubType.DWARF); this.subtype.add(SubType.BARBARIAN); this.power = new MageInt(2); this.toughness = new MageInt(2); // When Plundering Barbarian enters the battlefield, choose one — // • Smash the Chest — Destroy target artifact. Ability ability = new EntersBattlefieldTriggeredAbility(new DestroyTargetEffect()); ability.addTarget(new TargetArtifactPermanent()); ability.getModes().getMode().withFlavorWord("Smash the Chest"); // • Pry It Open — Creature a Treasure token. ability.addMode(new Mode( new CreateTokenEffect(new TreasureToken()) ).withFlavorWord("Pry It Open")); this.addAbility(ability); } private PlunderingBarbarian(final PlunderingBarbarian card) { super(card); } @Override public PlunderingBarbarian copy() { return new PlunderingBarbarian(this); } }
0
0.887893
1
0.887893
game-dev
MEDIA
0.987872
game-dev
0.994849
1
0.994849
lua9520/source-engine-2018-hl2_src
59,533
game/server/ai_behavior.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef AI_BEHAVIOR_H #define AI_BEHAVIOR_H #include "ai_component.h" #include "ai_basenpc.h" #include "ai_default.h" #include "AI_Criteria.h" #include "networkvar.h" #ifdef DEBUG #pragma warning(push) #include <typeinfo> #pragma warning(pop) #pragma warning(disable:4290) #endif #if defined( _WIN32 ) #pragma once #endif //----------------------------------------------------------------------------- // CAI_Behavior... // // Purpose: The core component that defines a behavior in an NPC by selecting // schedules and running tasks // // Intended to be used as an organizational tool as well as a way // for various NPCs to share behaviors without sharing an inheritance // relationship, and without cramming those behaviors into the base // NPC class. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Purpose: Base class defines interface to behaviors and provides bridging // methods //----------------------------------------------------------------------------- class IBehaviorBackBridge; //------------------------------------- abstract_class CAI_BehaviorBase : public CAI_Component { DECLARE_CLASS( CAI_BehaviorBase, CAI_Component ) public: CAI_BehaviorBase(CAI_BaseNPC *pOuter = NULL) : CAI_Component(pOuter), m_pBackBridge(NULL) { } virtual const char *GetName() = 0; virtual bool KeyValue( const char *szKeyName, const char *szValue ) { return false; } bool IsRunning() { Assert( GetOuter() ); return ( GetOuter()->GetRunningBehavior() == this ); } virtual bool CanSelectSchedule() { return true; } virtual void BeginScheduleSelection() {} virtual void EndScheduleSelection() {} void SetBackBridge( IBehaviorBackBridge *pBackBridge ) { Assert( m_pBackBridge == NULL || pBackBridge == NULL ); m_pBackBridge = pBackBridge; } void BridgePrecache() { Precache(); } void BridgeSpawn() { Spawn(); } void BridgeUpdateOnRemove() { UpdateOnRemove(); } void BridgeEvent_Killed( const CTakeDamageInfo &info ) { Event_Killed( info ); } void BridgeCleanupOnDeath( CBaseEntity *pCulprit, bool bFireDeathOutput ) { CleanupOnDeath( pCulprit, bFireDeathOutput ); } void BridgeOnChangeHintGroup( string_t oldGroup, string_t newGroup ) { OnChangeHintGroup( oldGroup, newGroup ); } void BridgeGatherConditions() { GatherConditions(); } void BridgePrescheduleThink() { PrescheduleThink(); } void BridgeOnScheduleChange() { OnScheduleChange(); } void BridgeOnStartSchedule( int scheduleType ); int BridgeSelectSchedule(); bool BridgeSelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode, int *pResult ); bool BridgeStartTask( const Task_t *pTask ); bool BridgeRunTask( const Task_t *pTask); bool BridgeAimGun( void ); int BridgeTranslateSchedule( int scheduleType ); bool BridgeGetSchedule( int localScheduleID, CAI_Schedule **ppResult ); bool BridgeTaskName(int taskID, const char **); Activity BridgeNPC_TranslateActivity( Activity activity ); void BridgeBuildScheduleTestBits() { BuildScheduleTestBits(); } bool BridgeIsCurTaskContinuousMove( bool *pResult ); void BridgeOnMovementFailed() { OnMovementFailed(); } void BridgeOnMovementComplete() { OnMovementComplete(); } float BridgeGetDefaultNavGoalTolerance(); bool BridgeFValidateHintType( CAI_Hint *pHint, bool *pResult ); bool BridgeIsValidEnemy( CBaseEntity *pEnemy ); CBaseEntity *BridgeBestEnemy(); bool BridgeIsValidCover( const Vector &vLocation, CAI_Hint const *pHint ); bool BridgeIsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ); float BridgeGetMaxTacticalLateralMovement( void ); bool BridgeShouldIgnoreSound( CSound *pSound ); void BridgeOnSeeEntity( CBaseEntity *pEntity ); void BridgeOnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ); bool BridgeIsInterruptable( void ); bool BridgeIsNavigationUrgent( void ); bool BridgeShouldPlayerAvoid( void ); int BridgeOnTakeDamage_Alive( const CTakeDamageInfo &info ); float BridgeGetReasonableFacingDist( void ); bool BridgeShouldAlwaysThink( bool *pResult ); void BridgeOnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon ); void BridgeOnRestore(); virtual bool BridgeSpeakMapmakerInterruptConcept( string_t iszConcept ); bool BridgeCanFlinch( void ); bool BridgeIsCrouching( void ); bool BridgeIsCrouchedActivity( Activity activity ); bool BridgeQueryHearSound( CSound *pSound ); bool BridgeCanRunAScriptedNPCInteraction( bool bForced ); Activity BridgeGetFlinchActivity( bool bHeavyDamage, bool bGesture ); bool BridgeOnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ); void BridgeModifyOrAppendCriteria( AI_CriteriaSet& criteriaSet ); void BridgeTeleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ); void BridgeHandleAnimEvent( animevent_t *pEvent ); virtual void GatherConditions(); virtual void GatherConditionsNotActive() { return; } // Override this and your behavior will call this in place of GatherConditions() when your behavior is NOT the active one. virtual void OnUpdateShotRegulator() {} virtual CAI_ClassScheduleIdSpace *GetClassScheduleIdSpace(); virtual int DrawDebugTextOverlays( int text_offset ); virtual int Save( ISave &save ); virtual int Restore( IRestore &restore ); static void SaveBehaviors(ISave &save, CAI_BehaviorBase *pCurrentBehavior, CAI_BehaviorBase **ppBehavior, int nBehaviors ); static int RestoreBehaviors(IRestore &restore, CAI_BehaviorBase **ppBehavior, int nBehaviors ); // returns index of "current" behavior, or -1 protected: int GetNpcState() { return GetOuter()->m_NPCState; } virtual void Precache() {} virtual void Spawn() {} virtual void UpdateOnRemove() {} virtual void Event_Killed( const CTakeDamageInfo &info ) {} virtual void CleanupOnDeath( CBaseEntity *pCulprit, bool bFireDeathOutput ) {} virtual void PrescheduleThink(); virtual void OnScheduleChange(); virtual void OnStartSchedule( int scheduleType ); virtual int SelectSchedule(); virtual int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ); virtual void StartTask( const Task_t *pTask ); virtual void RunTask( const Task_t *pTask ); virtual void AimGun( void ); virtual int TranslateSchedule( int scheduleType ); virtual CAI_Schedule *GetSchedule(int schedule); virtual const char *GetSchedulingErrorName(); virtual void BuildScheduleTestBits() {} bool IsCurSchedule( int schedId, bool fIdeal = true ); CAI_Hint * GetHintNode() { return GetOuter()->GetHintNode(); } const CAI_Hint *GetHintNode() const { return GetOuter()->GetHintNode(); } void SetHintNode( CAI_Hint *pHintNode ) { GetOuter()->SetHintNode( pHintNode ); } void ClearHintNode( float reuseDelay = 0.0 ) { GetOuter()->ClearHintNode( reuseDelay ); } protected: // Used by derived classes to chain a task to a task that might not be the // one they are currently handling: void ChainStartTask( int task, float taskData = 0 ); void ChainRunTask( int task, float taskData = 0 ); protected: virtual Activity NPC_TranslateActivity( Activity activity ); virtual bool IsCurTaskContinuousMove(); virtual void OnMovementFailed() {}; virtual void OnMovementComplete() {}; virtual float GetDefaultNavGoalTolerance(); virtual bool FValidateHintType( CAI_Hint *pHint ); virtual bool IsValidEnemy( CBaseEntity *pEnemy ); virtual CBaseEntity *BestEnemy(); virtual bool IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ); virtual bool IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ); virtual float GetMaxTacticalLateralMovement( void ); virtual bool ShouldIgnoreSound( CSound *pSound ); virtual void OnSeeEntity( CBaseEntity *pEntity ); virtual void OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ); virtual bool IsInterruptable( void ); virtual bool IsNavigationUrgent( void ); virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info ); virtual float GetReasonableFacingDist( void ); virtual bool ShouldPlayerAvoid( void ); virtual bool CanFlinch( void ); virtual bool IsCrouching( void ); virtual bool IsCrouchedActivity( Activity activity ); virtual bool QueryHearSound( CSound *pSound ); virtual bool CanRunAScriptedNPCInteraction( bool bForced ); virtual Activity GetFlinchActivity( bool bHeavyDamage, bool bGesture ); virtual bool OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ); virtual void ModifyOrAppendCriteria( AI_CriteriaSet& criteriaSet ); virtual void Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ); virtual void HandleAnimEvent( animevent_t *pEvent ); virtual bool ShouldAlwaysThink(); virtual void OnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon ) {}; virtual bool SpeakMapmakerInterruptConcept( string_t iszConcept ) { return false; }; virtual void OnRestore() {}; bool NotifyChangeBehaviorStatus( bool fCanFinishSchedule = false ); bool HaveSequenceForActivity( Activity activity ) { return GetOuter()->HaveSequenceForActivity( activity ); } //--------------------------------- string_t GetHintGroup() { return GetOuter()->GetHintGroup(); } void ClearHintGroup() { GetOuter()->ClearHintGroup(); } void SetHintGroup( string_t name ) { GetOuter()->SetHintGroup( name ); } virtual void OnChangeHintGroup( string_t oldGroup, string_t newGroup ) {} // // These allow derived classes to implement custom schedules // static CAI_GlobalScheduleNamespace *GetSchedulingSymbols() { return CAI_BaseNPC::GetSchedulingSymbols(); } static bool LoadSchedules() { return true; } virtual bool IsBehaviorSchedule( int scheduleType ) { return false; } CAI_Navigator * GetNavigator() { return GetOuter()->GetNavigator(); } CAI_Motor * GetMotor() { return GetOuter()->GetMotor(); } CAI_TacticalServices * GetTacticalServices() { return GetOuter()->GetTacticalServices(); } bool m_fOverrode; IBehaviorBackBridge *m_pBackBridge; DECLARE_DATADESC(); }; //----------------------------------------------------------------------------- // Purpose: Template provides provides back bridge to owning class and // establishes namespace settings //----------------------------------------------------------------------------- template <class NPC_CLASS = CAI_BaseNPC, const int ID_SPACE_OFFSET = 100000> class CAI_Behavior : public CAI_ComponentWithOuter<NPC_CLASS, CAI_BehaviorBase> { public: DECLARE_CLASS_NOFRIEND( CAI_Behavior, NPC_CLASS ); enum { NEXT_TASK = ID_SPACE_OFFSET, NEXT_SCHEDULE = ID_SPACE_OFFSET, NEXT_CONDITION = ID_SPACE_OFFSET }; void SetCondition( int condition ) { if ( condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000 ) // it's local to us condition = GetClassScheduleIdSpace()->ConditionLocalToGlobal( condition ); this->GetOuter()->SetCondition( condition ); } bool HasCondition( int condition ) { if ( condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000 ) // it's local to us condition = GetClassScheduleIdSpace()->ConditionLocalToGlobal( condition ); return this->GetOuter()->HasCondition( condition ); } bool HasInterruptCondition( int condition ) { if ( condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000 ) // it's local to us condition = GetClassScheduleIdSpace()->ConditionLocalToGlobal( condition ); return this->GetOuter()->HasInterruptCondition( condition ); } void ClearCondition( int condition ) { if ( condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000 ) // it's local to us condition = GetClassScheduleIdSpace()->ConditionLocalToGlobal( condition ); this->GetOuter()->ClearCondition( condition ); } protected: CAI_Behavior(NPC_CLASS *pOuter = NULL) : CAI_ComponentWithOuter<NPC_CLASS, CAI_BehaviorBase>(pOuter) { } static CAI_GlobalScheduleNamespace *GetSchedulingSymbols() { return NPC_CLASS::GetSchedulingSymbols(); } virtual CAI_ClassScheduleIdSpace *GetClassScheduleIdSpace() { return this->GetOuter()->GetClassScheduleIdSpace(); } static CAI_ClassScheduleIdSpace &AccessClassScheduleIdSpaceDirect() { return NPC_CLASS::AccessClassScheduleIdSpaceDirect(); } private: virtual bool IsBehaviorSchedule( int scheduleType ) { return ( scheduleType >= ID_SPACE_OFFSET && scheduleType < ID_SPACE_OFFSET + 10000 ); } }; //----------------------------------------------------------------------------- // Purpose: Some bridges a little more complicated to allow behavior to see // what base class would do or control order in which it's donw //----------------------------------------------------------------------------- abstract_class IBehaviorBackBridge { public: virtual void BackBridge_GatherConditions() = 0; virtual int BackBridge_SelectSchedule() = 0; virtual int BackBridge_TranslateSchedule( int scheduleType ) = 0; virtual Activity BackBridge_NPC_TranslateActivity( Activity activity ) = 0; virtual bool BackBridge_IsValidEnemy(CBaseEntity *pEnemy) = 0; virtual CBaseEntity* BackBridge_BestEnemy(void) = 0; virtual bool BackBridge_IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ) = 0; virtual bool BackBridge_IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ) = 0; virtual float BackBridge_GetMaxTacticalLateralMovement( void ) = 0; virtual bool BackBridge_ShouldIgnoreSound( CSound *pSound ) = 0; virtual void BackBridge_OnSeeEntity( CBaseEntity *pEntity ) = 0; virtual void BackBridge_OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ) = 0; virtual bool BackBridge_IsInterruptable( void ) = 0; virtual bool BackBridge_IsNavigationUrgent( void ) = 0; virtual bool BackBridge_ShouldPlayerAvoid( void ) = 0; virtual int BackBridge_OnTakeDamage_Alive( const CTakeDamageInfo &info ) = 0; virtual float BackBridge_GetDefaultNavGoalTolerance() = 0; virtual float BackBridge_GetReasonableFacingDist( void ) = 0; virtual bool BackBridge_CanFlinch( void ) = 0; virtual bool BackBridge_IsCrouching( void ) = 0; virtual bool BackBridge_IsCrouchedActivity( Activity activity ) = 0; virtual bool BackBridge_QueryHearSound( CSound *pSound ) = 0; virtual bool BackBridge_CanRunAScriptedNPCInteraction( bool bForced ) = 0; virtual Activity BackBridge_GetFlinchActivity( bool bHeavyDamage, bool bGesture ) = 0; virtual bool BackBridge_OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ) = 0; virtual void BackBridge_ModifyOrAppendCriteria( AI_CriteriaSet& criteriaSet ) = 0; virtual void BackBridge_Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) = 0; virtual void BackBridge_HandleAnimEvent( animevent_t *pEvent ) = 0; //------------------------------------- }; //----------------------------------------------------------------------------- // Purpose: The common instantiation of the above template //----------------------------------------------------------------------------- typedef CAI_Behavior<> CAI_SimpleBehavior; //----------------------------------------------------------------------------- // Purpose: Base class for AIs that want to act as a host for CAI_Behaviors // NPCs aren't required to use this, but probably want to. //----------------------------------------------------------------------------- template <class BASE_NPC> class CAI_BehaviorHost : public BASE_NPC, private IBehaviorBackBridge { public: DECLARE_CLASS_NOFRIEND( CAI_BehaviorHost, BASE_NPC ); CAI_BehaviorHost() : m_pCurBehavior(NULL) { #ifdef DEBUG m_fDebugInCreateBehaviors = false; #endif } void CleanupOnDeath( CBaseEntity *pCulprit = NULL, bool bFireDeathOutput = true ); virtual int Save( ISave &save ); virtual int Restore( IRestore &restore ); virtual bool CreateComponents(); // Automatically called during entity construction, derived class calls AddBehavior() virtual bool CreateBehaviors() { return true; } // forces movement and sets a new schedule virtual bool ScheduledMoveToGoalEntity( int scheduleType, CBaseEntity *pGoalEntity, Activity movementActivity ); virtual bool ScheduledFollowPath( int scheduleType, CBaseEntity *pPathStart, Activity movementActivity ); virtual void ForceSelectedGo(CBaseEntity *pPlayer, const Vector &targetPos, const Vector &traceDir, bool bRun); virtual void ForceSelectedGoRandom(void); // Bridges void Precache(); void NPCInit(); void UpdateOnRemove(); void Event_Killed( const CTakeDamageInfo &info ); void GatherConditions(); void PrescheduleThink(); int SelectSchedule(); void KeepRunningBehavior(); int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ); void OnScheduleChange(); void OnStartSchedule( int scheduleType ); int TranslateSchedule( int scheduleType ); void StartTask( const Task_t *pTask ); void RunTask( const Task_t *pTask ); void AimGun( void ); CAI_Schedule * GetSchedule(int localScheduleID); const char * TaskName(int taskID); void BuildScheduleTestBits(); void OnChangeHintGroup( string_t oldGroup, string_t newGroup ); Activity NPC_TranslateActivity( Activity activity ); bool IsCurTaskContinuousMove(); void OnMovementFailed(); void OnMovementComplete(); bool FValidateHintType( CAI_Hint *pHint ); float GetDefaultNavGoalTolerance(); bool IsValidEnemy(CBaseEntity *pEnemy); CBaseEntity* BestEnemy(void); bool IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ); bool IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ); float GetMaxTacticalLateralMovement( void ); bool ShouldIgnoreSound( CSound *pSound ); void OnSeeEntity( CBaseEntity *pEntity ); void OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ); bool IsInterruptable( void ); bool IsNavigationUrgent( void ); bool ShouldPlayerAvoid( void ); int OnTakeDamage_Alive( const CTakeDamageInfo &info ); float GetReasonableFacingDist( void ); bool CanFlinch( void ); bool IsCrouching( void ); bool IsCrouchedActivity( Activity activity ); bool QueryHearSound( CSound *pSound ); bool CanRunAScriptedNPCInteraction( bool bForced ); Activity GetFlinchActivity( bool bHeavyDamage, bool bGesture ); bool OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ); void HandleAnimEvent( animevent_t *pEvent ); bool ShouldAlwaysThink(); void OnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon ); virtual bool SpeakMapmakerInterruptConcept( string_t iszConcept ); void OnRestore(); void ModifyOrAppendCriteria( AI_CriteriaSet& set ); void Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ); //--------------------------------- virtual bool OnBehaviorChangeStatus( CAI_BehaviorBase *pBehavior, bool fCanFinishSchedule ); virtual void OnChangeRunningBehavior( CAI_BehaviorBase *pOldBehavior, CAI_BehaviorBase *pNewBehavior ); protected: void AddBehavior( CAI_BehaviorBase *pBehavior ); bool BehaviorSelectSchedule(); virtual bool ShouldBehaviorSelectSchedule( CAI_BehaviorBase *pBehavior ) { return true; } bool IsRunningBehavior() const; CAI_BehaviorBase *GetRunningBehavior(); CAI_BehaviorBase *DeferSchedulingToBehavior( CAI_BehaviorBase *pNewBehavior ); void ChangeBehaviorTo( CAI_BehaviorBase *pNewBehavior ); CAI_Schedule * GetNewSchedule(); CAI_Schedule * GetFailSchedule(); private: void BackBridge_GatherConditions(); int BackBridge_SelectSchedule(); int BackBridge_TranslateSchedule( int scheduleType ); Activity BackBridge_NPC_TranslateActivity( Activity activity ); bool BackBridge_IsValidEnemy(CBaseEntity *pEnemy); CBaseEntity* BackBridge_BestEnemy(void); bool BackBridge_IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ); bool BackBridge_IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ); float BackBridge_GetMaxTacticalLateralMovement( void ); bool BackBridge_ShouldIgnoreSound( CSound *pSound ); void BackBridge_OnSeeEntity( CBaseEntity *pEntity ); void BackBridge_OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ); bool BackBridge_IsInterruptable( void ); bool BackBridge_IsNavigationUrgent( void ); bool BackBridge_ShouldPlayerAvoid( void ); int BackBridge_OnTakeDamage_Alive( const CTakeDamageInfo &info ); float BackBridge_GetDefaultNavGoalTolerance(); float BackBridge_GetReasonableFacingDist( void ); bool BackBridge_CanFlinch( void ); bool BackBridge_IsCrouching( void ); bool BackBridge_IsCrouchedActivity( Activity activity ); bool BackBridge_QueryHearSound( CSound *pSound ); bool BackBridge_CanRunAScriptedNPCInteraction( bool bForced ); Activity BackBridge_GetFlinchActivity( bool bHeavyDamage, bool bGesture ); bool BackBridge_OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ); void BackBridge_ModifyOrAppendCriteria( AI_CriteriaSet& criteriaSet ); void BackBridge_Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ); void BackBridge_HandleAnimEvent( animevent_t *pEvent ); CAI_BehaviorBase **AccessBehaviors(); int NumBehaviors(); CAI_BehaviorBase * m_pCurBehavior; CUtlVector<CAI_BehaviorBase *> m_Behaviors; bool m_bCalledBehaviorSelectSchedule; #ifdef DEBUG bool m_fDebugInCreateBehaviors; #endif }; //----------------------------------------------------------------------------- // The first frame a behavior begins schedule selection, it won't have had it's GatherConditions() // called. To fix this, BeginScheduleSelection() manually calls the new behavior's GatherConditions(), // but sets this global so that the baseclass GatherConditions() isn't called as well. extern bool g_bBehaviorHost_PreventBaseClassGatherConditions; //----------------------------------------------------------------------------- inline void CAI_BehaviorBase::BridgeOnStartSchedule( int scheduleType ) { int localId = AI_IdIsGlobal( scheduleType ) ? GetClassScheduleIdSpace()->ScheduleGlobalToLocal( scheduleType ) : scheduleType; OnStartSchedule( localId ); } //------------------------------------- inline int CAI_BehaviorBase::BridgeSelectSchedule() { int result = SelectSchedule(); if ( IsBehaviorSchedule( result ) ) return GetClassScheduleIdSpace()->ScheduleLocalToGlobal( result ); return result; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeSelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode, int *pResult ) { m_fOverrode = true; int result = SelectFailSchedule( failedSchedule, failedTask, taskFailCode ); if ( m_fOverrode ) { if ( result != SCHED_NONE ) { if ( IsBehaviorSchedule( result ) ) *pResult = GetClassScheduleIdSpace()->ScheduleLocalToGlobal( result ); else *pResult = result; return true; } Warning( "An AI behavior is in control but has no recommended schedule\n" ); } return false; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeStartTask( const Task_t *pTask ) { m_fOverrode = true; StartTask( pTask ); return m_fOverrode; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeRunTask( const Task_t *pTask) { m_fOverrode = true; RunTask( pTask ); return m_fOverrode; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeAimGun( void ) { m_fOverrode = true; AimGun(); return m_fOverrode; } //------------------------------------- inline void CAI_BehaviorBase::ChainStartTask( int task, float taskData ) { Task_t tempTask = { task, taskData }; bool fPrevOverride = m_fOverrode; GetOuter()->StartTask( (const Task_t *)&tempTask ); m_fOverrode = fPrevOverride;; } //------------------------------------- inline void CAI_BehaviorBase::ChainRunTask( int task, float taskData ) { Task_t tempTask = { task, taskData }; bool fPrevOverride = m_fOverrode; GetOuter()->RunTask( (const Task_t *) &tempTask ); m_fOverrode = fPrevOverride;; } //------------------------------------- inline int CAI_BehaviorBase::BridgeTranslateSchedule( int scheduleType ) { int localId = AI_IdIsGlobal( scheduleType ) ? GetClassScheduleIdSpace()->ScheduleGlobalToLocal( scheduleType ) : scheduleType; int result = TranslateSchedule( localId ); return result; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeGetSchedule( int localScheduleID, CAI_Schedule **ppResult ) { *ppResult = GetSchedule( localScheduleID ); return (*ppResult != NULL ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeTaskName( int taskID, const char **ppResult ) { if ( AI_IdIsLocal( taskID ) ) { *ppResult = GetSchedulingSymbols()->TaskIdToSymbol( GetClassScheduleIdSpace()->TaskLocalToGlobal( taskID ) ); return (*ppResult != NULL ); } return false; } //------------------------------------- inline Activity CAI_BehaviorBase::BridgeNPC_TranslateActivity( Activity activity ) { return NPC_TranslateActivity( activity ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsCurTaskContinuousMove( bool *pResult ) { bool fPrevOverride = m_fOverrode; m_fOverrode = true; *pResult = IsCurTaskContinuousMove(); bool result = m_fOverrode; m_fOverrode = fPrevOverride; return result; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeFValidateHintType( CAI_Hint *pHint, bool *pResult ) { bool fPrevOverride = m_fOverrode; m_fOverrode = true; *pResult = FValidateHintType( pHint ); bool result = m_fOverrode; m_fOverrode = fPrevOverride; return result; } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsValidEnemy( CBaseEntity *pEnemy ) { return IsValidEnemy( pEnemy ); } //------------------------------------- inline CBaseEntity *CAI_BehaviorBase::BridgeBestEnemy() { return BestEnemy(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsValidCover( const Vector &vLocation, CAI_Hint const *pHint ) { return IsValidCover( vLocation, pHint ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ) { return IsValidShootPosition( vLocation, pNode, pHint ); } //------------------------------------- inline float CAI_BehaviorBase::BridgeGetMaxTacticalLateralMovement( void ) { return GetMaxTacticalLateralMovement(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeShouldIgnoreSound( CSound *pSound ) { return ShouldIgnoreSound( pSound ); } //------------------------------------- inline void CAI_BehaviorBase::BridgeOnSeeEntity( CBaseEntity *pEntity ) { OnSeeEntity( pEntity ); } //------------------------------------- inline void CAI_BehaviorBase::BridgeOnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ) { OnFriendDamaged( pSquadmate, pAttacker ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsInterruptable( void ) { return IsInterruptable(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsNavigationUrgent( void ) { return IsNavigationUrgent(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeCanFlinch( void ) { return CanFlinch(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsCrouching( void ) { return IsCrouching(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeIsCrouchedActivity( Activity activity ) { return IsCrouchedActivity( activity ); } inline bool CAI_BehaviorBase::BridgeQueryHearSound( CSound *pSound ) { return QueryHearSound( pSound ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeCanRunAScriptedNPCInteraction( bool bForced ) { return CanRunAScriptedNPCInteraction( bForced ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeShouldPlayerAvoid( void ) { return ShouldPlayerAvoid(); } //------------------------------------- inline int CAI_BehaviorBase::BridgeOnTakeDamage_Alive( const CTakeDamageInfo &info ) { return OnTakeDamage_Alive( info ); } //------------------------------------- inline float CAI_BehaviorBase::BridgeGetReasonableFacingDist( void ) { return GetReasonableFacingDist(); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeShouldAlwaysThink( bool *pResult ) { bool fPrevOverride = m_fOverrode; m_fOverrode = true; *pResult = ShouldAlwaysThink(); bool result = m_fOverrode; m_fOverrode = fPrevOverride; return result; } //------------------------------------- inline void CAI_BehaviorBase::BridgeOnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon ) { OnChangeActiveWeapon( pOldWeapon, pNewWeapon ); } //------------------------------------- inline bool CAI_BehaviorBase::BridgeSpeakMapmakerInterruptConcept( string_t iszConcept ) { return SpeakMapmakerInterruptConcept( iszConcept ); } //------------------------------------- inline void CAI_BehaviorBase::BridgeOnRestore() { OnRestore(); } //------------------------------------- inline float CAI_BehaviorBase::BridgeGetDefaultNavGoalTolerance() { return GetDefaultNavGoalTolerance(); } //----------------------------------------------------------------------------- inline Activity CAI_BehaviorBase::BridgeGetFlinchActivity( bool bHeavyDamage, bool bGesture ) { return GetFlinchActivity( bHeavyDamage, bGesture ); } //----------------------------------------------------------------------------- inline bool CAI_BehaviorBase::BridgeOnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ) { return OnCalcBaseMove( pMoveGoal, distClear, pResult ); } //----------------------------------------------------------------------------- inline void CAI_BehaviorBase::BridgeModifyOrAppendCriteria( AI_CriteriaSet& criteriaSet ) { ModifyOrAppendCriteria( criteriaSet ); } //----------------------------------------------------------------------------- inline void CAI_BehaviorBase::BridgeTeleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) { Teleport( newPosition, newAngles, newVelocity ); } //----------------------------------------------------------------------------- inline void CAI_BehaviorBase::BridgeHandleAnimEvent( animevent_t *pEvent ) { HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::CleanupOnDeath( CBaseEntity *pCulprit, bool bFireDeathOutput ) { DeferSchedulingToBehavior( NULL ); for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeCleanupOnDeath( pCulprit, bFireDeathOutput ); } BaseClass::CleanupOnDeath( pCulprit, bFireDeathOutput ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::GatherConditions() { // Iterate over behaviors and call GatherConditionsNotActive() on each behavior // not currently active. for( int i = 0; i < m_Behaviors.Count(); i++ ) { if( m_Behaviors[i] != m_pCurBehavior ) { m_Behaviors[i]->GatherConditionsNotActive(); } } if ( m_pCurBehavior ) m_pCurBehavior->BridgeGatherConditions(); else BaseClass::GatherConditions(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_GatherConditions() { if ( g_bBehaviorHost_PreventBaseClassGatherConditions ) return; BaseClass::GatherConditions(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnScheduleChange() { if ( m_pCurBehavior ) m_pCurBehavior->BridgeOnScheduleChange(); BaseClass::OnScheduleChange(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnStartSchedule( int scheduleType ) { if ( m_pCurBehavior ) m_pCurBehavior->BridgeOnStartSchedule( scheduleType ); BaseClass::OnStartSchedule( scheduleType ); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::BackBridge_SelectSchedule() { return BaseClass::SelectSchedule(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BehaviorSelectSchedule() { for ( int i = 0; i < m_Behaviors.Count(); i++ ) { if ( m_Behaviors[i]->CanSelectSchedule() && ShouldBehaviorSelectSchedule( m_Behaviors[i] ) ) { DeferSchedulingToBehavior( m_Behaviors[i] ); return true; } } DeferSchedulingToBehavior( NULL ); return false; } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsRunningBehavior() const { return ( m_pCurBehavior != NULL ); } //------------------------------------- template <class BASE_NPC> inline CAI_BehaviorBase *CAI_BehaviorHost<BASE_NPC>::GetRunningBehavior() { return m_pCurBehavior; } //------------------------------------- template <class BASE_NPC> inline CAI_Schedule *CAI_BehaviorHost<BASE_NPC>::GetNewSchedule() { m_bCalledBehaviorSelectSchedule = false; CAI_Schedule *pResult = BaseClass::GetNewSchedule(); if ( !m_bCalledBehaviorSelectSchedule && m_pCurBehavior ) DeferSchedulingToBehavior( NULL ); return pResult; } //------------------------------------- template <class BASE_NPC> inline CAI_Schedule *CAI_BehaviorHost<BASE_NPC>::GetFailSchedule() { m_bCalledBehaviorSelectSchedule = false; CAI_Schedule *pResult = BaseClass::GetFailSchedule(); if ( !m_bCalledBehaviorSelectSchedule && m_pCurBehavior ) DeferSchedulingToBehavior( NULL ); return pResult; } //------------------------------------ template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::ChangeBehaviorTo( CAI_BehaviorBase *pNewBehavior ) { bool change = ( m_pCurBehavior != pNewBehavior ); CAI_BehaviorBase *pOldBehavior = m_pCurBehavior; m_pCurBehavior = pNewBehavior; if ( change ) { if ( m_pCurBehavior ) { m_pCurBehavior->BeginScheduleSelection(); g_bBehaviorHost_PreventBaseClassGatherConditions = true; m_pCurBehavior->GatherConditions(); g_bBehaviorHost_PreventBaseClassGatherConditions = false; } if ( pOldBehavior ) { pOldBehavior->EndScheduleSelection(); this->VacateStrategySlot(); } OnChangeRunningBehavior( pOldBehavior, pNewBehavior ); } } //------------------------------------- template <class BASE_NPC> inline CAI_BehaviorBase *CAI_BehaviorHost<BASE_NPC>::DeferSchedulingToBehavior( CAI_BehaviorBase *pNewBehavior ) { CAI_BehaviorBase *pOldBehavior = m_pCurBehavior; ChangeBehaviorTo( pNewBehavior ); return pOldBehavior; } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::BackBridge_TranslateSchedule( int scheduleType ) { return BaseClass::TranslateSchedule( scheduleType ); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::TranslateSchedule( int scheduleType ) { if ( m_pCurBehavior ) { return m_pCurBehavior->BridgeTranslateSchedule( scheduleType ); } return BaseClass::TranslateSchedule( scheduleType ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::PrescheduleThink() { BaseClass::PrescheduleThink(); if ( m_pCurBehavior ) m_pCurBehavior->BridgePrescheduleThink(); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::SelectSchedule() { m_bCalledBehaviorSelectSchedule = true; if ( m_pCurBehavior ) { return m_pCurBehavior->BridgeSelectSchedule(); } return BaseClass::SelectSchedule(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::KeepRunningBehavior() { if ( m_pCurBehavior ) m_bCalledBehaviorSelectSchedule = true; } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ) { m_bCalledBehaviorSelectSchedule = true; int result = 0; if ( m_pCurBehavior && m_pCurBehavior->BridgeSelectFailSchedule( failedSchedule, failedTask, taskFailCode, &result ) ) return result; return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::StartTask( const Task_t *pTask ) { if ( m_pCurBehavior && m_pCurBehavior->BridgeStartTask( pTask ) ) return; BaseClass::StartTask( pTask ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::RunTask( const Task_t *pTask ) { if ( m_pCurBehavior && m_pCurBehavior->BridgeRunTask( pTask ) ) return; BaseClass::RunTask( pTask ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::AimGun( void ) { if ( m_pCurBehavior && m_pCurBehavior->BridgeAimGun() ) return; BaseClass::AimGun(); } //------------------------------------- template <class BASE_NPC> inline CAI_Schedule *CAI_BehaviorHost<BASE_NPC>::GetSchedule(int localScheduleID) { CAI_Schedule *pResult; if ( m_pCurBehavior && m_pCurBehavior->BridgeGetSchedule( localScheduleID, &pResult ) ) return pResult; return BaseClass::GetSchedule( localScheduleID ); } //------------------------------------- template <class BASE_NPC> inline const char *CAI_BehaviorHost<BASE_NPC>::TaskName(int taskID) { const char *pszResult = NULL; if ( m_pCurBehavior && m_pCurBehavior->BridgeTaskName( taskID, &pszResult ) ) return pszResult; return BaseClass::TaskName( taskID ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BuildScheduleTestBits() { if ( m_pCurBehavior ) m_pCurBehavior->BridgeBuildScheduleTestBits(); BaseClass::BuildScheduleTestBits(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnChangeHintGroup( string_t oldGroup, string_t newGroup ) { for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeOnChangeHintGroup( oldGroup, newGroup ); } BaseClass::OnChangeHintGroup( oldGroup, newGroup ); } //------------------------------------- template <class BASE_NPC> inline Activity CAI_BehaviorHost<BASE_NPC>::BackBridge_NPC_TranslateActivity( Activity activity ) { return BaseClass::NPC_TranslateActivity( activity ); } //------------------------------------- template <class BASE_NPC> inline Activity CAI_BehaviorHost<BASE_NPC>::NPC_TranslateActivity( Activity activity ) { if ( m_pCurBehavior ) { return m_pCurBehavior->BridgeNPC_TranslateActivity( activity ); } return BaseClass::NPC_TranslateActivity( activity ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsCurTaskContinuousMove() { bool result = false; if ( m_pCurBehavior && m_pCurBehavior->BridgeIsCurTaskContinuousMove( &result ) ) return result; return BaseClass::IsCurTaskContinuousMove(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnMovementFailed() { if ( m_pCurBehavior ) m_pCurBehavior->BridgeOnMovementFailed(); BaseClass::OnMovementFailed(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnMovementComplete() { if ( m_pCurBehavior ) m_pCurBehavior->BridgeOnMovementComplete(); BaseClass::OnMovementComplete(); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::GetDefaultNavGoalTolerance() { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeGetDefaultNavGoalTolerance(); return BaseClass::GetDefaultNavGoalTolerance(); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::BackBridge_GetDefaultNavGoalTolerance() { return BaseClass::GetDefaultNavGoalTolerance(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::FValidateHintType( CAI_Hint *pHint ) { bool result = false; if ( m_pCurBehavior && m_pCurBehavior->BridgeFValidateHintType( pHint, &result ) ) return result; return BaseClass::FValidateHintType( pHint ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsValidEnemy(CBaseEntity *pEnemy) { return BaseClass::IsValidEnemy( pEnemy ); } //------------------------------------- template <class BASE_NPC> inline CBaseEntity *CAI_BehaviorHost<BASE_NPC>::BackBridge_BestEnemy(void) { return BaseClass::BestEnemy(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ) { return BaseClass::IsValidCover( vLocation, pHint ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ) { return BaseClass::IsValidShootPosition( vLocation, pNode, pHint ); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::BackBridge_GetMaxTacticalLateralMovement( void ) { return BaseClass::GetMaxTacticalLateralMovement(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_ShouldIgnoreSound( CSound *pSound ) { return BaseClass::ShouldIgnoreSound( pSound ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_OnSeeEntity( CBaseEntity *pEntity ) { BaseClass::OnSeeEntity( pEntity ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ) { BaseClass::OnFriendDamaged( pSquadmate, pAttacker ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsInterruptable( void ) { return BaseClass::IsInterruptable(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsNavigationUrgent( void ) { return BaseClass::IsNavigationUrgent(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_CanFlinch( void ) { return BaseClass::CanFlinch(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsCrouching( void ) { return BaseClass::IsCrouching(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_IsCrouchedActivity( Activity activity ) { return BaseClass::IsCrouchedActivity( activity ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_QueryHearSound( CSound *pSound ) { return BaseClass::QueryHearSound( pSound ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_CanRunAScriptedNPCInteraction( bool bForced ) { return BaseClass::CanRunAScriptedNPCInteraction( bForced ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_ShouldPlayerAvoid( void ) { return BaseClass::ShouldPlayerAvoid(); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::BackBridge_OnTakeDamage_Alive( const CTakeDamageInfo &info ) { return BaseClass::OnTakeDamage_Alive( info ); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::BackBridge_GetReasonableFacingDist( void ) { return BaseClass::GetReasonableFacingDist(); } //------------------------------------- template <class BASE_NPC> inline Activity CAI_BehaviorHost<BASE_NPC>::BackBridge_GetFlinchActivity( bool bHeavyDamage, bool bGesture ) { return BaseClass::GetFlinchActivity( bHeavyDamage, bGesture ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::BackBridge_OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ) { return BaseClass::OnCalcBaseMove( pMoveGoal, distClear, pResult ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_ModifyOrAppendCriteria( AI_CriteriaSet &criteriaSet ) { BaseClass::ModifyOrAppendCriteria( criteriaSet ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) { BaseClass::Teleport( newPosition, newAngles, newVelocity ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::BackBridge_HandleAnimEvent( animevent_t *pEvent ) { BaseClass::HandleAnimEvent( pEvent ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsValidEnemy( CBaseEntity *pEnemy ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsValidEnemy( pEnemy ); return BaseClass::IsValidEnemy( pEnemy ); } //------------------------------------- template <class BASE_NPC> inline CBaseEntity *CAI_BehaviorHost<BASE_NPC>::BestEnemy() { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeBestEnemy(); return BaseClass::BestEnemy(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::ShouldAlwaysThink() { bool result = false; if ( m_pCurBehavior && m_pCurBehavior->BridgeShouldAlwaysThink( &result ) ) return result; return BaseClass::ShouldAlwaysThink(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon ) { for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeOnChangeActiveWeapon( pOldWeapon, pNewWeapon ); } BaseClass::OnChangeActiveWeapon( pOldWeapon, pNewWeapon ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::SpeakMapmakerInterruptConcept( string_t iszConcept ) { for( int i = 0; i < m_Behaviors.Count(); i++ ) { if ( m_Behaviors[i]->BridgeSpeakMapmakerInterruptConcept( iszConcept ) ) return true; } return false; } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnRestore() { for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeOnRestore(); } BaseClass::OnRestore(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsValidCover( const Vector &vLocation, CAI_Hint const *pHint ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsValidCover( vLocation, pHint ); return BaseClass::IsValidCover( vLocation, pHint ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsValidShootPosition( vLocation, pNode, pHint ); return BaseClass::IsValidShootPosition( vLocation, pNode, pHint ); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::GetMaxTacticalLateralMovement( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeGetMaxTacticalLateralMovement(); return BaseClass::GetMaxTacticalLateralMovement(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::ShouldIgnoreSound( CSound *pSound ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeShouldIgnoreSound( pSound ); return BaseClass::ShouldIgnoreSound( pSound ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnSeeEntity( CBaseEntity *pEntity ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeOnSeeEntity( pEntity ); BaseClass::OnSeeEntity( pEntity ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeOnFriendDamaged( pSquadmate, pAttacker ); BaseClass::OnFriendDamaged( pSquadmate, pAttacker ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsInterruptable( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsInterruptable(); return BaseClass::IsInterruptable(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsNavigationUrgent( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsNavigationUrgent(); return BaseClass::IsNavigationUrgent(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::CanFlinch( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeCanFlinch(); return BaseClass::CanFlinch(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsCrouching( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsCrouching(); return BaseClass::IsCrouching(); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::IsCrouchedActivity( Activity activity ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeIsCrouchedActivity( activity ); return BaseClass::IsCrouchedActivity( activity ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::QueryHearSound( CSound *pSound ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeQueryHearSound( pSound ); return BaseClass::QueryHearSound( pSound ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::CanRunAScriptedNPCInteraction( bool bForced ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeCanRunAScriptedNPCInteraction( bForced ); return BaseClass::CanRunAScriptedNPCInteraction( bForced ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::ShouldPlayerAvoid( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeShouldPlayerAvoid(); return BaseClass::ShouldPlayerAvoid(); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeOnTakeDamage_Alive( info ); return BaseClass::OnTakeDamage_Alive( info ); } //------------------------------------- template <class BASE_NPC> inline float CAI_BehaviorHost<BASE_NPC>::GetReasonableFacingDist( void ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeGetReasonableFacingDist(); return BaseClass::GetReasonableFacingDist(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::Precache() { BaseClass::Precache(); for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgePrecache(); } } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::ScheduledMoveToGoalEntity( int scheduleType, CBaseEntity *pGoalEntity, Activity movementActivity ) { // If a behavior is active, we need to stop running it ChangeBehaviorTo( NULL ); return BaseClass::ScheduledMoveToGoalEntity( scheduleType, pGoalEntity, movementActivity ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::ScheduledFollowPath( int scheduleType, CBaseEntity *pPathStart, Activity movementActivity ) { // If a behavior is active, we need to stop running it ChangeBehaviorTo( NULL ); return BaseClass::ScheduledFollowPath( scheduleType, pPathStart, movementActivity ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::ForceSelectedGo(CBaseEntity *pPlayer, const Vector &targetPos, const Vector &traceDir, bool bRun) { // If a behavior is active, we need to stop running it ChangeBehaviorTo( NULL ); BaseClass::ForceSelectedGo(pPlayer, targetPos, traceDir, bRun); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::ForceSelectedGoRandom(void) { // If a behavior is active, we need to stop running it ChangeBehaviorTo( NULL ); BaseClass::ForceSelectedGoRandom(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::NPCInit() { BaseClass::NPCInit(); for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeSpawn(); } } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::UpdateOnRemove() { for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeUpdateOnRemove(); } BaseClass::UpdateOnRemove(); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::Event_Killed( const CTakeDamageInfo &info ) { for( int i = 0; i < m_Behaviors.Count(); i++ ) { m_Behaviors[i]->BridgeEvent_Killed( info ); } BaseClass::Event_Killed( info ); } //------------------------------------- template <class BASE_NPC> inline Activity CAI_BehaviorHost<BASE_NPC>::GetFlinchActivity( bool bHeavyDamage, bool bGesture ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeGetFlinchActivity( bHeavyDamage, bGesture ); return BaseClass::GetFlinchActivity( bHeavyDamage, bGesture ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeOnCalcBaseMove( pMoveGoal, distClear, pResult ); return BaseClass::OnCalcBaseMove( pMoveGoal, distClear, pResult ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::ModifyOrAppendCriteria( AI_CriteriaSet &criteriaSet ) { BaseClass::ModifyOrAppendCriteria( criteriaSet ); if ( m_pCurBehavior ) { // Append active behavior name criteriaSet.AppendCriteria( "active_behavior", GetRunningBehavior()->GetName() ); m_pCurBehavior->BridgeModifyOrAppendCriteria( criteriaSet ); return; } } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) { if ( m_pCurBehavior ) { m_pCurBehavior->BridgeTeleport( newPosition, newAngles, newVelocity ); return; } BaseClass::Teleport( newPosition, newAngles, newVelocity ); } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::HandleAnimEvent( animevent_t *pEvent ) { if ( m_pCurBehavior ) return m_pCurBehavior->BridgeHandleAnimEvent( pEvent ); return BaseClass::HandleAnimEvent( pEvent ); } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::OnBehaviorChangeStatus( CAI_BehaviorBase *pBehavior, bool fCanFinishSchedule ) { if ( pBehavior == GetRunningBehavior() && !pBehavior->CanSelectSchedule() && !fCanFinishSchedule ) { DeferSchedulingToBehavior( NULL ); return true; } return false; } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::OnChangeRunningBehavior( CAI_BehaviorBase *pOldBehavior, CAI_BehaviorBase *pNewBehavior ) { } //------------------------------------- template <class BASE_NPC> inline void CAI_BehaviorHost<BASE_NPC>::AddBehavior( CAI_BehaviorBase *pBehavior ) { #ifdef DEBUG Assert( m_Behaviors.Find( pBehavior ) == m_Behaviors.InvalidIndex() ); Assert( m_fDebugInCreateBehaviors ); for ( int i = 0; i < m_Behaviors.Count(); i++) { Assert( typeid(*m_Behaviors[i]) != typeid(*pBehavior) ); } #endif m_Behaviors.AddToTail( pBehavior ); pBehavior->SetOuter( this ); pBehavior->SetBackBridge( this ); } //------------------------------------- template <class BASE_NPC> inline CAI_BehaviorBase **CAI_BehaviorHost<BASE_NPC>::AccessBehaviors() { if (m_Behaviors.Count()) return m_Behaviors.Base(); return NULL; } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::NumBehaviors() { return m_Behaviors.Count(); } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::Save( ISave &save ) { int result = BaseClass::Save( save ); if ( result ) CAI_BehaviorBase::SaveBehaviors( save, m_pCurBehavior, AccessBehaviors(), NumBehaviors() ); return result; } //------------------------------------- template <class BASE_NPC> inline int CAI_BehaviorHost<BASE_NPC>::Restore( IRestore &restore ) { int result = BaseClass::Restore( restore ); if ( result ) { int iCurrent = CAI_BehaviorBase::RestoreBehaviors( restore, AccessBehaviors(), NumBehaviors() ); if ( iCurrent != -1 ) m_pCurBehavior = AccessBehaviors()[iCurrent]; else m_pCurBehavior = NULL; } return result; } //------------------------------------- template <class BASE_NPC> inline bool CAI_BehaviorHost<BASE_NPC>::CreateComponents() { if ( BaseClass::CreateComponents() ) { #ifdef DEBUG m_fDebugInCreateBehaviors = true; #endif bool result = CreateBehaviors(); #ifdef DEBUG m_fDebugInCreateBehaviors = false; #endif return result; } return false; } //----------------------------------------------------------------------------- #endif // AI_BEHAVIOR_H
0
0.97203
1
0.97203
game-dev
MEDIA
0.917818
game-dev
0.645381
1
0.645381
Joshhhuaaa/EnhancedSC
1,334
UnrealScript/Echelon/Classes/EDispatcher.uc
//============================================================================= // EDispatcher: receives one trigger (corresponding to its name) as input, // then triggers a set of specifid events with optional delays. //============================================================================= class EDispatcher extends Triggers; #exec Texture Import File=..\Engine\Textures\Echelon\Dispatch.pcx Name=S_Dispatcher Mips=Off Flags=2 NOCONSOLE //----------------------------------------------------------------------------- // EDispatcher variables. var() name OutEvents[8]; // Events to generate. var() float OutDelays[8]; // Relative delays before generating events. var int i; // Internal counter. //============================================================================= // EDispatcher logic. // // When EDispatcher is triggered... // function Trigger( actor Other, pawn EventInstigator, optional name InTag ) { Instigator = EventInstigator; gotostate('Dispatch'); } // // Dispatch events. // state Dispatch { ignores trigger; Begin: for( i=0; i<ArrayCount(OutEvents); i++ ) { if( (OutEvents[i] != '') && (OutEvents[i] != 'None') ) { Sleep( OutDelays[i] ); TriggerEvent(OutEvents[i],self,Instigator); } } GotoState(''); } defaultproperties { Texture=Texture'S_Dispatcher' }
0
0.961857
1
0.961857
game-dev
MEDIA
0.939965
game-dev
0.893643
1
0.893643
cjcliffe/CubicVR
5,454
cubicvr/external/bullet-2.78/src/BulletDynamics/ConstraintSolver/btJacobianEntry.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_JACOBIAN_ENTRY_H #define BT_JACOBIAN_ENTRY_H #include "LinearMath/btVector3.h" #include "BulletDynamics/Dynamics/btRigidBody.h" //notes: // Another memory optimization would be to store m_1MinvJt in the remaining 3 w components // which makes the btJacobianEntry memory layout 16 bytes // if you only are interested in angular part, just feed massInvA and massInvB zero /// Jacobian entry is an abstraction that allows to describe constraints /// it can be used in combination with a constraint solver /// Can be used to relate the effect of an impulse to the constraint error ATTRIBUTE_ALIGNED16(class) btJacobianEntry { public: btJacobianEntry() {}; //constraint between two different rigidbodies btJacobianEntry( const btMatrix3x3& world2A, const btMatrix3x3& world2B, const btVector3& rel_pos1,const btVector3& rel_pos2, const btVector3& jointAxis, const btVector3& inertiaInvA, const btScalar massInvA, const btVector3& inertiaInvB, const btScalar massInvB) :m_linearJointAxis(jointAxis) { m_aJ = world2A*(rel_pos1.cross(m_linearJointAxis)); m_bJ = world2B*(rel_pos2.cross(-m_linearJointAxis)); m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ); btAssert(m_Adiag > btScalar(0.0)); } //angular constraint between two different rigidbodies btJacobianEntry(const btVector3& jointAxis, const btMatrix3x3& world2A, const btMatrix3x3& world2B, const btVector3& inertiaInvA, const btVector3& inertiaInvB) :m_linearJointAxis(btVector3(btScalar(0.),btScalar(0.),btScalar(0.))) { m_aJ= world2A*jointAxis; m_bJ = world2B*-jointAxis; m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); btAssert(m_Adiag > btScalar(0.0)); } //angular constraint between two different rigidbodies btJacobianEntry(const btVector3& axisInA, const btVector3& axisInB, const btVector3& inertiaInvA, const btVector3& inertiaInvB) : m_linearJointAxis(btVector3(btScalar(0.),btScalar(0.),btScalar(0.))) , m_aJ(axisInA) , m_bJ(-axisInB) { m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); btAssert(m_Adiag > btScalar(0.0)); } //constraint on one rigidbody btJacobianEntry( const btMatrix3x3& world2A, const btVector3& rel_pos1,const btVector3& rel_pos2, const btVector3& jointAxis, const btVector3& inertiaInvA, const btScalar massInvA) :m_linearJointAxis(jointAxis) { m_aJ= world2A*(rel_pos1.cross(jointAxis)); m_bJ = world2A*(rel_pos2.cross(-jointAxis)); m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = btVector3(btScalar(0.),btScalar(0.),btScalar(0.)); m_Adiag = massInvA + m_0MinvJt.dot(m_aJ); btAssert(m_Adiag > btScalar(0.0)); } btScalar getDiagonal() const { return m_Adiag; } // for two constraints on the same rigidbody (for example vehicle friction) btScalar getNonDiagonal(const btJacobianEntry& jacB, const btScalar massInvA) const { const btJacobianEntry& jacA = *this; btScalar lin = massInvA * jacA.m_linearJointAxis.dot(jacB.m_linearJointAxis); btScalar ang = jacA.m_0MinvJt.dot(jacB.m_aJ); return lin + ang; } // for two constraints on sharing two same rigidbodies (for example two contact points between two rigidbodies) btScalar getNonDiagonal(const btJacobianEntry& jacB,const btScalar massInvA,const btScalar massInvB) const { const btJacobianEntry& jacA = *this; btVector3 lin = jacA.m_linearJointAxis * jacB.m_linearJointAxis; btVector3 ang0 = jacA.m_0MinvJt * jacB.m_aJ; btVector3 ang1 = jacA.m_1MinvJt * jacB.m_bJ; btVector3 lin0 = massInvA * lin ; btVector3 lin1 = massInvB * lin; btVector3 sum = ang0+ang1+lin0+lin1; return sum[0]+sum[1]+sum[2]; } btScalar getRelativeVelocity(const btVector3& linvelA,const btVector3& angvelA,const btVector3& linvelB,const btVector3& angvelB) { btVector3 linrel = linvelA - linvelB; btVector3 angvela = angvelA * m_aJ; btVector3 angvelb = angvelB * m_bJ; linrel *= m_linearJointAxis; angvela += angvelb; angvela += linrel; btScalar rel_vel2 = angvela[0]+angvela[1]+angvela[2]; return rel_vel2 + SIMD_EPSILON; } //private: btVector3 m_linearJointAxis; btVector3 m_aJ; btVector3 m_bJ; btVector3 m_0MinvJt; btVector3 m_1MinvJt; //Optimization: can be stored in the w/last component of one of the vectors btScalar m_Adiag; }; #endif //BT_JACOBIAN_ENTRY_H
0
0.838859
1
0.838859
game-dev
MEDIA
0.981052
game-dev
0.985188
1
0.985188
soyeonm/FILM
2,952
alfred_utils/gen/agents/semantic_map_planner_agent.py
import glob import cv2 import constants from agents.agent_base import AgentBase from agents.plan_agent import PlanAgent from game_states.planned_game_state import PlannedGameState class SemanticMapPlannerAgent(AgentBase): def __init__(self, thread_id=0, game_state=None): assert(isinstance(game_state, PlannedGameState)) super(SemanticMapPlannerAgent, self).__init__(thread_id, game_state) self.plan_agent = PlanAgent(thread_id, game_state, self) self.planning = False def reset(self, seed=None, info=None, scene=None, objs=None): self.planning = False info = self.game_state.get_setup_info(info, scene=scene)[0] super(SemanticMapPlannerAgent, self).reset({'seed': seed, 'info': info}, scene=scene, objs=objs) if self.plan_agent is not None: self.plan_agent.reset() return info def setup_problem(self, game_state_problem_args, scene=None, objs=None): super(SemanticMapPlannerAgent, self).setup_problem(game_state_problem_args, scene=scene, objs=objs) self.pose = self.game_state.pose def get_reward(self): raise NotImplementedError def step(self, action, executing_plan=False): if action['action'] == 'End': self.current_frame_count += 1 self.total_frame_count += 1 self.terminal = True if constants.RECORD_VIDEO_IMAGES: im_ind = len(glob.glob(constants.save_path + '/*.png')) for _ in range(10): cv2.imwrite(constants.save_path + '/%09d.png' % im_ind, self.game_state.s_t[:, :, ::-1]) im_ind += 1 else: if 'Teleport' in action['action']: start_pose = self.pose end_angle = action['horizon'] end_pose = (int(action['x'] / constants.AGENT_STEP_SIZE), int(action['z'] / constants.AGENT_STEP_SIZE), int(action['rotation'] / 90), int(end_angle)) self.game_state.gt_graph.navigate_to_goal(self.game_state, start_pose, end_pose) self.pose = self.game_state.pose elif action['action'] == 'Plan': self.plan_agent.execute_plan() if not constants.EVAL: self.current_frame_count += 1 self.total_frame_count += 1 elif action['action'] == 'Scan': self.game_state.step(action) if not constants.EVAL: self.current_frame_count += 1 self.total_frame_count += 1 elif action['action'] == 'Explore': if not constants.EVAL: self.current_frame_count += 1 self.total_frame_count += 1 else: super(SemanticMapPlannerAgent, self).step(action)
0
0.575052
1
0.575052
game-dev
MEDIA
0.749266
game-dev,ml-ai
0.924134
1
0.924134
open-toontown/open-toontown
5,704
toontown/cogdominium/CogdoGameExit.py
from panda3d.core import NodePath, Point3 from direct.interval.MetaInterval import Parallel, Sequence from direct.interval.SoundInterval import SoundInterval from direct.interval.FunctionInterval import Wait, Func from toontown.building import ElevatorConstants from toontown.building import ElevatorUtils from . import CogdoUtil from . import CogdoGameConsts class CogdoGameExit(NodePath): def __init__(self, openSfx = None, closeSfx = None): NodePath.__init__(self, 'CogdoGameExit') self._model = CogdoUtil.loadModel('exitDoor') self._model.reparentTo(self) self._leftDoor = self._model.find('**/left_door') self._rightDoor = self._model.find('**/right_door') self._openSfx = openSfx or base.loader.loadSfx('phase_9/audio/sfx/CHQ_VP_door_open.ogg') self._closeSfx = closeSfx or base.loader.loadSfx('phase_9/audio/sfx/CHQ_VP_door_close.ogg') self._elevatorPoints = [] for point in ElevatorConstants.ElevatorPoints: self._elevatorPoints.append(point[0]) self._currentSlot = 0 self._ival = None self._open = True self._toon2track = {} self.close(animate=False) return def destroy(self): self._cleanToonTracks() if self._ival is not None: self._ival.clearToInitial() del self._ival self._model.removeNode() del self._leftDoor del self._rightDoor del self._model del self._openSfx del self._closeSfx del self._elevatorPoints return def isOpen(self): return self._open def uniqueName(self, name): return self.getName() + name def open(self, animate = True): if self._open: return if animate: self._finishIval() self._ival = Sequence(Parallel(SoundInterval(self._closeSfx), self._leftDoor.posInterval(self.getOpenCloseDuration(), ElevatorUtils.getLeftOpenPoint(ElevatorConstants.ELEVATOR_NORMAL), startPos=ElevatorUtils.getLeftClosePoint(ElevatorConstants.ELEVATOR_NORMAL), blendType='easeInOut'), self._rightDoor.posInterval(self.getOpenCloseDuration(), ElevatorUtils.getRightOpenPoint(ElevatorConstants.ELEVATOR_NORMAL), startPos=ElevatorUtils.getRightClosePoint(ElevatorConstants.ELEVATOR_NORMAL), blendType='easeInOut'))) self._ival.start() else: ElevatorUtils.openDoors(self._leftDoor, self._rightDoor, type=ElevatorConstants.ELEVATOR_NORMAL) self._open = True def getOpenCloseDuration(self): return CogdoGameConsts.ExitDoorMoveDuration def close(self, animate = True): if not self._open: return if animate: self._finishIval() self._ival = Sequence(Parallel(SoundInterval(self._closeSfx), self._leftDoor.posInterval(self.getOpenCloseDuration(), ElevatorUtils.getLeftClosePoint(ElevatorConstants.ELEVATOR_NORMAL), startPos=ElevatorUtils.getLeftOpenPoint(ElevatorConstants.ELEVATOR_NORMAL), blendType='easeIn'), self._rightDoor.posInterval(self.getOpenCloseDuration(), ElevatorUtils.getRightClosePoint(ElevatorConstants.ELEVATOR_NORMAL), startPos=ElevatorUtils.getRightOpenPoint(ElevatorConstants.ELEVATOR_NORMAL), blendType='easeIn'))) self._ival.start() else: ElevatorUtils.closeDoors(self._leftDoor, self._rightDoor, type=ElevatorConstants.ELEVATOR_NORMAL) self._open = False def _finishIval(self): if self._ival is not None and self._ival.isPlaying(): self._ival.finish() return def toonEnters(self, toon, goInside = True): self._runToonThroughSlot(toon, self._currentSlot, goInside=goInside) self._currentSlot += 1 if self._currentSlot > len(self._elevatorPoints): self._currentSlot = 0 def _runToonThroughSlot(self, toon, slot, goInside = True): helperNode = NodePath('helper') helperNode.reparentTo(toon.getParent()) helperNode.lookAt(self) lookAtH = helperNode.getH(self._model) toonH = toon.getH(self._model) hDiff = abs(lookAtH - toonH) distanceFromElev = toon.getDistance(self._model) moveSpeed = 9.778 anim = 'run' if toon.animFSM.getCurrentState() == 'Sad': moveSpeed *= 0.5 anim = 'sad-walk' runInsideDistance = 20 track = Sequence(Func(toon.stopSmooth), Func(toon.loop, anim, 1.0), Parallel(toon.hprInterval(hDiff / 360.0, Point3(lookAtH, 0, 0), other=self._model, blendType='easeIn'), toon.posInterval(distanceFromElev / moveSpeed, Point3(self._elevatorPoints[slot], 0, 0), other=self._model, blendType='easeIn')), name=toon.uniqueName('runThroughExit'), autoPause=1) if goInside: track.append(Parallel(toon.hprInterval(lookAtH / 360.0, Point3(0, 0, 0), other=self._model, blendType='easeOut'), toon.posInterval(runInsideDistance / moveSpeed, Point3(self._elevatorPoints[slot], runInsideDistance, 0), other=self._model, blendType='easeOut'))) track.append(Func(self._clearToonTrack, toon)) track.append(Func(toon.setAnimState, 'Happy', 1.0)) self._storeToonTrack(toon, track) track.start() def _cleanToonTracks(self): toons = [ toon for toon in self._toon2track ] for toon in toons: self._clearToonTrack(toon) def _clearToonTrack(self, toon): oldTrack = self._toon2track.get(toon) if oldTrack is not None: oldTrack.pause() del self._toon2track[toon] return def _storeToonTrack(self, toon, track): self._clearToonTrack(toon) self._toon2track[toon] = track
0
0.876167
1
0.876167
game-dev
MEDIA
0.499284
game-dev,desktop-app
0.976049
1
0.976049
projectPiki/pikmin2
71,238
src/utilityU/PSMainSide_ObjSound.cpp
#include "Game/Entities/PelletItem.h" #include "Game/Entities/PelletOtakara.h" #include "Game/Navi.h" #include "PSSystem/PSMainSide_ObjSound.h" #include "PSM/BossSeq.h" #include "PSM/EnemyBoss.h" #include "PSM/Tsuyukusa.h" #include "PSM/WorkItem.h" #include "PSM/ObjCalc.h" #include "PSM/CreaturePrm.h" #include "PSM/Navi.h" #include "PSMath.h" #include "utilityU.h" namespace PSM { EnemyBigBoss* EnemyBigBoss::sBigBoss; u8 Piki::sDopedPikminNum = 0; /** * @note Address: N/A * @note Size: 0x50 */ ObjBase::ObjBase() : JSULink<ObjBase>(this) { // UNUSED FUNCTION } /** * @note Address: 0x8045CE64 * @note Size: 0x80 */ ObjBase::~ObjBase() { } /** * @note Address: 0x8045CEE4 * @note Size: 0x4C */ void ObjMgr::frameEnd_onPlaySe() { FOREACH_NODE(JSULink<ObjBase>, mHead, link) { link->getObject()->frameEnd_onPlaySe(); } } /** * @note Address: 0x8045CF30 * @note Size: 0x104 */ ObjMgr::~ObjMgr() { if (mScenes) { mScenes->detachObjMgr(); } while (mHead) { JSULink<ObjBase>* link = (JSULink<ObjBase>*)mHead; ObjBase* obj = link->getObject(); remove(obj); delete obj; } sInstance = nullptr; } /** * @note Address: N/A * @note Size: 0xCC */ Creature::Creature(Game::Creature* gameObj) : mGameObj(gameObj) { P2ASSERTLINE(97, gameObj); P2ASSERTLINE(98, PSSystem::SingletonBase<ObjMgr>::sInstance); // UNUSED FUNCTION } /** * @note Address: N/A * @note Size: 0x3C */ bool Creature::isVisible() { // UNUSED FUNCTION } /** * @note Address: 0x8045D034 * @note Size: 0x58 */ void Creature::exec() { if (!mGameObj->sound_culling()) { onCalcOn(); } } /** * @note Address: 0x8045D08C * @note Size: 0x128 */ bool Creature::judgeNearWithPlayer(const Vec& pos1, const Vec& pos2, f32 near, f32 far) { return PSMath::calcDistanceInRange(pos1, pos2, near, far); } /** * @note Address: 0x8045D1B4 * @note Size: 0xA0 */ bool Creature::isNear(Game::Creature* obj, f32 near) { Vec* pos = (Vec*)mGameObj->getSound_PosPtr(); Vec* pos2 = (Vec*)obj->getSound_PosPtr(); return judgeNearWithPlayer(*pos, *pos2, near, near / 2); /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stfd f31, 0x10(r1) psq_st f31, 24(r1), 0, qr0 stw r31, 0xc(r1) stw r30, 8(r1) mr r30, r3 fmr f31, f1 lwz r3, 0x2c(r3) mr r31, r4 lwz r12, 0(r3) lwz r12, 0x100(r12) mtctr r12 bctrl mr r0, r3 mr r3, r31 lwz r12, 0(r31) mr r31, r0 lwz r12, 0x100(r12) mtctr r12 bctrl lwz r12, 0x28(r30) mr r5, r3 lfs f0, lbl_80520C54@sda21(r2) fmr f1, f31 lwz r12, 0x34(r12) mr r3, r30 fmuls f2, f31, f0 mr r4, r31 mtctr r12 bctrl psq_l f31, 24(r1), 0, qr0 lwz r0, 0x24(r1) lfd f31, 0x10(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /** * @note Address: 0x8045D254 * @note Size: 0x70 */ u8 Creature::getPlayingHandleNum() { JAInter::Object* jai = getJAIObject(); u8 num = 0; for (u8 i = 0; i < jai->mHandleCount; i++) { if (jai->mSounds[i]) { num++; } } return num; } /** * @note Address: 0x8045D2C4 * @note Size: 0x15C */ void Creature::loopCalc(FrameCalcArg& arg) { JAInter::Object* jai = arg.mObj->getJAIObject(); Vec& pos = jai->_28; f32& dist = *arg.mDist; P2ASSERTLINE(170, jai->_24); u8 players = PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this); PSMTXMultVec(*JAIBasic::msBasic->mCameras[players].mMtx, jai->_24, &pos); dist = pikmin2_sqrtf((pos.x * pos.x) + (pos.y * pos.y) + (pos.z * pos.z)); for (u8 i = 0; i < jai->mHandleCount; i++) { JAISound* se = jai->mSounds[i]; if (se) { JAISound_0x34* data = se->mSoundObj; data->mPosition = pos; data->mDistance = dist; static_cast<SeSound*>(se)->mPlayerNum = players; } } f32& pan = *arg.mPan; pan = SeSound::calcPan(pos, dist); f32& dolby = *arg.mDolby; dolby = SeSound::calcDolby(pos, dist); /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stmw r27, 0xc(r1) mr r27, r3 mr r28, r4 lwz r3, 0(r4) lwz r12, 0x28(r3) lwz r12, 0x24(r12) mtctr r12 bctrl mr r31, r3 lwz r29, 4(r28) lwz r0, 0x24(r3) addi r30, r31, 0x28 cmplwi r0, 0 bne lbl_8045D324 lis r3, lbl_8049CFA0@ha lis r5, lbl_8049CFB8@ha addi r3, r3, lbl_8049CFA0@l li r4, 0xaa addi r5, r5, lbl_8049CFB8@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8045D324: lwz r3, "sInstance__Q28PSSystem34SingletonBase<Q23PSM11ObjCalcBase>"@sda21(r13) mr r4, r27 lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl mr r27, r3 lwz r3, msBasic__8JAIBasic@sda21(r13) clrlwi r0, r27, 0x18 lwz r4, 0x24(r31) mulli r0, r0, 0xc lwz r3, 4(r3) mr r5, r30 add r3, r3, r0 lwz r3, 8(r3) bl PSMTXMultVec lfs f1, 0(r30) lfs f0, 4(r30) fmuls f1, f1, f1 lfs f2, 8(r30) fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl pikmin2_sqrtf__Ff stfs f1, 0(r29) li r5, 0 b lbl_8045D3D4 lbl_8045D394: lwz r3, 0x1c(r31) rlwinm r0, r5, 2, 0x16, 0x1d lwzx r3, r3, r0 cmplwi r3, 0 beq lbl_8045D3D0 lwz r4, 0x34(r3) lfs f0, 0(r30) stfs f0, 0(r4) lfs f0, 4(r30) stfs f0, 4(r4) lfs f0, 8(r30) stfs f0, 8(r4) lfs f0, 0(r29) stfs f0, 0x18(r4) stb r27, 0x49c(r3) lbl_8045D3D0: addi r5, r5, 1 lbl_8045D3D4: lbz r0, 0x19(r31) clrlwi r3, r5, 0x18 cmplw r3, r0 blt lbl_8045D394 lwz r27, 8(r28) mr r3, r30 lfs f1, 0(r29) bl calcPan__Q23PSM7SeSoundFRC3Vecf stfs f1, 0(r27) mr r3, r30 lwz r27, 0xc(r28) lfs f1, 0(r29) bl calcDolby__Q23PSM7SeSoundFRC3Vecf stfs f1, 0(r27) lmw r27, 0xc(r1) lwz r0, 0x24(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /** * @note Address: 0x8045D420 * @note Size: 0x380 */ JAISound* Creature::startSoundInner(PSM::StartSoundArg& arg) { if (mGameObj->sound_culling()) { return nullptr; } if (!static_cast<SceneBase*>(PSMGetSceneMgrCheck()->getEndScene())->getSeSceneGate(this, arg.mSoundID)) { return nullptr; } u32 sound = arg.mSoundID; u32 unk = arg._08; JAInter::Object* jai = arg.mObj->getJAIObject(); JAISound** temp = nullptr; if (!(sound & 0x800)) { temp = jai->getUseSoundHandlePointer(sound); } if (!temp) { temp = jai->getFreeSoundHandlePointer(); } if (temp) { JAInter::Actor actor(this, jai->_24, 0, 0); u8 players = PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this); JAIBasic::msBasic->startSoundActorT(sound, temp, &actor, unk, players); onPlayingSe(sound, *temp); if (*temp) { (*temp)->mIsPlayingWithActor = true; } return *temp; } else { u8 prio = 255; u8 id = 255; for (u8 i = 0; i < jai->mHandleCount; i++) { if (!((1 << i) & jai->mUseHandleFlag) && jai->mSounds[i]->mSoundInfo->mPriority <= prio) { id = i; prio = jai->mSounds[i]->mSoundInfo->mPriority; } } if (id == 255 || JAInter::SoundTable::getInfoPointer(sound)->mPriority >= prio) { return nullptr; } jai->handleStop(id, 0); JAInter::Actor actor(this, jai->_24, 0, 0); u8 players = PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this); JAIBasic::msBasic->startSoundActorT(sound, getHandleArea(id), &actor, unk, players); onPlayingSe(sound, *getHandleArea(id)); JAISound* se = jai->mSounds[id]; if (se) { se->mIsPlayingWithActor = true; } return se; } return nullptr; /* stwu r1, -0x50(r1) mflr r0 lis r5, lbl_8049CFA0@ha stw r0, 0x54(r1) stmw r25, 0x34(r1) mr r25, r3 mr r28, r4 addi r26, r5, lbl_8049CFA0@l lwz r3, 0x2c(r3) lwz r12, 0(r3) lwz r12, 0x104(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045D464 li r3, 0 b lbl_8045D78C lbl_8045D464: lwz r0, spSceneMgr__8PSSystem@sda21(r13) cmplwi r0, 0 bne lbl_8045D484 addi r3, r26, 0x30 addi r5, r26, 0x18 li r4, 0x1d3 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8045D484: lwz r27, spSceneMgr__8PSSystem@sda21(r13) cmplwi r27, 0 bne lbl_8045D4A4 addi r3, r26, 0x30 addi r5, r26, 0x18 li r4, 0x1dc crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8045D4A4: lwz r0, 8(r27) cmplwi r0, 0 bne lbl_8045D4C4 addi r3, r26, 0x3c addi r5, r26, 0x18 li r4, 0xa1 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8045D4C4: lwz r3, 8(r27) mr r4, r25 lwz r5, 4(r28) lwz r12, 0(r3) lwz r12, 0x38(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 bne lbl_8045D4F0 li r3, 0 b lbl_8045D78C lbl_8045D4F0: lwz r29, 0(r28) lwz r31, 4(r28) mr r3, r29 lwz r30, 8(r28) lwz r12, 0x28(r29) lwz r12, 0x24(r12) mtctr r12 bctrl rlwinm. r0, r31, 0, 0x14, 0x14 li r26, 0 mr r28, r3 bne lbl_8045D538 lwz r12, 0(r3) mr r4, r31 lwz r12, 0x30(r12) mtctr r12 bctrl mr r26, r3 lbl_8045D538: cmplwi r26, 0 bne lbl_8045D558 mr r3, r28 lwz r12, 0(r28) lwz r12, 0x2c(r12) mtctr r12 bctrl mr r26, r3 lbl_8045D558: cmplwi r26, 0 beq lbl_8045D604 cmplwi r29, 0 lwz r7, 0x24(r28) bne lbl_8045D574 mr r3, r7 b lbl_8045D578 lbl_8045D574: mr r3, r29 lbl_8045D578: li r6, -1 li r5, 0 li r0, 1 stw r3, 0x1c(r1) lwz r3, "sInstance__Q28PSSystem34SingletonBase<Q23PSM11ObjCalcBase>"@sda21(r13) mr r4, r25 stw r7, 0x20(r1) stw r6, 0x24(r1) stw r5, 0x28(r1) stb r0, 0x2c(r1) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl mr r8, r3 lwz r3, msBasic__8JAIBasic@sda21(r13) mr r4, r31 mr r5, r26 mr r7, r30 addi r6, r1, 0x1c bl "startSoundActorT<8JAISound>__8JAIBasicFUlPP8JAISoundPQ27JAInter5ActorUlUc" mr r3, r25 mr r4, r31 lwz r12, 0x28(r25) lwz r5, 0(r26) lwz r12, 0x38(r12) mtctr r12 bctrl lwz r3, 0(r26) cmplwi r3, 0 beq lbl_8045D5FC li r0, 1 stb r0, 0x1a(r3) lbl_8045D5FC: lwz r3, 0(r26) b lbl_8045D78C lbl_8045D604: lbz r6, 0x19(r28) li r27, 0xff li r26, 0xff li r7, 0 li r5, 1 b lbl_8045D65C lbl_8045D61C: clrlwi r3, r7, 0x18 lwz r0, 0x20(r28) slw r3, r5, r3 and. r0, r3, r0 bne lbl_8045D658 lwz r4, 0x1c(r28) rlwinm r3, r7, 2, 0x16, 0x1d clrlwi r0, r27, 0x18 lwzx r3, r4, r3 lwz r3, 0x44(r3) lbz r3, 4(r3) cmplw r3, r0 bgt lbl_8045D658 mr r27, r3 mr r26, r7 lbl_8045D658: addi r7, r7, 1 lbl_8045D65C: clrlwi r0, r7, 0x18 cmplw r0, r6 blt lbl_8045D61C clrlwi r0, r26, 0x18 cmplwi r0, 0xff beq lbl_8045D788 mr r3, r31 bl getInfoPointer__Q27JAInter10SoundTableFUl lbz r3, 4(r3) clrlwi r0, r27, 0x18 cmplw r3, r0 blt lbl_8045D788 mr r3, r28 mr r4, r26 lwz r12, 0(r28) li r5, 0 lwz r12, 0x34(r12) mtctr r12 bctrl cmplwi r29, 0 lwz r7, 0x24(r28) bne lbl_8045D6BC mr r3, r7 b lbl_8045D6C0 lbl_8045D6BC: mr r3, r29 lbl_8045D6C0: li r6, -1 li r5, 0 li r0, 1 stw r3, 8(r1) lwz r3, "sInstance__Q28PSSystem34SingletonBase<Q23PSM11ObjCalcBase>"@sda21(r13) mr r4, r25 stw r7, 0xc(r1) stw r6, 0x10(r1) stw r5, 0x14(r1) stb r0, 0x18(r1) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl lwz r12, 0x28(r25) mr r27, r3 mr r3, r25 mr r4, r26 lwz r12, 0x3c(r12) mtctr r12 bctrl mr r5, r3 lwz r3, msBasic__8JAIBasic@sda21(r13) mr r4, r31 mr r7, r30 mr r8, r27 addi r6, r1, 8 bl "startSoundActorT<8JAISound>__8JAIBasicFUlPP8JAISoundPQ27JAInter5ActorUlUc" mr r3, r25 mr r4, r26 lwz r12, 0x28(r25) lwz r12, 0x3c(r12) mtctr r12 bctrl mr r5, r3 mr r3, r25 lwz r12, 0x28(r25) mr r4, r31 lwz r5, 0(r5) lwz r12, 0x38(r12) mtctr r12 bctrl lwz r3, 0x1c(r28) rlwinm r0, r26, 2, 0x16, 0x1d lwzx r3, r3, r0 cmplwi r3, 0 beq lbl_8045D78C li r0, 1 stb r0, 0x1a(r3) b lbl_8045D78C lbl_8045D788: li r3, 0 lbl_8045D78C: lmw r25, 0x34(r1) lwz r0, 0x54(r1) mtlr r0 addi r1, r1, 0x50 blr */ } /** * @note Address: 0x8045D7A0 * @note Size: 0x4 */ void Creature::onPlayingSe(u32, JAISound*) { } /** * @note Address: 0x8045D7A4 * @note Size: 0x10C */ CreatureObj::CreatureObj(Game::Creature* gameObj, u8 p2) : Creature(gameObj) , JAInter::Object(reinterpret_cast<Vec*>(gameObj->getSound_PosPtr()), JKRGetCurrentHeap(), p2) { } /** * @note Address: 0x8045D948 * @note Size: 0x3C */ JAISound* CreatureObj::startSound(u32 soundID, u32 a2) { StartSoundArg arg(this, soundID, a2); return startSoundInner(arg); } /** * @note Address: 0x8045D984 * @note Size: 0x8C */ void CreatureObj::startSound(u8 id, u32 soundID, u32 a3) { u8 players = PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this); JAIBasic::msBasic->startSoundVecT(soundID, &mSounds[id], _24, a3, 0, players); } /** * @note Address: 0x8045DA10 * @note Size: 0xA8 */ void CreatureObj::startSound(JAISound** se, u32 soundID, u32 a3) { JUT_PANICLINE(395, "使用禁止再生関数"); // "Disabled playback functions" JAIBasic::msBasic->startSoundVecT(soundID, se, _24, a3, 0, PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this)); } /** * @note Address: 0x8045DAB8 * @note Size: 0x4C */ void CreatureObj::frameEnd_onPlaySe() { FrameCalcArg arg(this, &mDistance, &mPan, &mDolby); loopCalc(arg); } /** * @note Address: N/A * @note Size: 0x118 */ inline CreatureAnime::CreatureAnime(Game::Creature* gameObj, u8 p2) : Creature(gameObj) , JAIAnimeSound(reinterpret_cast<Vec*>(gameObj->getSound_PosPtr()), JKRGetCurrentHeap(), p2) , _AC(0.0f) , _B0(0.0f) { // UNUSED FUNCTION } /** * @note Address: 0x8045DB04 * @note Size: 0x148 */ void CreatureAnime::startAnimSound(u32 soundID, JAISound** se, JAInter::Actor* actor, u8) { if (mGameObj->sound_culling()) { return; } if (static_cast<SceneBase*>(PSMGetSceneMgrCheck()->getEndScene())->getSeSceneGate(this, soundID)) { actor->mObj = this; u8 players = PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this); JAIAnimeSound::startAnimSound(soundID, se, actor, players); P2ASSERTLINE(441, se); onPlayingSe(soundID, *se); } } /** * @note Address: 0x8045DC4C * @note Size: 0x3C */ JAISound* CreatureAnime::startSound(u32 soundID, u32 a2) { StartSoundArg arg(this, soundID, a2); return startSoundInner(arg); } /** * @note Address: 0x8045DC88 * @note Size: 0xB0 */ void CreatureAnime::startSound(u8 id, u32 soundID, u32 a3) { JUT_PANICLINE(466, "使用禁止再生関数"); // "Disabled playback functions" JAIBasic::msBasic->startSoundVecT(soundID, &mSounds[id], _24, a3, 0, PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this)); } /** * @note Address: 0x8045DD38 * @note Size: 0xA8 */ void CreatureAnime::startSound(JAISound** se, u32 soundID, u32 a3) { JUT_PANICLINE(482, "使用禁止再生関数"); // "Disabled playback functions" JAIBasic::msBasic->startSoundVecT(soundID, se, _24, a3, 0, PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this)); } /** * @note Address: 0x8045DDE0 * @note Size: 0x40 */ void CreatureAnime::setAnime(JAIAnimeSoundData* data, u32 flag, f32 loopStartFrame, f32 loopEndFrame) { if (data != mSoundData) { if ((int)data == 0xffffffff) { data = nullptr; } initActorAnimSound(data, flag, loopStartFrame, loopEndFrame); } } /** * @note Address: 0x8045DE20 * @note Size: 0x304 */ void CreatureAnime::playActorAnimSound(JAInter::Actor* actor, f32 pitchmod, u8 a2) { JUT_ASSERTLINE(549, mSoundData->mEntryNum < mAnimID, "JAIAnimeSound::playActorAnimSound dataCounterが異常です。\n"); JAIAnimeSoundData* data = &mSoundData[mAnimID]; u8 max = mHandleCount; for (u8 i = 0; i < max; i++) { u8* handle = mSoundStatus; if (handle[i]) { JAISound* se = mSounds[i]; if (!se) { break; } if (data->_08 != se->mSoundID) { continue; } if (!(data->_08 & 0xc00)) { mAnimID += mSoundFlags; return; } else { break; } } if (!(mUseHandleFlag & 1 << i)) { JAISound** se = mSounds; if (!se) { break; } if (i != max - 1) { continue; } int maxTime = 0; int useId = 0; for (u8 j = 0; j < max; j++) { if (!handle[j] && (se[j]->mActiveTimer < maxTime)) { maxTime = se[j]->mActiveTimer; useId = j; } } // if (a2 != max && (!(data->_10[0] & 8) || _6C == data->_10[7]) && _5C == 1 && (max & 2 == 0) || (_5C == -1 && (max & 1 == 0))) // { JAISound** sound = &mSounds[a2]; if (*sound) { handleStop(a2, 0); } startAnimSound(data->_08, sound, actor, a2); if (*sound) { mBasEntries[a2] = (JAIAnimeFrameSoundData*)data; mSoundStatus[a2] = true; (*sound)->setVolume((f32)data->_08 / 127.0f, 0, SOUNDPARAM_Unk5); (*sound)->setPitch((f32)data->_18 * (1.0f - pitchmod), 0, SOUNDPARAM_Unk5); } //} mAnimID += mSoundFlags; return; } } /* stwu r1, -0x50(r1) mflr r0 stw r0, 0x54(r1) stfd f31, 0x40(r1) psq_st f31, 72(r1), 0, qr0 stmw r24, 0x20(r1) mr r26, r3 fmr f31, f1 lwz r3, 0xa8(r3) mr r27, r4 lwz r4, 0x98(r26) mr r28, r5 lhz r0, 0(r3) li r30, 0 cmplw r4, r0 blt lbl_8045DE7C lis r3, lbl_8049CFA0@ha lis r5, lbl_8049CFFC@ha addi r3, r3, lbl_8049CFA0@l li r4, 0x225 addi r5, r5, lbl_8049CFFC@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8045DE7C: lwz r0, 0x98(r26) lwz r5, 0xa8(r26) slwi r4, r0, 5 lbz r3, 0x49(r26) addi r31, r4, 8 add r31, r5, r31 b lbl_8045DF88 lbl_8045DE98: lwz r6, 0x70(r26) clrlwi r5, r30, 0x18 lbzx r0, r6, r5 cmplwi r0, 0 beq lbl_8045DEF4 lwz r4, 0x4c(r26) slwi r0, r5, 2 lwzx r5, r4, r0 cmplwi r5, 0 beq lbl_8045DF94 lwz r4, 0(r31) lwz r0, 0x20(r5) cmplw r4, r0 beq lbl_8045DED8 addi r30, r30, 1 b lbl_8045DF88 lbl_8045DED8: rlwinm. r0, r4, 0, 0x14, 0x15 bne lbl_8045DF94 lwz r3, 0x98(r26) lwz r0, 0x8c(r26) add r0, r3, r0 stw r0, 0x98(r26) b lbl_8045E108 lbl_8045DEF4: li r0, 1 lwz r4, 0x50(r26) slw r0, r0, r5 and. r0, r4, r0 beq lbl_8045DF10 addi r30, r30, 1 b lbl_8045DF88 lbl_8045DF10: lwz r7, 0x4c(r26) slwi r0, r5, 2 lwzx r0, r7, r0 cmplwi r0, 0 beq lbl_8045DF94 addi r0, r3, -1 cmpw r5, r0 bne lbl_8045DF84 li r5, 0 li r8, 0 li r9, 0 b lbl_8045DF70 lbl_8045DF40: clrlwi r4, r9, 0x18 lbzx r0, r6, r4 cmplwi r0, 0 bne lbl_8045DF6C slwi r0, r4, 2 lwzx r4, r7, r0 lwz r0, 0x2c(r4) cmplw r5, r0 bge lbl_8045DF6C mr r5, r0 mr r8, r9 lbl_8045DF6C: addi r9, r9, 1 lbl_8045DF70: clrlwi r0, r9, 0x18 cmplw r0, r3 blt lbl_8045DF40 mr r30, r8 b lbl_8045DF94 lbl_8045DF84: addi r30, r30, 1 lbl_8045DF88: clrlwi r0, r30, 0x18 cmplw r0, r3 blt lbl_8045DE98 lbl_8045DF94: clrlwi r0, r30, 0x18 cmplw r0, r3 beq lbl_8045E0F8 lwz r4, 0x10(r31) rlwinm. r0, r4, 0, 0x1c, 0x1c beq lbl_8045DFBC lwz r3, 0x9c(r26) lbz r0, 0x16(r31) cmplw r3, r0 bne lbl_8045E0F8 lbl_8045DFBC: lwz r3, 0x8c(r26) cmplwi r3, 1 bne lbl_8045DFD0 rlwinm. r0, r4, 0, 0x1e, 0x1e beq lbl_8045DFE4 lbl_8045DFD0: addis r0, r3, 1 cmplwi r0, 0xffff bne lbl_8045E0F8 clrlwi. r0, r4, 0x1f bne lbl_8045E0F8 lbl_8045DFE4: lwz r0, 0x4c(r26) rlwinm r25, r30, 2, 0x16, 0x1d clrlwi r24, r30, 0x18 add r29, r0, r25 lwz r0, 0(r29) cmplwi r0, 0 beq lbl_8045E01C addi r3, r26, 0x30 mr r4, r30 lwz r12, 0x30(r26) li r5, 0 lwz r12, 0x34(r12) mtctr r12 bctrl lbl_8045E01C: mr r3, r26 mr r5, r29 lwz r12, 0x28(r26) mr r6, r27 mr r7, r28 lwz r4, 0(r31) lwz r12, 0x94(r12) mtctr r12 bctrl lwz r0, 0(r29) cmplwi r0, 0 beq lbl_8045E0F8 lwz r3, 0x74(r26) lis r0, 0x4330 li r6, 1 stw r0, 8(r1) lfd f2, lbl_80520C68@sda21(r2) li r4, 0 stwx r31, r3, r25 li r5, 5 lfs f0, lbl_80520C58@sda21(r2) lwz r3, 0x70(r26) stbx r6, r3, r24 lbz r0, 0x14(r31) lwz r3, 0(r29) stw r0, 0xc(r1) lwz r12, 0x10(r3) lfd f1, 8(r1) lwz r12, 0x1c(r12) fsubs f1, f1, f2 fdivs f1, f1, f0 mtctr r12 bctrl lbz r3, 0x15(r31) lis r0, 0x4330 lfs f0, lbl_80520C5C@sda21(r2) li r4, 0 extsb r5, r3 lwz r3, 0(r29) xoris r5, r5, 0x8000 stw r0, 0x10(r1) lwz r12, 0x10(r3) fsubs f2, f31, f0 stw r5, 0x14(r1) li r5, 5 lfd f3, lbl_80520C70@sda21(r2) lfd f0, 0x10(r1) lfs f1, lbl_80520C60@sda21(r2) fsubs f3, f0, f3 lfs f0, 0xc(r31) lwz r12, 0x2c(r12) fmuls f2, f3, f2 fmadds f1, f2, f1, f0 mtctr r12 bctrl lbl_8045E0F8: lwz r3, 0x98(r26) lwz r0, 0x8c(r26) add r0, r3, r0 stw r0, 0x98(r26) lbl_8045E108: psq_l f31, 72(r1), 0, qr0 lfd f31, 0x40(r1) lmw r24, 0x20(r1) lwz r0, 0x54(r1) mtlr r0 addi r1, r1, 0x50 blr */ } /** * @note Address: 0x8045E124 * @note Size: 0xB4 */ void CreatureAnime::exec() { bool prev = mActive; mActive = mGameObj->sound_culling() == 0; if (mActive) { if (prev == 0) { onCalcTurnOn(); } onCalcOn(); } else if (prev == 1) { onCalcTurnOff(); } } /** * @note Address: 0x8045E1D8 * @note Size: 0xC8 */ void CreatureAnime::onCalcOn() { JAInter::Actor actor(this, _24, 0, 0); setAnimSoundActor(&actor, mGameObj->getSound_CurrAnimFrame(), mGameObj->getSound_CurrAnimSpeed(), PSSystem::SingletonBase<ObjCalcBase>::sInstance->getPlayerNo(this)); /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stfd f31, 0x28(r1) stw r31, 0x24(r1) stw r30, 0x20(r1) or. r30, r3, r3 lwz r7, 0x54(r3) bne lbl_8045E204 mr r4, r7 b lbl_8045E208 lbl_8045E204: mr r4, r30 lbl_8045E208: li r6, -1 li r5, 0 li r0, 1 stw r4, 8(r1) lwz r3, "sInstance__Q28PSSystem34SingletonBase<Q23PSM11ObjCalcBase>"@sda21(r13) mr r4, r30 stw r7, 0xc(r1) stw r6, 0x10(r1) stw r5, 0x14(r1) stb r0, 0x18(r1) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl mr r31, r3 lwz r3, 0x2c(r30) lwz r12, 0(r3) lwz r12, 0x10c(r12) mtctr r12 bctrl lwz r3, 0x2c(r30) fmr f31, f1 lwz r12, 0(r3) lwz r12, 0x108(r12) mtctr r12 bctrl fmr f2, f31 mr r5, r31 addi r3, r30, 0x30 addi r4, r1, 8 bl setAnimSoundActor__13JAIAnimeSoundFPQ27JAInter5ActorffUc lwz r0, 0x34(r1) lfd f31, 0x28(r1) lwz r31, 0x24(r1) lwz r30, 0x20(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /** * @note Address: 0x8045E2A0 * @note Size: 0x24 */ void CreatureAnime::onCalcTurnOn() { static_cast<Game::EnemyBase*>(mGameObj)->setPSEnemyBaseAnime(); } /** * @note Address: 0x8045E2C4 * @note Size: 0x4 */ void CreatureAnime::onCalcTurnOff() { } /** * @note Address: 0x8045E2C8 * @note Size: 0x4C */ void CreatureAnime::frameEnd_onPlaySe() { FrameCalcArg arg(this, &mDistance, &mPan, &mDolby); loopCalc(arg); } /** * @note Address: 0x8045E314 * @note Size: 0x4C */ void BattleLink::battleOn() { ActorDirector_Battle* dir = PSMGetBattleD(); if (dir && dir->mActor) { dir->mActor->append(this); } } /** * @note Address: 0x8045E360 * @note Size: 0x4C */ void BattleLink::battleOff() { ActorDirector_Battle* dir = PSMGetBattleD(); if (dir && dir->mActor) { dir->mActor->remove(this); } } /** * @note Address: 0x8045E3AC * @note Size: 0x4C */ void KehaiLink::kehaiOn() { ActorDirector_Kehai* dir = PSMGetKehaiD(); if (dir && dir->mActor) { dir->mActor->append(this); } } /** * @note Address: 0x8045E3F8 * @note Size: 0x4C */ void KehaiLink::kehaiOff() { ActorDirector_Kehai* dir = PSMGetKehaiD(); if (dir && dir->mActor) { dir->mActor->remove(this); } } /** * @note Address: 0x8045E444 * @note Size: 0x180 */ EnemyBase::EnemyBase(Game::EnemyBase* gameObj, u8 p2) : CreatureAnime(gameObj, p2) , BattleLink(gameObj) , KehaiLink(gameObj) { } /** * @note Address: 0x8045E6A0 * @note Size: 0x174 */ void EnemyBase::startAnimSound(u32 soundID, JAISound** se, JAInter::Actor* actor, u8 a1) { if ((static_cast<Game::EnemyBase*>(mGameObj)->isEvent(0, Game::EB_Bittered))) { u32 id = soundID; if ((id == PSSE_EN_DOPING_GAS_FREEZE || id == PSSE_EN_DOPING_ROCK_FLICK || id == PSSE_EN_DOPING_FLICK_LAST || id == PSSE_EN_DOPING_ROCK_BREAK) || ((id >> 12) & 0xf) == 2) { CreatureAnime::startAnimSound(soundID, se, actor, a1); } } /* .loc_0x0: stwu r1, -0x20(r1) mflr r0 lis r7, 0x804A stw r0, 0x24(r1) stmw r26, 0x8(r1) mr r26, r3 mr r27, r4 mr r28, r5 mr r29, r6 subi r31, r7, 0x3060 lwz r3, 0x2C(r3) lwz r0, 0x1E0(r3) rlwinm. r0,r0,0,22,22 beq- .loc_0x58 cmplwi r27, 0x50B0 beq- .loc_0x58 subi r0, r27, 0x58B1 cmplwi r0, 0x2 ble- .loc_0x58 rlwinm r0,r27,20,28,31 cmplwi r0, 0x2 bne- .loc_0x160 .loc_0x58: lwz r12, 0x0(r3) lwz r12, 0x104(r12) mtctr r12 bctrl rlwinm. r0,r3,0,24,31 bne- .loc_0x160 lwz r0, -0x6780(r13) cmplwi r0, 0 bne- .loc_0x90 addi r3, r31, 0x30 addi r5, r31, 0x18 li r4, 0x1D3 crclr 6, 0x6 bl -0x4340EC .loc_0x90: lwz r30, -0x6780(r13) cmplwi r30, 0 bne- .loc_0xB0 addi r3, r31, 0x30 addi r5, r31, 0x18 li r4, 0x1DC crclr 6, 0x6 bl -0x43410C .loc_0xB0: lwz r0, 0x8(r30) cmplwi r0, 0 bne- .loc_0xD0 addi r3, r31, 0x3C addi r5, r31, 0x18 li r4, 0xA1 crclr 6, 0x6 bl -0x43412C .loc_0xD0: lwz r3, 0x8(r30) mr r4, r26 mr r5, r27 lwz r12, 0x0(r3) lwz r12, 0x38(r12) mtctr r12 bctrl rlwinm. r0,r3,0,24,31 beq- .loc_0x160 stw r26, 0x0(r29) mr r4, r26 lwz r3, -0x6E4C(r13) lwz r12, 0x0(r3) lwz r12, 0xC(r12) mtctr r12 bctrl mr r7, r3 mr r4, r27 mr r5, r28 mr r6, r29 addi r3, r26, 0x30 bl -0x3B2B74 cmplwi r28, 0 bne- .loc_0x144 addi r3, r31, 0 addi r5, r31, 0x18 li r4, 0x1B9 crclr 6, 0x6 bl -0x4341A0 .loc_0x144: mr r3, r26 mr r4, r27 lwz r12, 0x28(r26) lwz r5, 0x0(r28) lwz r12, 0x38(r12) mtctr r12 bctrl .loc_0x160: lmw r26, 0x8(r1) lwz r0, 0x24(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /** * @note Address: 0x8045E814 * @note Size: 0x5C */ JAISound* EnemyBase::startSoundInner(PSM::StartSoundArg& arg) { if ((static_cast<Game::EnemyBase*>(mGameObj)->isEvent(0, Game::EB_Bittered))) { u32 id = arg.mSoundID; if ((id == PSSE_EN_DOPING_GAS_FREEZE || id == PSSE_EN_DOPING_ROCK_FLICK || id == PSSE_EN_DOPING_FLICK_LAST || id == PSSE_EN_DOPING_ROCK_BREAK) || ((id >> 12) & 0xf) != 2) { return nullptr; } } return Creature::startSoundInner(arg); /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) lwz r5, 0x2c(r3) lwz r0, 0x1e0(r5) rlwinm. r0, r0, 0, 0x16, 0x16 beq lbl_8045E85C lwz r5, 4(r4) cmplwi r5, 0x50b0 beq lbl_8045E85C addi r0, r5, -22705 cmplwi r0, 2 ble lbl_8045E85C rlwinm r0, r5, 0x14, 0x1c, 0x1f cmplwi r0, 2 beq lbl_8045E85C li r3, 0 b lbl_8045E860 lbl_8045E85C: bl startSoundInner__Q23PSM8CreatureFRQ23PSM13StartSoundArg lbl_8045E860: lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /** * @note Address: 0x8045E870 * @note Size: 0x44 */ void EnemyBase::onCalcTurnOn() { static_cast<Game::EnemyBase*>(mGameObj)->setPSEnemyBaseAnime(); updateKehai(); } /** * @note Address: 0x8045E8B4 * @note Size: 0x4C */ void EnemyBase::onCalcTurnOff() { battleOff(); kehaiOff(); } /** * @note Address: 0x8045E900 * @note Size: 0xF0 */ void EnemyBase::onCalcOn() { CreatureAnime::onCalcOn(); updateBattle(); updateKehai(); } /** * @note Address: 0x8045E9F0 * @note Size: 0x60 */ void EnemyBase::battleOff() { BattleLink::battleOff(); updateKehai(); } /** * @note Address: 0x8045EA50 * @note Size: 0x88 */ void EnemyBase::updateKehai() { bool state = calcKehai(); bool list = KehaiLink::mList; if (state && !list) { kehaiOn(); } else if (!state && list) { kehaiOff(); } } /** * @note Address: 0x8045EAD8 * @note Size: 0xC8 */ void EnemyBase::updateBattle() { if (mGameObj->isAlive()) { Game::EnemyBase* obj = static_cast<Game::EnemyBase*>(mGameObj); if (obj->mSfxEmotion == 2 && !BattleLink::mList) { battleOn(); } else if (obj->mSfxEmotion != 2 && BattleLink::mList) { battleOff(); } } else { if (BattleLink::mList) { battleOff(); } } /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r3, 0x2c(r3) lwz r12, 0(r3) lwz r12, 0xa8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EB6C lwz r3, 0x2c(r31) lbz r0, 0x1f0(r3) cmplwi r0, 2 bne lbl_8045EB3C lwz r0, 0xbc(r31) cmplwi r0, 0 bne lbl_8045EB3C addi r3, r31, 0xb8 lwz r12, 0xc8(r31) lwz r12, 8(r12) mtctr r12 bctrl b lbl_8045EB8C lbl_8045EB3C: lbz r0, 0x1f0(r3) cmplwi r0, 2 beq lbl_8045EB8C lwz r0, 0xbc(r31) cmplwi r0, 0 beq lbl_8045EB8C mr r3, r31 lwz r12, 0x28(r31) lwz r12, 0xc4(r12) mtctr r12 bctrl b lbl_8045EB8C lbl_8045EB6C: lwz r0, 0xbc(r31) cmplwi r0, 0 beq lbl_8045EB8C mr r3, r31 lwz r12, 0x28(r31) lwz r12, 0xc4(r12) mtctr r12 bctrl lbl_8045EB8C: lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /** * @note Address: 0x8045EBA0 * @note Size: 0x338 */ bool EnemyBase::calcKehai() { Game::EnemyBase* enemy = static_cast<Game::EnemyBase*>(mGameObj); if (!enemy->isAlive() || enemy->isUnderground()) { return false; } Vec& enemypos = *(Vec*)enemy->getSound_PosPtr(); Iterator<Game::Navi> iterator(Game::naviMgr); CI_LOOP(iterator) { Game::Navi* navi = *iterator; if (navi->mController1) { Vector3f pos = navi->getPosition(); volatile Vec pos2; pos2.x = pos.x; pos2.y = pos.y; pos2.z = pos.z; if (judgeNearWithPlayer(enemypos, *(Vec*)&pos, CreaturePrm::cVolZeroDist_Kehai[getCastType() - 2], CreaturePrm::cVolZeroDist_InnerSize_Kehai[getCastType() - 2])) { return true; } } } return false; /* stwu r1, -0x60(r1) mflr r0 stw r0, 0x64(r1) stfd f31, 0x50(r1) psq_st f31, 88(r1), 0, qr0 stw r31, 0x4c(r1) stw r30, 0x48(r1) mr r30, r3 lwz r31, 0x2c(r3) mr r3, r31 lwz r12, 0(r31) lwz r12, 0xa8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EBFC mr r3, r31 lwz r12, 0(r31) lwz r12, 0xd0(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EC04 lbl_8045EBFC: li r3, 0 b lbl_8045EEB8 lbl_8045EC04: mr r3, r31 lwz r12, 0(r31) lwz r12, 0x100(r12) mtctr r12 bctrl li r4, 0 lwz r0, naviMgr__4Game@sda21(r13) lis r5, "__vt__22Iterator<Q24Game4Navi>"@ha stw r4, 0x38(r1) addi r5, r5, "__vt__22Iterator<Q24Game4Navi>"@l cmplwi r4, 0 stw r5, 0x2c(r1) mr r31, r3 stw r4, 0x30(r1) stw r0, 0x34(r1) bne lbl_8045EC60 mr r3, r0 lwz r12, 0(r3) lwz r12, 0x18(r12) mtctr r12 bctrl stw r3, 0x30(r1) b lbl_8045EE94 lbl_8045EC60: mr r3, r0 lwz r12, 0(r3) lwz r12, 0x18(r12) mtctr r12 bctrl stw r3, 0x30(r1) b lbl_8045ECD0 lbl_8045EC7C: lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl mr r4, r3 lwz r3, 0x38(r1) lwz r12, 0(r3) lwz r12, 8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 bne lbl_8045EE94 lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x30(r1) lbl_8045ECD0: lwz r12, 0x2c(r1) addi r3, r1, 0x2c lwz r12, 0x10(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EC7C b lbl_8045EE94 lbl_8045ECF0: lwz r3, 0x34(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl lwz r0, 0x278(r3) cmplwi r0, 0 beq lbl_8045EDD8 mr r4, r3 addi r3, r1, 0x14 lwz r12, 0(r4) lwz r12, 8(r12) mtctr r12 bctrl lfs f2, 0x14(r1) mr r3, r30 lfs f1, 0x18(r1) lfs f0, 0x1c(r1) stfs f2, 8(r1) stfs f1, 0xc(r1) lwz r5, 8(r1) stfs f0, 0x10(r1) lwz r4, 0xc(r1) lwz r0, 0x10(r1) stw r5, 0x20(r1) stw r4, 0x24(r1) stw r0, 0x28(r1) lwz r12, 0x28(r30) lwz r12, 0x1c(r12) mtctr r12 bctrl slwi r5, r3, 2 mr r3, r30 lwz r12, 0x28(r30) lis r4, cVolZeroDist_InnerSize_Kehai__Q23PSM11CreaturePrm@ha addi r0, r4, cVolZeroDist_InnerSize_Kehai__Q23PSM11CreaturePrm@l lwz r12, 0x1c(r12) add r4, r0, r5 lfs f31, -8(r4) mtctr r12 bctrl lwz r12, 0x28(r30) lis r4, cVolZeroDist_Kehai__Q23PSM11CreaturePrm@ha slwi r5, r3, 2 fmr f2, f31 addi r0, r4, cVolZeroDist_Kehai__Q23PSM11CreaturePrm@l lwz r12, 0x34(r12) add r5, r0, r5 mr r3, r30 lfs f1, -8(r5) mr r4, r31 addi r5, r1, 0x20 mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EDD8 li r3, 1 b lbl_8045EEB8 lbl_8045EDD8: lwz r0, 0x38(r1) cmplwi r0, 0 bne lbl_8045EE04 lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x30(r1) b lbl_8045EE94 lbl_8045EE04: lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x30(r1) b lbl_8045EE78 lbl_8045EE24: lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl mr r4, r3 lwz r3, 0x38(r1) lwz r12, 0(r3) lwz r12, 8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 bne lbl_8045EE94 lwz r3, 0x34(r1) lwz r4, 0x30(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x30(r1) lbl_8045EE78: lwz r12, 0x2c(r1) addi r3, r1, 0x2c lwz r12, 0x10(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045EE24 lbl_8045EE94: lwz r3, 0x34(r1) lwz r12, 0(r3) lwz r12, 0x1c(r12) mtctr r12 bctrl lwz r4, 0x30(r1) cmplw r4, r3 bne lbl_8045ECF0 li r3, 0 lbl_8045EEB8: psq_l f31, 88(r1), 0, qr0 lwz r0, 0x64(r1) lfd f31, 0x50(r1) lwz r31, 0x4c(r1) lwz r30, 0x48(r1) mtlr r0 addi r1, r1, 0x60 blr */ } /** * @note Address: 0x8045EED8 * @note Size: 0x94 */ bool EnemyBase::judgeNearWithPlayer(const Vec& enemyPosition, const Vec& naviPosition, f32 distanceX, f32 distanceY) { f32 x = enemyPosition.x - naviPosition.x; if (!(x >= 0.0f)) { x = -x; } if (x < distanceX) { x = enemyPosition.y - naviPosition.y; x = (x >= 0.0f) ? x : -x; if (x < distanceX) { x = enemyPosition.z - naviPosition.z; x = (x >= 0.0f) ? x : -x; if (x < distanceX) return true; } } return false; /* lfs f3, 0(r4) lfs f2, 0(r5) lfs f0, lbl_80520C50@sda21(r2) fsubs f2, f3, f2 fcmpo cr0, f2, f0 cror 2, 1, 2 bne lbl_8045EEF8 b lbl_8045EEFC lbl_8045EEF8: fneg f2, f2 lbl_8045EEFC: fcmpo cr0, f2, f1 bge lbl_8045EF64 lfs f3, 4(r4) lfs f2, 4(r5) lfs f0, lbl_80520C50@sda21(r2) fsubs f2, f3, f2 fcmpo cr0, f2, f0 cror 2, 1, 2 bne lbl_8045EF24 b lbl_8045EF28 lbl_8045EF24: fneg f2, f2 lbl_8045EF28: fcmpo cr0, f2, f1 bge lbl_8045EF64 lfs f3, 8(r4) lfs f2, 8(r5) lfs f0, lbl_80520C50@sda21(r2) fsubs f2, f3, f2 fcmpo cr0, f2, f0 cror 2, 1, 2 bne lbl_8045EF50 b lbl_8045EF54 lbl_8045EF50: fneg f2, f2 lbl_8045EF54: fcmpo cr0, f2, f1 bge lbl_8045EF64 li r3, 1 blr lbl_8045EF64: li r3, 0 blr */ } /** * @note Address: 0x8045EF6C * @note Size: 0x1AC */ EnemyNotAggressive::EnemyNotAggressive(Game::EnemyBase* gameObj, u8 p2) : EnemyBase(gameObj, p2) { } /** * @note Address: 0x8045F118 * @note Size: 0x160 */ Tsuyukusa::Tsuyukusa(Game::Creature* gameObj) : CreatureObj(gameObj, 2) , mIsEnabled(FALSE) , mLink(gameObj) { P2ASSERTLINE(1078, gameObj); } /** * @note Address: 0x8045F278 * @note Size: 0xB8 */ void Tsuyukusa::noukouFrameWork(bool enable) { PSM::ListDirectorActor* actor = PSMGetGroundD()->mActor; P2ASSERTLINE(1086, actor); if (enable == true && mIsEnabled == 0) { actor->append(&mLink); } else if (!enable && mIsEnabled == true) { actor->remove(&mLink); } mIsEnabled = enable; } /** * @note Address: 0x8045F330 * @note Size: 0x128 */ bool EnemyBig::judgeNearWithPlayer(const Vec& pos1, const Vec& pos2, f32 min, f32 max) { return Creature::judgeNearWithPlayer(pos1, pos2, min, max); } /** * @note Address: N/A * @note Size: 0x1F0 */ inline EnemyBoss::EnemyBoss(Game::EnemyBase* gameObj) : EnemyBase(gameObj, 4) , mNaviDistance(10000000.0f) , mDisappearTimer(-1) , _E8(-1) , mLink(this) , mAppearFlag(false) , mIsFirstAppear(0) , _FE(1) , mHasReset(0) { // UNUSED FUNCTION } /** * @note Address: 0x8045F458 * @note Size: 0x74 */ void EnemyBoss::onPlayingSe(u32, JAISound* sound) { if (sound) { PSGame::SoundTable::SePerspInfo info; info.set(1.0f, sBoss_ViewDist, sBoss_ViewDistVol, sBoss_DistMax, 0.0f); static_cast<SeSound*>(sound)->specializePerspCalc(info); } } /** * @note Address: 0x8045F4CC * @note Size: 0x14 */ bool EnemyBoss::judgeNearWithPlayer(const Vec&, const Vec&, f32 min, f32) { return mNaviDistance < min; } /** * @note Address: 0x8045F4E0 * @note Size: 0xB4 */ void EnemyBoss::exec() { EnemyBase::exec(); } /** * @note Address: 0x8045F594 * @note Size: 0xF8 */ void EnemyBoss::onCalcOn() { calcDistance(); EnemyBase::onCalcOn(); } /** * @note Address: 0x8045F68C * @note Size: 0x364 */ void EnemyBoss::calcDistance() { f32 dist = 10000000.0f; Iterator<Game::Navi> iterator(Game::naviMgr); CI_LOOP(iterator) { Game::Navi* navi = *iterator; if (navi->isAlive()) { Vector3f pos = mGameObj->getPosition(); Vector3f navipos = navi->getPosition(); f32 cdist = pos.distance(navipos); if (cdist < dist) { dist = cdist; } } } mNaviDistance = dist; /* stwu r1, -0xa0(r1) mflr r0 stw r0, 0xa4(r1) stfd f31, 0x90(r1) psq_st f31, 152(r1), 0, qr0 stw r31, 0x8c(r1) stw r30, 0x88(r1) li r4, 0 lwz r0, naviMgr__4Game@sda21(r13) lis r5, "__vt__22Iterator<Q24Game4Navi>"@ha stw r4, 0x80(r1) addi r5, r5, "__vt__22Iterator<Q24Game4Navi>"@l cmplwi r4, 0 stw r5, 0x74(r1) mr r31, r3 lfs f31, lbl_80520C78@sda21(r2) stw r4, 0x78(r1) stw r0, 0x7c(r1) bne lbl_8045F6F4 mr r3, r0 lwz r12, 0(r3) lwz r12, 0x18(r12) mtctr r12 bctrl stw r3, 0x78(r1) b lbl_8045F9AC lbl_8045F6F4: mr r3, r0 lwz r12, 0(r3) lwz r12, 0x18(r12) mtctr r12 bctrl stw r3, 0x78(r1) b lbl_8045F764 lbl_8045F710: lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl mr r4, r3 lwz r3, 0x80(r1) lwz r12, 0(r3) lwz r12, 8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 bne lbl_8045F9AC lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x78(r1) lbl_8045F764: lwz r12, 0x74(r1) addi r3, r1, 0x74 lwz r12, 0x10(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045F710 b lbl_8045F9AC lbl_8045F784: lwz r3, 0x7c(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl lwz r0, 0x278(r3) mr r30, r3 cmplwi r0, 0 beq lbl_8045F8F0 lwz r4, 0x2c(r31) addi r3, r1, 0x44 lwz r12, 0(r4) lwz r12, 8(r12) mtctr r12 bctrl lfs f2, 0x44(r1) mr r4, r30 lfs f1, 0x48(r1) addi r3, r1, 0x5c lfs f0, 0x4c(r1) stfs f2, 0x2c(r1) lwz r12, 0(r30) stfs f1, 0x30(r1) lwz r6, 0x2c(r1) stfs f0, 0x34(r1) lwz r5, 0x30(r1) lwz r0, 0x34(r1) lwz r12, 8(r12) stw r6, 0x50(r1) stw r5, 0x54(r1) stw r0, 0x58(r1) mtctr r12 bctrl lfs f0, 0x5c(r1) lfs f1, 0x60(r1) stfs f0, 0x38(r1) lfs f0, 0x64(r1) stfs f1, 0x3c(r1) lwz r0, 0x38(r1) lwz r3, 0x3c(r1) stfs f0, 0x40(r1) lfs f0, 0x50(r1) stw r0, 0x68(r1) lwz r0, 0x40(r1) stw r3, 0x6c(r1) lfs f1, 0x68(r1) stw r0, 0x70(r1) fsubs f3, f1, f0 lfs f2, 0x6c(r1) lfs f0, 0x54(r1) lfs f1, 0x70(r1) fsubs f2, f2, f0 lfs f0, 0x58(r1) stfs f3, 0x20(r1) fsubs f1, f1, f0 lfs f0, lbl_80520C50@sda21(r2) stfs f2, 0x24(r1) lwz r0, 0x20(r1) lwz r3, 0x24(r1) stfs f1, 0x28(r1) stw r0, 8(r1) lwz r0, 0x28(r1) stw r3, 0xc(r1) lfs f2, 8(r1) lfs f1, 0xc(r1) stw r0, 0x10(r1) fmuls f3, f2, f2 fmuls f2, f1, f1 lfs f1, 0x10(r1) stfs f3, 8(r1) fmuls f1, f1, f1 stfs f2, 0xc(r1) lwz r0, 8(r1) lwz r3, 0xc(r1) stfs f1, 0x10(r1) stw r0, 0x14(r1) lwz r0, 0x10(r1) stw r3, 0x18(r1) lfs f2, 0x14(r1) lfs f1, 0x18(r1) stw r0, 0x1c(r1) fadds f1, f2, f1 lfs f2, 0x1c(r1) fadds f1, f2, f1 fcmpo cr0, f1, f0 ble lbl_8045F8E4 frsqrte f0, f1 fmuls f1, f0, f1 lbl_8045F8E4: fcmpo cr0, f1, f31 bge lbl_8045F8F0 fmr f31, f1 lbl_8045F8F0: lwz r0, 0x80(r1) cmplwi r0, 0 bne lbl_8045F91C lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x78(r1) b lbl_8045F9AC lbl_8045F91C: lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x78(r1) b lbl_8045F990 lbl_8045F93C: lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x20(r12) mtctr r12 bctrl mr r4, r3 lwz r3, 0x80(r1) lwz r12, 0(r3) lwz r12, 8(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 bne lbl_8045F9AC lwz r3, 0x7c(r1) lwz r4, 0x78(r1) lwz r12, 0(r3) lwz r12, 0x14(r12) mtctr r12 bctrl stw r3, 0x78(r1) lbl_8045F990: lwz r12, 0x74(r1) addi r3, r1, 0x74 lwz r12, 0x10(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_8045F93C lbl_8045F9AC: lwz r3, 0x7c(r1) lwz r12, 0(r3) lwz r12, 0x1c(r12) mtctr r12 bctrl lwz r4, 0x78(r1) cmplw r4, r3 bne lbl_8045F784 stfs f31, 0xe0(r31) psq_l f31, 152(r1), 0, qr0 lwz r0, 0xa4(r1) lfd f31, 0x90(r1) lwz r31, 0x8c(r1) lwz r30, 0x88(r1) mtlr r0 addi r1, r1, 0xa0 blr */ } /** * @note Address: 0x8045F9F0 * @note Size: 0x140 */ void EnemyBoss::setAppearFlag(bool flag) { mAppearFlag = flag; PSSystem::SceneMgr* mgr = PSMGetSceneMgrCheck(); mgr->checkScene(); SceneBase* scene = static_cast<SceneBase*>(mgr->mScenes->mChild); if (scene && scene->getSeSceneGate(this, 0)) { if (flag == true) { if (!mIsFirstAppear) { mIsFirstAppear = true; onAppear1st(); } onAppear(); } else { onDisappear(); } } } /** * @note Address: 0x8045FB30 * @note Size: 0x5C */ void EnemyBoss::dyingFrameWork() { if (_E8 != 0xffffffff) { _E8++; } if (_E8 & 0x10000000 && (_E8 & 0xfffffff) >= 180) { setKilled(); } } /** * @note Address: 0x8045FB8C * @note Size: 0x234 */ void EnemyBoss::onDeathMotionTop() { _E8 = 0; Scene_Game* scene = PSMGetGameScene(); if (scene) { scene->mEnemyBossList.append(&mLink); } if (PSMGetGameScene()) { bool canJump = true; FOREACH_NODE(JSULink<EnemyBoss>, PSSystem::SingletonBase<BossBgmFader::Mgr>::getInstance()->mTypedProc.getFirst(), link) { EnemyBoss* obj = link->getObject(); if (obj->_FE && obj->_E8 == -1) { canJump = false; } } if (canJump) { jumpRequest(PSM::EnemyMidBoss::BossBgm_Defeated); } } } /** * @note Address: 0x8045FDC0 * @note Size: 0x15C */ void EnemyBoss::setKilled() { if (_E8 < 180) { _E8 |= 0x10000000; return; } Scene_Game* scene = PSMGetGameScene(); if (scene) { scene->mEnemyBossList.remove(&mLink); } if (_FE) { _E8 = -1; mAppearFlag = false; _FE = false; if (scene) { scene->bossKilled(this); } mDisappearTimer = 0; } } /** * @note Address: 0x8045FF1C * @note Size: 0x24 */ bool EnemyBoss::isOnDisappearing() { return mDisappearTimer != 0xffff; } /** * @note Address: 0x8045FF40 * @note Size: 0x30 */ void EnemyBoss::updateDisappearing() { if (mDisappearTimer == 0xffff) { return; } mDisappearTimer++; if (mDisappearTimer > 120) { mDisappearTimer = 0xffff; } } /** * @note Address: 0x8045FF70 * @note Size: 0x260 */ EnemyMidBoss::EnemyMidBoss(Game::EnemyBase* gameObj) : EnemyBoss(gameObj) , mNumLinks(0xFFFF) , _104(500.0f) , mLink(this) , _118(0) { BossBgmFader::Mgr* mgr = BossBgmFader::Mgr::sInstance; if (mgr) { mNumLinks = mgr->mTypedProc.getNumLinks(); mgr->appendTarget(&mLink); } } /** * @note Address: 0x804601D0 * @note Size: 0x1A8 */ EnemyBoss::~EnemyBoss() { } /** * @note Address: 0x80460378 * @note Size: 0x21C */ void EnemyMidBoss::onCalcOn() { EnemyBoss::onCalcOn(); if (_118 && !mAppearFlag) { Scene_Game* scene = PSMGetGameScene(); if (scene && scene->getSeSceneGate(this, 0) && mNaviDistance < _104) { mAppearFlag = true; PSSystem::SceneMgr* mgr = PSMGetSceneMgrCheck(); mgr->checkScene(); SceneBase* scene = static_cast<SceneBase*>(mgr->mScenes->mChild); if (scene && scene->getSeSceneGate(this, 0)) { if (!mIsFirstAppear) { mIsFirstAppear = true; onAppear1st(); } onAppear(); } _118 = false; } } } /** * @note Address: 0x80460594 * @note Size: 0xEC */ void EnemyMidBoss::jumpRequest(u16 state) { MiddleBossSeq* seq = PSMGetMiddleBossSeq(); if (seq && seq) { seq->mCurrBossObj = this; seq->requestJumpBgmOnBeat(state); } } /** * @note Address: 0x80460680 * @note Size: 0x10C */ void EnemyMidBoss::onAppear1st() { Scene_Game* scene = PSMGetGameScene(); if (scene) { scene->bossAppear(this, PSM::EnemyMidBoss::BossBgm_Appear); } } /** * @note Address: 0x8046078C * @note Size: 0x60 */ void EnemyMidBoss::postPikiAttack(bool flag) { if (PSSystem::SingletonBase<BossBgmFader::Mgr>::sInstance) { DirectorUpdator* dir = PSSystem::SingletonBase<BossBgmFader::Mgr>::sInstance->mTypedProc.mDirectorUpdator; if (dir) { if (flag) { dir->directOn(mNumLinks); } else { dir->directOff(mNumLinks); } } } } /** * @note Address: 0x804607EC * @note Size: 0x68 */ EnemyBigBoss::EnemyBigBoss(Game::EnemyBase* gameObj) : EnemyMidBoss(gameObj) , mCurrBgmState(1) { sBigBoss = this; } /** * @note Address: 0x80460854 * @note Size: 0x1F0 */ EnemyMidBoss::~EnemyMidBoss() { } /** * @note Address: 0x80460A44 * @note Size: 0x88 */ EnemyBigBoss::~EnemyBigBoss() { sBigBoss = nullptr; } /** * @note Address: 0x80460ACC * @note Size: 0xE8 */ void EnemyBigBoss::jumpRequest(u16 state) { MiddleBossSeq* seq = PSMGetMiddleBossSeq(); if (seq) { seq->mCurrBossObj = this; seq->requestJumpBgmOnBeat(state); } } /** * @note Address: 0x80460BB4 * @note Size: 0x38 */ void EnemyBigBoss::onDeathMotionTop() { _E8 = 0; jumpRequest(BigBossBgm_Defeated); } /** * @note Address: 0x80460BEC * @note Size: 0x10C */ void EnemyBigBoss::onAppear1st() { Scene_Game* scene = PSMGetGameScene(); if (scene) { scene->bossAppear(this, mCurrBgmState); } } /** * @note Address: 0x80460CF8 * @note Size: 0xBC * Adjusts pitch for chappy sounds */ void Enemy_SpecialChappy::onPlayingSe(u32 soundID, JAISound* sound) { if (!sound) { return; } if (soundID >= PSSE_EN_CHAPPY_WALK && PSSE_EN_CHAPPY_EAT >= soundID && soundID != PSSE_EN_CHAPPY_DEAD && soundID != PSSE_EN_CHAPPY_BITE2) { sound->setPitch(0.8f, 0, SOUNDPARAM_Unk0); } else if (soundID == PSSE_EN_CHAPPY_DEAD) { sound->setPitch(0.65f, 0, SOUNDPARAM_Unk0); } else if (soundID == PSSE_EN_CHAPPY_BITE2) { sound->setPitch(0.8f, 20, SOUNDPARAM_Unk0); } } /** * @note Address: 0x80460DB4 * @note Size: 0x2C */ void DirectorLink::eventStart() { eventRestart(); } /** * @note Address: 0x80460DE0 * @note Size: 0x4C */ void DirectorLink::eventRestart() { ListDirectorActor* actor = getListDirectorActor(); if (actor) { actor->append(this); } } /** * @note Address: 0x80460E2C * @note Size: 0x4C */ void DirectorLink::eventStop() { ListDirectorActor* actor = getListDirectorActor(); if (actor) { actor->remove(this); } } /** * @note Address: 0x80460E78 * @note Size: 0x2C */ void DirectorLink::eventFinish() { eventStop(); } /** * @note Address: 0x80460EA4 * @note Size: 0x34 */ ListDirectorActor* EventLink::getListDirectorActor() { ActorDirector_Scaled* actor = PSMGetEventD(); if (actor) { return actor->mActor; } return nullptr; } /** * @note Address: 0x80460ED8 * @note Size: 0x34 */ ListDirectorActor* OtakaraEventLink::getListDirectorActor() { ActorDirector_TrackOn* actor = PSMGetOtakaraEventD(); if (actor) { return (ListDirectorActor*)actor->mActor; } return nullptr; } /** * @note Address: 0x80460F0C * @note Size: 0x4 */ void OtakaraEventLink::eventFinish() { } /** * @note Address: 0x80460F10 * @note Size: 0x250 */ ActorDirector_TrackOn* OtakaraEventLink_2PBattle::getTargetDirector() { P2ASSERTLINE(1699, getObject()); Otakara* obj = static_cast<Otakara*>(getObject()->getPSCreature()); P2ASSERTLINE(1701, obj); P2ASSERTLINE(1706, obj->isTreasure()); Game::Onyon* onyon = obj->mOnyon; ActorDirector_TrackOn* actor = nullptr; switch (obj->mBedamaType) { case Otakara::PSMBedama_None: actor = nullptr; break; case Otakara::PSMBedama_Cherry: if (onyon) { if (onyon->mOnyonType == ONYON_TYPE_BLUE) { actor = PSMGetIchouForLugieD(); } else if (onyon->mOnyonType == ONYON_TYPE_RED) { actor = PSMGetIchouForOrimerD(); } else { JUT_PANICLINE(1780, "P2Assert"); } } break; case Otakara::PSMBedama_Yellow: P2ASSERTLINE(1787, onyon); if (onyon->mOnyonType == ONYON_TYPE_BLUE) { actor = PSMGetBeedamaForLugieD(); } else if (onyon->mOnyonType == ONYON_TYPE_RED) { actor = PSMGetBeedamaForOrimerD(); } else { JUT_PANICLINE(1794, "P2Assert"); } break; case Otakara::PSMBedama_Red: actor = PSMGetBeedamaForLugieD(); break; case Otakara::PSMBedama_Blue: actor = PSMGetBeedamaForOrimerD(); break; } P2ASSERTLINE(1818, actor); return actor; } /** * @note Address: 0x80461160 * @note Size: 0x194 */ void OtakaraEventLink_2PBattle::eventStart() { P2ASSERTLINE(1699, getObject()); Otakara* obj = static_cast<Otakara*>(getObject()->getPSCreature()); P2ASSERTLINE(1701, obj); P2ASSERTLINE(1706, obj->isTreasure()); if (!obj->canFinish()) { ActorDirector_TrackOn* director = getTargetDirector(); if (director->mActor) { static_cast<ListDirectorActor*>(director->mActor)->append(this); } } } /** * @note Address: 0x804612F4 * @note Size: 0x2C */ void OtakaraEventLink_2PBattle::eventRestart() { eventStart(); } /** * @note Address: 0x80461320 * @note Size: 0x194 */ void OtakaraEventLink_2PBattle::eventStop() { P2ASSERTLINE(1699, getObject()); Otakara* obj = static_cast<Otakara*>(getObject()->getPSCreature()); P2ASSERTLINE(1701, obj); P2ASSERTLINE(1706, obj->isTreasure()); if (!obj->canFinish()) { ActorDirector_TrackOn* director = getTargetDirector(); if (director->mActor) { static_cast<ListDirectorActor*>(director->mActor)->remove(this); } } } /** * @note Address: 0x804614B4 * @note Size: 0x2C */ void OtakaraEventLink_2PBattle::eventFinish() { eventStop(); } /** * @note Address: 0x804614E0 * @note Size: 0x140 */ ListDirectorActor* OtakaraEventLink_2PBattle::getListDirectorActor() { P2ASSERTLINE(1699, getObject()); Otakara* obj = static_cast<Otakara*>(getObject()->getPSCreature()); P2ASSERTLINE(1701, obj); P2ASSERTLINE(1706, obj->isTreasure()); P2ASSERTLINE(1891, (int)obj->mBedamaType == Otakara::PSMBedama_None); return (ListDirectorActor*)PSMGetOtakaraEventD()->mActor; } /** * @note Address: 0x80461620 * @note Size: 0x170 */ WorkItem::WorkItem(Game::BaseItem* gameObj) : EventBase(gameObj, 2) , mLink(gameObj) { } /** * @note Address: 0x80461790 * @note Size: 0x30 */ void WorkItem::eventStart() { mLink.eventStart(); } /** * @note Address: 0x804617C0 * @note Size: 0x30 */ void WorkItem::eventRestart() { mLink.eventRestart(); } /** * @note Address: 0x804617F0 * @note Size: 0x30 */ void WorkItem::eventStop() { mLink.eventStop(); } /** * @note Address: 0x80461820 * @note Size: 0x30 */ void WorkItem::eventFinish() { mLink.eventFinish(); } /** * @note Address: 0x80461850 * @note Size: 0x1A0 */ void Otakara::setGoalOnyon(Game::Creature* onyon) { if ((int)mBedamaType == PSMBedama_Blue || (int)mBedamaType == PSMBedama_Red || (int)mBedamaType == PSMBedama_Yellow) { return; } Game::Creature* old = mOnyon; mOnyon = static_cast<Game::Onyon*>(onyon); otakaraCheckEvent(this); if (mOtaEvent->is2PBattle()) { if (!mOnyon) { if ((int)mBedamaType == PSMBedama_Blue || (int)mBedamaType == PSMBedama_Red) { P2ASSERTLINE(2014, mOtaEvent); ListDirectorActor* actor = static_cast<ListDirectorActor*>(static_cast<OtakaraEventLink_2PBattle*>(mOtaEvent)->getTargetDirector()->mActor); actor->remove(mOtaEvent); } } else if (old && old != mOnyon && (int)mBedamaType == PSMBedama_Yellow) { mOnyon = static_cast<Game::Onyon*>(old); P2ASSERTLINE(2030, mOtaEvent); ListDirectorActor* actor = static_cast<ListDirectorActor*>(static_cast<OtakaraEventLink_2PBattle*>(mOtaEvent)->getTargetDirector()->mActor); actor->remove(mOtaEvent); mOnyon = static_cast<Game::Onyon*>(onyon); P2ASSERTLINE(2041, mOtaEvent); actor = static_cast<ListDirectorActor*>(static_cast<OtakaraEventLink_2PBattle*>(mOtaEvent)->getTargetDirector()->mActor); actor->append(mOtaEvent); } } } /** * @note Address: 0x804619F0 * @note Size: 0xDC */ void Otakara::otakaraEventStart() { P2ASSERTLINE(2058, mOtaEvent); if (!is2PBattle()) { mEventLink.eventStart(); } P2ASSERTLINE(2074, mOtaEvent); mOtaEvent->eventStart(); } /** * @note Address: 0x80461ACC * @note Size: 0xDC */ void Otakara::otakaraEventRestart() { P2ASSERTLINE(2082, mOtaEvent); P2ASSERTLINE(2058, mOtaEvent); if (!is2PBattle()) { mEventLink.eventRestart(); } mOtaEvent->eventRestart(); } /** * @note Address: 0x80461BA8 * @note Size: 0xDC */ void Otakara::otakaraEventStop() { P2ASSERTLINE(2094, mOtaEvent); P2ASSERTLINE(2058, mOtaEvent); if (!is2PBattle()) { mEventLink.eventStop(); } mOtaEvent->eventStop(); } /** * @note Address: 0x80461C84 * @note Size: 0xDC */ void Otakara::otakaraEventFinish() { P2ASSERTLINE(2106, mOtaEvent); P2ASSERTLINE(2058, mOtaEvent); if (!is2PBattle()) { mEventLink.eventFinish(); } mOtaEvent->eventFinish(); } /** * @note Address: 0x80461D60 * @note Size: 0x224 */ PelletOtakara::PelletOtakara(Game::PelletOtakara::Object* gameObj, bool is2PBattle) : Otakara(gameObj) { if (!is2PBattle) { mOtaEvent = new OtakaraEventLink(gameObj); } else { mOtaEvent = new OtakaraEventLink_2PBattle(gameObj); } } /** * @note Address: 0x80461F84 * @note Size: 0x148 */ Otakara::~Otakara() { } /** * @note Address: 0x804620CC * @note Size: 0x1D4 */ PelletItem::PelletItem(Game::PelletItem::Object* gameObj) : Otakara(gameObj) { mOtaEvent = new OtakaraEventLink(gameObj); } /** * @note Address: 0x804622A0 * @note Size: 0x148 */ Piki::Piki(Game::Piki* p) : CreatureObj(p, 2) , mFreeCounter(-1) , mHummingCounter(-1) { } /** * @note Address: 0x804623E8 * @note Size: 0x180 */ void Piki::onCalcOn() { if (mFreeCounter != -1) { mFreeCounter++; } u32 a = mHummingCounter; if (static_cast<Game::Piki*>(mGameObj)->isWalking()) { if (a == -1) { mHummingCounter = 0; } else { mHummingCounter++; } Scene_Game* scene = PSMGetGameScene(); if (scene) { PikiHummingMgr* mgr = scene->mHummingMgr; P2ASSERTLINE(2180, mgr); mgr->play(this); } } else { mHummingCounter = -1; } } /** * @note Address: 0x80462568 * @note Size: 0xC */ void Piki::becomeFree() { mFreeCounter = 0; } /** * @note Address: 0x80462574 * @note Size: 0xC */ void Piki::becomeNotFree() { mFreeCounter = -1; } /** * @note Address: 0x80462580 * @note Size: 0x144 */ JAISound* Piki::startFreePikiSound(u32 soundID, u32 time, u32 flag) { if (PSMCheckSceneIsDemo() && soundID == PSSE_PK_VC_AKUBI) { return nullptr; } soundID = checkHappaChappySE(soundID); if (soundID == 0xffffffff) { return nullptr; } if (mFreeCounter == -1) { return startSound(soundID, flag); } if (mFreeCounter >= (int)time) { return startSound(soundID, flag); } return nullptr; } /** * @note Address: 0x804626C4 * @note Size: 0x70 */ JAISound* Piki::startPikiSound(JAInter::Object* obj, u32 soundID, u32 flag) { soundID = checkHappaChappySE(soundID); if (soundID == 0xffffffff) { return nullptr; } return obj->startSound(soundID, flag); } /** * @note Address: 0x80462734 * @note Size: 0xB4 */ JAISound* Piki::startPikiSetSound(JAInter::Object* obj, u32 soundID, PSGame::SeMgr::SetSeId set, u32 flag) { soundID = checkHappaChappySE(soundID); if (soundID == 0xffffffff) { return nullptr; } return PSSystem::getSeMgrInstance()->mSetSeList[(u8)set]->startSound(obj, soundID, flag); } /** * @note Address: 0x804627E8 * @note Size: 0x1D4 */ JAISound* Piki::startFreePikiSetSound(u32 soundID, PSGame::SeMgr::SetSeId set, u32 time, u32 flag) { if (PSMCheckSceneIsDemo() && soundID == PSSE_PK_VC_AKUBI) { return nullptr; } if (mFreeCounter == -1) { return startPikiSetSound(this, soundID, set, flag); } if (mFreeCounter >= (int)time) { return startPikiSetSound(this, soundID, set, flag); } return nullptr; } /** * @note Address: 0x804629BC * @note Size: 0x104 */ u32 Piki::checkHappaChappySE(u32 id) { if (static_cast<Game::Piki*>(mGameObj)->getKind() != Game::Bulbmin) { return id; } switch (id) { case PSSE_PK_VC_BREAKUP: id = PSSE_PK_HAPPA_BREAKUP; break; case PSSE_PK_VC_CALLED: id = PSSE_PK_HAPPA_CALLED; break; case PSSE_PK_VC_THROW_WAIT: id = PSSE_PK_HAPPA_THROW_WAIT; break; case PSSE_PK_VC_THROWN: id = PSSE_PK_HAPPA_THROWN; break; case PSSE_PK_VC_EATEN: id = PSSE_PK_HAPPA_EATEN; break; case PSSE_PK_VC_GHOST: id = PSSE_PK_HAPPA_GHOST; break; case PSSE_PK_VC_JUMP_INTO_HOLE: id = PSSE_PK_HAPPA_JUMP_HOLE; break; case PSSE_PK_VC_FALL: case PSSE_PK_VC_BLOWN_DEAD: id = PSSE_PK_HAPPA_FALL; break; case PSSE_PK_VC_PRESSED: id = PSSE_PK_HAPPA_PRESSED; break; case PSSE_PK_FLOWER_VOICE: id = PSSE_PK_HAPPA_FLOWER; break; case PSSE_PK_FLOWER_FALL_VOICE: id = PSSE_PK_HAPPA_FLOWER_FALL; break; case PSSE_PL_PULLOUT_PIKI: id = PSSE_PK_HAPPA_PULLOUT; break; case PSSE_PK_VC_LIFT_TRY: id = PSSE_PK_HAPPA_LIFT_TRY; break; case PSSE_PK_VC_LIFT_SUCCESS: id = PSSE_PK_HAPPA_LIFT_SUCCESS; break; case PSSE_PK_VC_LIFT_MOVE: id = PSSE_PK_HAPPA_LIFT_MOVE; break; case PSSE_PK_VC_ATTACK: id = PSSE_PK_HAPPA_ATTACK; break; case PSSE_PK_VC_DOPING: id = PSSE_PK_HAPPA_DOPING; break; case PSSE_PK_VC_DOPE_ATTACK: id = PSSE_PK_HAPPA_DOPE_ATTACK; break; case PSSE_PK_VC_DOPE_END: id = PSSE_PK_HAPPA_DOPE_END; break; case PSSE_PK_VC_SCATTERED: id = PSSE_PK_HAPPA_SCATTERED; break; case PSSE_PK_VC_DIGGING: id = PSSE_PK_HAPPA_DIGGING; break; case PSSE_PK_VC_SAVED: id = PSSE_PK_HAPPA_SAVED; break; case PSSE_PK_VC_PANIC: id = PSSE_PK_HAPPA_PANIC; break; case PSSE_PK_SE_ATTACH: case PSSE_PK_SE_KARABURI: case PSSE_PK_SE_ATTACKHIT: case PSSE_PK_SE_WATER_IN: case PSSE_PK_SE_HIT_FOUNTAIN: case PSSE_PK_SE_HIT_HARDWALL: case PSSE_PK_SE_HIT_SOFTWALL: case PSSE_PK_SE_HIT_CONCRETEWALL: case PSSE_PK_SE_HIT_BRIDGE: case PSSE_PK_SE_HIT_STONE: case PSSE_PK_SE_PULL_GRASS: case PSSE_EN_KURAGE_GET_PIKI: case PSSE_PK_SE_STABBED: case PSSE_PK_VC_DRINK: case PSSE_PK_SE_HIT_ELEC_GATE: break; default: id = -1; } return id; } /** * @note Address: 0x80462AC0 * @note Size: 0x138 */ Navi::Navi(Game::Navi* gameObj) : CreatureObj(gameObj, 2) , mCurrSound(nullptr) { } /** * @note Address: 0x80462BF8 * @note Size: 0x24 */ void Navi::init(u16 rappa) { mRappa.init(rappa); } /** * @note Address: 0x80462C1C * @note Size: 0x28 */ void Navi::setShacho() { mRappa.setId(137); } /** * @note Address: 0x80462C44 * @note Size: 0x50 */ void Navi::stopWaitVoice() { if (mCurrSound) { mCurrSound->stop(0); mCurrSound = nullptr; } } /** * @note Address: 0x80462C94 * @note Size: 0x108 */ JAISound* Navi::startSound(u32 soundID, u32 flag) { switch (soundID) { case PSSE_PL_SLEEP_ORIMA: case PSSE_PL_PUNCH_ORIMA: case PSSE_PL_GORYU_PLAYER: case PSSE_PL_WAKEUP_ORIMA: stopWaitVoice(); break; case PSSE_PL_ORIMA_DAMAGE: startSound(getManType() + PSSE_PL_DAMAGE_ORIMA, 0); return; } PSM::StartSoundArg arg(this, soundID, flag); JAISound* se = startSoundInner(arg); if (soundID >= PSSE_PL_WAIT_JUMP_ORIMA && soundID <= PSSE_PL_WAIT_CHAT_SHACHO) { mCurrSound = se; } /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stw r31, 0x2c(r1) mr r31, r5 stw r30, 0x28(r1) mr r30, r4 cmpwi r30, 0x897 stw r29, 0x24(r1) mr r29, r3 bge lbl_80462CE0 cmpwi r30, 0x88d bge lbl_80462CD4 cmpwi r30, 0x80f beq lbl_80462D20 b lbl_80462D48 lbl_80462CD4: cmpwi r30, 0x893 bge lbl_80462D48 b lbl_80462CF4 lbl_80462CE0: cmpwi r30, 0x89d beq lbl_80462CF4 bge lbl_80462D48 cmpwi r30, 0x899 bge lbl_80462D48 lbl_80462CF4: lwz r3, 0x90(r29) cmplwi r3, 0 beq lbl_80462D48 lwz r12, 0x10(r3) li r4, 0 lwz r12, 0x14(r12) mtctr r12 bctrl li r0, 0 stw r0, 0x90(r29) b lbl_80462D48 lbl_80462D20: bl getManType__Q23PSM4NaviFv mr r4, r3 mr r3, r29 lwz r12, 0x28(r29) addi r4, r4, 0x890 li r5, 0 lwz r12, 0x7c(r12) mtctr r12 bctrl b lbl_80462D80 lbl_80462D48: stw r29, 8(r1) mr r3, r29 addi r4, r1, 8 stw r30, 0xc(r1) stw r31, 0x10(r1) lwz r12, 0x28(r29) lwz r12, 0x30(r12) mtctr r12 bctrl cmplwi r30, 0x874 blt lbl_80462D80 cmplwi r30, 0x888 bgt lbl_80462D80 stw r3, 0x90(r29) lbl_80462D80: lwz r0, 0x34(r1) lwz r31, 0x2c(r1) lwz r30, 0x28(r1) lwz r29, 0x24(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /** * @note Address: 0x80462D9C * @note Size: 0x28 */ int Navi::getManType() { if (mRappa.mId == 13) { return 0; } if (mRappa.mId == 14) { return 4; // should be 1 but everything breaks } return 2; /* lwz r0, 0x88(r3) cmplwi r0, 0xd bne lbl_80462DB0 li r3, 0 blr lbl_80462DB0: cmplwi r0, 0xe li r3, 2 bnelr li r3, 1 blr */ } /** * @note Address: 0x80462DC4 * @note Size: 0xA0 */ JAISound* Navi::playShugoSE() { u32 sound; if (getManType() == 0) { sound = PSSE_PL_SHUGO; } else { sound = (getManType() - 1 == 1) + 0xa0; } return startSound(sound, 0); /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) lwz r4, 0x88(r3) cmplwi r4, 0xd bne lbl_80462DE4 li r0, 0 b lbl_80462DF8 lbl_80462DE4: cmplwi r4, 0xe bne lbl_80462DF4 li r0, 1 b lbl_80462DF8 lbl_80462DF4: li r0, 2 lbl_80462DF8: cmpwi r0, 0 bne lbl_80462E08 li r4, 7 b lbl_80462E40 lbl_80462E08: cmplwi r4, 0xd bne lbl_80462E18 li r5, 0 b lbl_80462E2C lbl_80462E18: cmplwi r4, 0xe bne lbl_80462E28 li r5, 1 b lbl_80462E2C lbl_80462E28: li r5, 2 lbl_80462E2C: addi r4, r5, -1 subfic r0, r5, 1 nor r0, r4, r0 srawi r4, r0, 0x1f addi r4, r4, 0xa0 lbl_80462E40: lwz r12, 0x28(r3) li r5, 0 lwz r12, 0x7c(r12) mtctr r12 bctrl lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /** * @note Address: 0x80462E64 * @note Size: 0xA0 */ JAISound* Navi::playKaisanSE() { u32 sound; if (getManType() == 0) { sound = PSSE_PL_KAISAN; } else { sound = ((getManType() - 1) == 1) + PSSE_PL_KAISAN_SHACHO; } return startSound(sound, 0); /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) lwz r4, 0x88(r3) cmplwi r4, 0xd bne lbl_80462E84 li r0, 0 b lbl_80462E98 lbl_80462E84: cmplwi r4, 0xe bne lbl_80462E94 li r0, 1 b lbl_80462E98 lbl_80462E94: li r0, 2 lbl_80462E98: cmpwi r0, 0 bne lbl_80462EA8 li r4, 0x808 b lbl_80462EE0 lbl_80462EA8: cmplwi r4, 0xd bne lbl_80462EB8 li r5, 0 b lbl_80462ECC lbl_80462EB8: cmplwi r4, 0xe bne lbl_80462EC8 li r5, 1 b lbl_80462ECC lbl_80462EC8: li r5, 2 lbl_80462ECC: addi r4, r5, -1 subfic r0, r5, 1 nor r0, r4, r0 srawi r4, r0, 0x1f addi r4, r4, 0x8a2 lbl_80462EE0: lwz r12, 0x28(r3) li r5, 0 lwz r12, 0x7c(r12) mtctr r12 bctrl lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /** * @note Address: 0x80462F04 * @note Size: 0x130 */ void Navi::playWalkSound(PSM::Navi::FootType type, int id) { int test = type + (id * 2); PSGame::RandId& randid = PSSystem::getSeMgrInstance()->mRandid; if (static_cast<Game::Navi*>(mGameObj)->isWalking()) { stopWaitVoice(); } randid.mId = 0.7f; JAISe* sound = randid.startSound(this, test, 2, 0); randid.mId = -1.0f; if (sound) { sound->setPortData(10, getManType()); } /* stwu r1, -0x20(r1) mflr r0 slwi r5, r5, 1 stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) add r30, r4, r5 stw r29, 0x14(r1) mr r29, r3 lwz r0, "sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) cmplwi r0, 0 bne lbl_80462F50 lis r3, lbl_8049CFD0@ha lis r5, lbl_8049CFB8@ha addi r3, r3, lbl_8049CFD0@l li r4, 0x237 addi r5, r5, lbl_8049CFB8@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80462F50: lwz r3, 0x2c(r29) lwz r4, "sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) lwz r12, 0(r3) addi r31, r4, 0x24 lwz r12, 0x21c(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_80462F9C lwz r3, 0x90(r29) cmplwi r3, 0 beq lbl_80462F9C lwz r12, 0x10(r3) li r4, 0 lwz r12, 0x14(r12) mtctr r12 bctrl li r0, 0 stw r0, 0x90(r29) lbl_80462F9C: lfs f0, lbl_80520C88@sda21(r2) cmplwi r29, 0 mr r4, r29 stfs f0, 0(r31) beq lbl_80462FB4 addi r4, r29, 0x30 lbl_80462FB4: mr r3, r31 mr r5, r30 li r6, 2 li r7, 0 bl startSound__Q26PSGame6RandIdFPQ27JAInter6ObjectUlUlUl lfs f0, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13) cmplwi r3, 0 stfs f0, 0(r31) beq lbl_80463018 lwz r0, 0x88(r29) cmplwi r0, 0xd bne lbl_80462FEC li r0, 0 b lbl_80463000 lbl_80462FEC: cmplwi r0, 0xe bne lbl_80462FFC li r0, 1 b lbl_80463000 lbl_80462FFC: li r0, 2 lbl_80463000: lwz r12, 0x10(r3) clrlwi r5, r0, 0x10 li r4, 0xa lwz r12, 8(r12) mtctr r12 bctrl lbl_80463018: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /** * @note Address: 0x80463034 * @note Size: 0x158 */ Cluster::Cluster(Game::Creature* gameObj, PSSystem::ClusterSe::Factory& factory) : CreatureObj(gameObj, 2) { mClusterSeMgr = new PSSystem::ClusterSe::Mgr; mClusterSeMgr->constructParts(factory); } /** * @note Address: 0x8046318C * @note Size: 0x60 */ void Cluster::startClusterSound(u8 count) { exec(); mClusterSeMgr->play(count, this); } } // namespace PSM /** * @note Address: 0x804631EC * @note Size: 0x58 */ void PSSetCurCameraNo(u8 cams) { static_cast<PSM::ObjCalc_SingleGame*>(PSSystem::SingletonBase<PSM::ObjCalcBase>::getInstance())->mPlayerNum = cams; } /** * @note Address: 0x80463244 * @note Size: 0x8 */ f32 PSMGetNoukouDist() { return PSM::CreaturePrm::cNoukouDistance; } /** * @note Address: 0x8046324C * @note Size: 0x70 */ void PSSetLastBeedamaDirection(bool isOlimar, bool isOn) { PSM::ActorDirector_TrackOn* director; if (isOlimar) { director = PSMGetBeedamaForOrimerD(); } else { director = PSMGetBeedamaForLugieD(); } if (director) { if (isOn) { director->directOn(); } else { director->directOff(); } } }
0
0.87061
1
0.87061
game-dev
MEDIA
0.36975
game-dev
0.94849
1
0.94849
kunitoki/yup
1,824
thirdparty/rive/include/rive/generated/data_bind/bindable_property_number_base.hpp
#ifndef _RIVE_BINDABLE_PROPERTY_NUMBER_BASE_HPP_ #define _RIVE_BINDABLE_PROPERTY_NUMBER_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/data_bind/bindable_property.hpp" namespace rive { class BindablePropertyNumberBase : public BindableProperty { protected: typedef BindableProperty Super; public: static const uint16_t typeKey = 473; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case BindablePropertyNumberBase::typeKey: case BindablePropertyBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } static const uint16_t propertyValuePropertyKey = 636; protected: float m_PropertyValue = 0.0f; public: inline float propertyValue() const { return m_PropertyValue; } void propertyValue(float value) { if (m_PropertyValue == value) { return; } m_PropertyValue = value; propertyValueChanged(); } Core* clone() const override; void copy(const BindablePropertyNumberBase& object) { m_PropertyValue = object.m_PropertyValue; BindableProperty::copy(object); } bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { switch (propertyKey) { case propertyValuePropertyKey: m_PropertyValue = CoreDoubleType::deserialize(reader); return true; } return BindableProperty::deserialize(propertyKey, reader); } protected: virtual void propertyValueChanged() {} }; } // namespace rive #endif
0
0.952141
1
0.952141
game-dev
MEDIA
0.470317
game-dev
0.781433
1
0.781433
jswigart/omni-bot
7,947
Installer/Files/et/nav/urbanterritory.gm
//========================================================================================== // // UrbanTerritory.gm // // Who When What //------------------------------------------------------------------------------------------ // palota 20 April 2010 Initial Script // palota 23 October 2010 DYNAMITE_safe, ROUTE_allies_passage, mg42 aim vectors // palota 12 November 2011 fixed ladders paththrough navigation, added paththrough navigation to destroy sewer hatches, disable bot push on roof pipes, higher SNIPE priority, increased ATTACK max users // //========================================================================================== // global Map = { Debug=0, safeIsDestroyed=false, safePlantedTime=null, IgnoreEntPositions = { Vector3(-1441, 799, 30), Vector3(-835, -255, 66), Vector3(-798, -273, 65), Vector3(-874, -275, 65), Vec3(1300, 2517, -2), Vec3(326, 880, 0), Vec3(336, -801, 0) }, DestroyBreakable1 = function(_this, position, facing) { for(i=0; i<5; i+=1) { ent = TraceLine( position, position + 200*facing, 0, TRACE.SHOT, _this.Bot.GetGameId(), false ).entity; if(!ent || GetEntClass(ent)!=CLASS.BREAKABLE){ break; } id = GetGameIdFromEntity(ent); Util.MapDebugPrint("destroying breakable " + id, true); _this.Bot.HoldButton(BTN.FORWARD, 5); _this.AddAimRequest(Priority.High, "facing", facing); _this.AddWeaponRequest(Priority.High, WEAPON.KNIFE); _this.BlockForWeaponChange(WEAPON.KNIFE); for(j=0; j<30; j+=1) { if (!EntityIsValid(id)){ break; } _this.Bot.HoldButton(BTN.ATTACK1, 0.5); if(facing.z < -0.7){ _this.Bot.HoldButton(BTN.CROUCH, 0.4); } _this.Bot.ResetStuckTime(); sleep(0.5); } } }, DestroyBreakable = function(_this, position, facing) { Map.DestroyBreakable1(_this, position, facing); sleep(3); }, Navigation = { door = { navigate = function(_this) { _this.AddAimRequest(Priority.High, "facing", Vec3(0,-1,0)); sleep(1.5); } }, long_ladder = //to the roof { navigate = function(_this) { _this.AddAimRequest(Priority.High, "position", Vec3(-1389.056, -414.324, 422.125)); sleep(5); } }, ladder_down = //roof { navigate = function(_this) { // at top of ladder, turn completely around _this.AddAimRequest(Priority.High, "position", Vector3(392.873, -519.284, 288.125)); _this.Bot.HoldButton(BTN.CROUCH, 1.5); sleep(0.5); if(_this.Bot.GetPosition().z > 380){ _this.Bot.HoldButton(BTN.BACKWARD, 0.5); sleep(0.5); } sleep(1); } }, ladder_sewer = //route from the axis spawn to sewerage { navigate = function(_this) { Map.DestroyBreakable1(_this, Vec3(-1384.126, 702.168, 70.125), Vec3(0.222, -0.003, -0.975)); _this.AddAimRequest(Priority.High, "facing", Vector3(-0.3,0,-0.9)); _this.Bot.HoldButton(BTN.FORWARD,BTN.CROUCH, 1.5); sleep(0.3); _this.AddAimRequest(Priority.High, "facing", Vector3(0.3,0,-0.9)); sleep(2); } }, hatch_truck = { navigate = function(_this) { Map.DestroyBreakable(_this, Vec3(1304.875, 2523.771, -16.733), Vec3(0.635, 0.003, 0.773)); } }, hatch_center = { navigate = function(_this) { Map.DestroyBreakable(_this, Vec3(330.125, 884.487, -18.482), Vec3(-0.315, 0.015, 0.949)); } }, hatch_bank = { navigate = function(_this) { Map.DestroyBreakable(_this, Vec3(342.275, -806.875, -11.855), Vec3(0.020, -0.392, 0.920)); } }, ductfan = { navigate = function(_this) { Map.DestroyBreakable(_this, Vec3(1202.515, -1088.875, -11.328), Vec3(-0.004, -0.353, 0.935)); } }, }, Gold_Taken = function( trigger ) { if(!Map.safeIsDestroyed){ Map.Safe_Destroyed(); } Util.EnableGoal("DEFEND_truck.*"); SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_truck1"); SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_truck4"); SetAvailableMapGoals( TEAM.ALLIES, false, "DEFEND_truck5"); SetAvailableMapGoals( TEAM.ALLIES, false, "DEFEND_safe.*"); }, Gold_Returned = function( trigger ) { Util.DisableGoal("DEFEND_truck.*"); SetAvailableMapGoals( TEAM.ALLIES, true, "DEFEND_safe.*"); }, Safe_Planted = function( trigger ) { SetAvailableMapGoals( TEAM.ALLIES, false, "DEFEND_safe8"); }, Safe_Destroyed = function() { Map.safeIsDestroyed = true; SetAvailableMapGoals( TEAM.AXIS, true, "FLAG_Gold"); SetAvailableMapGoals( TEAM.AXIS, false, "ATTACK_safe.*"); SetAvailableMapGoals( TEAM.AXIS, false, "DYNAMITE_safe"); Util.MapDebugPrint( "Safe_Destroyed" ); }, }; global OnMapLoad = function() { OnTrigger( "Axis have stolen Gold!", Map.Gold_Taken ); OnTrigger( "Flag returned Gold!", Map.Gold_Returned ); OnTrigger( "Planted at The Safe.", Map.Safe_Planted ); // grenade goals send a trigger when the target entity is destroyed // replacing the Watch_Safe thread with this as an example since this is a lot easier // /bot goal_create grenade safetrigger /bot goal_setproperty trace while pointing at the explosive ent // feel free to remove these comments. OnTrigger( "GRENADE_safetrigger Exploded.", Map.Safe_Destroyed ); // a re-usable region trigger to disable bot pushing and combat movement. this one is around the rooftop ladder OnTriggerRegion(AABB(-213,-640.875,265.125,476.875,-407.125,510),RegionTrigger.DisableBotPush); Util.DisableGoal("GRENADE.*"); SetAvailableMapGoals( TEAM.AXIS, false, "REPAIRMG.*"); SetAvailableMapGoals( TEAM.ALLIES, false, "CAPPOINT.*"); Util.DisableGoal("DEFEND_truck.*"); Util.LimitToTeam( TEAM.ALLIES, "TRIPMINE_l.*"); SetAvailableMapGoals( TEAM.AXIS, false, "FLAG_Gold"); SetGoalPriority("MOUNTMG42.*", 0, TEAM.AXIS, CLASS.ENGINEER); SetGoalPriority("SNIPE.*", 0.81, TEAM.AXIS); Util.SetMaxUsersInProgress(9, "ATTACK.*"); Util.SetMaxUsersInProgress(1, "SNIPE.*"); Util.SetMaxUsersInProgress(1, "MOUNTMG42.*"); SetMapGoalProperties( "DEFEND.*", {mincamptime=40, maxcamptime=150} ); SetMapGoalProperties( "MOBILEMG42_.*", {mincamptime=90, maxcamptime=300} ); SetMapGoalProperties( "MOUNTMG42_.*", {mincamptime=90, maxcamptime=300} ); MapRoutes = { FLAG_Gold = { ROUTE_axis_spawn = { ROUTE_north1 = { ROUTE_floor1 = {}}, ROUTE_north3 = { ROUTE_floor2 = {}}, ROUTE_north4 = { ROUTE_floor2 = {}}, ROUTE_sewer_center = { Weight=4, ROUTE_xxx = {}, ROUTE_sewer_south = { Weight=3, ROUTE_shaft1 = {}, ROUTE_shaft2 = {}, }, }, ROUTE_roof = {}, ROUTE_south_west = { ROUTE_marijuana = { ROUTE_floor1 = {}}}, ROUTE_disco = { ROUTE_floor2 = {}}, } }, CAPPOINT_van = { ROUTE_gold1 = { ROUTE_north1 = {}, ROUTE_north3 = {}, ROUTE_north4 = { Weight=2 }, ROUTE_sewer_south = { Weight=3, ROUTE_sewer_north = {}}, } }, DEFEND_safe1 = { ROUTE_allied_spawn = { ROUTE_back = { Weight=2 }, ROUTE_entrance = {}, ROUTE_allies2 = {}, } }, DEFEND_truck1 = { ROUTE_allied_spawn = { ROUTE_allies_passage = {}, ROUTE_north1 = {}, ROUTE_north3 = {}, } }, }; MapRoutes.DYNAMITE_safe = MapRoutes.FLAG_Gold; MapRoutes.ATTACK_safe3 = MapRoutes.FLAG_Gold; MapRoutes.ATTACK_safe4 = MapRoutes.ATTACK_safe3; MapRoutes.DEFEND_safe2 = MapRoutes.DEFEND_safe1; MapRoutes.DEFEND_safe5 = MapRoutes.DEFEND_safe1; MapRoutes.DEFEND_safe7 = MapRoutes.DEFEND_safe1; MapRoutes.DEFEND_safe8 = MapRoutes.DEFEND_safe1; MapRoutes.DEFEND_truck3 = MapRoutes.DEFEND_truck1; MapRoutes.DEFEND_truck4 = MapRoutes.DEFEND_truck1; Util.Routes(MapRoutes); }; global OnBotJoin = function( bot ) { bot.TargetBreakableDist = 250.0; if (!Map.IgnoreEnt) { Map.IgnoreEnt = table(); foreach(i and pos in Map.IgnoreEntPositions) { ent = TraceLine( pos, pos + Vector3(10,10,10), 0, TRACE.SHOT, 0, false ).entity; if(ent) { Map.IgnoreEnt[i] = ent; Util.MapDebugPrint("Ignoring entity " + GetGameIdFromEntity(ent), true); } } } foreach(ent in Map.IgnoreEnt) { bot.IgnoreTarget(ent, 99999); } };
0
0.982536
1
0.982536
game-dev
MEDIA
0.992794
game-dev
0.835354
1
0.835354
chown2/lunaticvibesf
12,969
src/game/scene/scene.cpp
#include "scene.h" #include <cstddef> #include <format> #include <functional> #include <memory> #include <common/assert.h> #include <common/beat.h> #include <common/log.h> #include <common/sysutil.h> #include <config/cfg_profile.h> #include <config/config_mgr.h> #include <game/graphics/font.h> #include <game/graphics/graphics.h> #include <game/graphics/sprite.h> #include <game/graphics/texture_video.h> #include <game/runtime/generic_info.h> #include <game/runtime/i18n.h> #include <game/runtime/state.h> #include <game/scene/scene_context.h> #include <game/skin/skin_lr2_debug.h> #include <game/skin/skin_mgr.h> #include <game/sound/sound_mgr.h> #include <game/sound/sound_sample.h> #include <imgui.h> // prototype SceneBase::SceneBase(const std::shared_ptr<SkinMgr>& skinMgr, SkinType skinType, unsigned rate, bool backgroundInput) : _type(SceneType::NOT_INIT), _input(ConfigMgr::Profile()->get(cfg::P_INPUT_POLLING_RATE, 1000), backgroundInput), _rate(rate) { // Disable skin caching for now. dst options are changing all the time const bool simple_skin = gInCustomize && skinType != SkinType::THEME_SELECT; if (skinMgr) { skinMgr->reload(skinType, gInCustomize && simple_skin); pSkin = skinMgr->get(skinType); } else { LOG_VERBOSE << "[SceneBase] No skinMgr"; } int notificationPosY = 480; int notificationWidth = 640; if (pSkin && ((!gInCustomize && skinType != SkinType::THEME_SELECT) || (gInCustomize && skinType == SkinType::THEME_SELECT))) { const int x = pSkin->info.resolution.first; const int y = pSkin->info.resolution.second; lunaticvibes::window::graphics_resize_canvas(x, y); notificationPosY = y; notificationWidth = x; } if (!simple_skin) { int faceIndex; const Path fontPath = getSysMonoFontPath(nullptr, &faceIndex, i18n::getCurrentLanguage()); const int notificationHeight = 20; const int textHeight = 24; _fNotifications = std::make_shared<lunaticvibes::Font>(fontPath, static_cast<int>(textHeight * 1.5), faceIndex); _texNotificationsBG = std::make_shared<Texture>(0x000000ff); for (size_t i = 0; i < _sNotifications.size(); ++i) { SpriteText::SpriteTextBuilder textBuilder; textBuilder.font = _fNotifications; textBuilder.textInd = IndexText(static_cast<size_t>(IndexText::_OVERLAY_NOTIFICATION_0) + i); textBuilder.align = TextAlign::TEXT_ALIGN_LEFT; textBuilder.ptsize = textHeight; _sNotifications[i] = textBuilder.build(); _sNotifications[i]->setMotionLoopTo(0); SpriteStatic::SpriteStaticBuilder bgBuilder; bgBuilder.texture = _texNotificationsBG; _sNotificationsBG[i] = bgBuilder.build(); _sNotificationsBG[i]->setMotionLoopTo(0); notificationPosY -= notificationHeight; MotionKeyFrame f; f.time = 0; f.param.rect = Rect(0, notificationPosY, notificationWidth, notificationHeight); f.param.accel = MotionKeyFrameParams::CONSTANT; f.param.blend = BlendMode::ALPHA; f.param.filter = true; f.param.angle = 0; f.param.center = Point(0, 0); f.param.color = 0xffffff80; _sNotificationsBG[i]->appendMotionKeyFrame(f); f.param.rect.y += (notificationHeight - textHeight) / 2; f.param.rect.h = textHeight; f.param.color = 0xffffffff; _sNotifications[i]->appendMotionKeyFrame(f); } } _input.register_p("DEBUG_TOGGLE", std::bind_front(&SceneBase::DebugToggle, this)); _input.register_p("GLOBALFUNC", std::bind_front(&SceneBase::GlobalFuncKeys, this)); _input.register_p("SKIN_MOUSE_CLICK", std::bind_front(&SceneBase::MouseClick, this)); _input.register_h("SKIN_MOUSE_DRAG", std::bind_front(&SceneBase::MouseDrag, this)); _input.register_r("SKIN_MOUSE_RELEASE", std::bind_front(&SceneBase::MouseRelease, this)); if (pSkin && !(gNextScene == SceneType::SELECT && skinType == SkinType::THEME_SELECT)) { State::resetTimer(); State::set(IndexText::_OVERLAY_TOPLEFT, ""); // Skin may be cached. Reset mouse status pSkin->setHandleMouseEvents(true); } } SceneBase::~SceneBase() { LVF_ASSERT(!_input.isRunning()); } void SceneBase::update() { auto t = lunaticvibes::Time::now(); if (pSkin) { // update skin pSkin->update(t); auto [x, y] = _input.getCursorPos(); pSkin->update_mouse(x, y); checkAndStartTextEdit(); // update notifications { std::unique_lock lock(gOverlayContext._mutex); // notifications expire check while (!gOverlayContext.notifications.empty() && (t - gOverlayContext.notifications.begin()->first).norm() > static_cast<decltype(std::declval<timeNormRes>().count())>(10 * 1000)) // 10s { gOverlayContext.notifications.pop_front(); } // update notification texts auto itNotifications = gOverlayContext.notifications.rbegin(); for (size_t i = 0; i < _sNotifications.size(); ++i) { if (itNotifications != gOverlayContext.notifications.rend()) { State::set(IndexText(static_cast<size_t>(IndexText::_OVERLAY_NOTIFICATION_0) + i), itNotifications->second); ++itNotifications; } else { State::set(IndexText(static_cast<size_t>(IndexText::_OVERLAY_NOTIFICATION_0) + i), ""); } } } // update top-left texts for (auto& bg : _sNotificationsBG) { if (bg != nullptr) bg->update(t); } for (auto& notification : _sNotifications) { if (notification != nullptr) notification->update(t); } // update videos TextureVideo::updateAll(); } if ((!gInCustomize || _type == SceneType::CUSTOMIZE) && shouldShowImgui()) { lunaticvibes::window::ImGuiNewFrame(); updateImgui(); ImGui::Render(); } } void SceneBase::MouseClick(InputMask& m, const lunaticvibes::Time& t) { if (!pSkin) return; if (m[Input::Pad::M1]) { auto [x, y] = _input.getCursorPos(); pSkin->update_mouse_click(x, y); } } void SceneBase::MouseDrag(InputMask& m, const lunaticvibes::Time& t) { if (!pSkin) return; if (m[Input::Pad::M1]) { auto [x, y] = _input.getCursorPos(); pSkin->update_mouse_drag(x, y); } } void SceneBase::MouseRelease(InputMask& m, const lunaticvibes::Time& t) { if (!pSkin) return; if (m[Input::Pad::M1]) { pSkin->update_mouse_release(); } } bool SceneBase::queuedScreenshot = false; bool SceneBase::queuedFPS = false; bool SceneBase::showFPS = false; void SceneBase::draw() const { if (pSkin) { pSkin->draw(); } { std::shared_lock lock(gOverlayContext._mutex); if (!gOverlayContext.notifications.empty()) { // draw notifications at the bottom. One string per line for (size_t i = 0; i < gOverlayContext.notifications.size() && i < _sNotifications.size(); ++i) { if (_sNotificationsBG[i] != nullptr) { _sNotificationsBG[i]->draw(); } if (_sNotifications[i] != nullptr) { _sNotifications[i]->updateText(); _sNotifications[i]->draw(); } } } } if (queuedScreenshot) { Path p = "screenshot"; p /= std::format("LV {:04d}-{:02d}-{:02d} {:02d}-{:02d}-{:02d}.png", State::get(IndexNumber::DATE_YEAR), State::get(IndexNumber::DATE_MON), State::get(IndexNumber::DATE_DAY), State::get(IndexNumber::DATE_HOUR), State::get(IndexNumber::DATE_MIN), State::get(IndexNumber::DATE_SEC)); lunaticvibes::window::queue_screenshot(std::move(p)); SoundMgr::playSysSample(SoundChannelType::KEY_SYS, eSoundSample::SOUND_SCREENSHOT); queuedScreenshot = false; } if (queuedFPS) { showFPS = !showFPS; queuedFPS = false; } } static bool should_show_text_overlay() { for (size_t i = 0; i < 4; ++i) if (!State::get(IndexText(static_cast<int>(IndexText::_OVERLAY_TOPLEFT) + i)).empty()) return true; return false; } bool SceneBase::shouldShowImgui() const { return showFPS || should_show_text_overlay() || lunaticvibes::g_enable_imgui_debug_monitor; } void SceneBase::updateImgui() { LVF_DEBUG_ASSERT(IsMainThread()); // TODO: implement showFPS without Imgui, as Imgui takes over 10% FPS. if (showFPS || should_show_text_overlay()) { ImGui::SetNextWindowPos(ImVec2(0.f, 0.f), ImGuiCond_Always); ImGui::PushStyleColor(ImGuiCol_WindowBg, {0.f, 0.f, 0.f, 0.4f}); if (ImGui::Begin("##textoverlay", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize)) { if (showFPS) { ImGui::PushID("##fps"); ImGui::Text("FPS: Render %d | Input %d", State::get(IndexNumber::FPS), State::get(IndexNumber::INPUT_DETECT_FPS)); ImGui::PopID(); } static const char* overlayTextID[] = { "##overlaytext1", "##overlaytext2", "##overlaytext3", "##overlaytext4", }; size_t count = 0; for (size_t i = 0; i < 4; ++i) { auto idx = IndexText(static_cast<int>(IndexText::_OVERLAY_TOPLEFT) + i); if (!State::get(idx).empty()) { ImGui::PushID(overlayTextID[count++]); ImGui::TextUnformatted(State::get(idx).c_str()); ImGui::PopID(); } } ImGui::End(); } ImGui::PopStyleColor(); } if (lunaticvibes::g_enable_imgui_debug_monitor) { if (imguiShowMonitorLR2DST) imguiMonitorLR2DST(); if (imguiShowMonitorNumber) imguiMonitorNumber(); if (imguiShowMonitorOption) imguiMonitorOption(); if (imguiShowMonitorSlider) imguiMonitorSlider(); if (imguiShowMonitorSwitch) imguiMonitorSwitch(); if (imguiShowMonitorText) imguiMonitorText(); if (imguiShowMonitorBargraph) imguiMonitorBargraph(); if (imguiShowMonitorTimer) imguiMonitorTimer(); } } void SceneBase::DebugToggle(InputMask& p, const lunaticvibes::Time& t) { if (!(!gInCustomize || _type == SceneType::CUSTOMIZE)) return; if (!lunaticvibes::g_enable_imgui_debug_monitor) return; if (p[Input::F1]) { imguiShowMonitorLR2DST = !imguiShowMonitorLR2DST; } if (p[Input::F2]) { imguiShowMonitorNumber = !imguiShowMonitorNumber; } if (p[Input::F3]) { imguiShowMonitorOption = !imguiShowMonitorOption; } if (p[Input::F4]) { imguiShowMonitorSlider = !imguiShowMonitorSlider; } if (p[Input::F5]) { imguiShowMonitorSwitch = !imguiShowMonitorSwitch; } if (p[Input::F6]) { imguiShowMonitorText = !imguiShowMonitorText; } if (p[Input::F7]) { imguiShowMonitorBargraph = !imguiShowMonitorBargraph; } if (p[Input::F8]) { imguiShowMonitorTimer = !imguiShowMonitorTimer; } } bool SceneBase::isInTextEdit() const { return inTextEdit; } IndexText SceneBase::textEditType() const { return inTextEdit ? pSkin->textEditType() : IndexText::INVALID; } void SceneBase::startTextEdit(bool clear) { if (pSkin) { pSkin->startTextEdit(clear); inTextEdit = true; } } void SceneBase::stopTextEdit(bool modify) { if (pSkin) { inTextEdit = false; pSkin->stopTextEdit(modify); } } void SceneBase::GlobalFuncKeys(InputMask& m, const lunaticvibes::Time& t) { if (m[Input::F6]) { queuedScreenshot = true; } if (m[Input::F7]) { queuedFPS = true; } }
0
0.96843
1
0.96843
game-dev
MEDIA
0.583307
game-dev,desktop-app
0.978412
1
0.978412
google/pienoon
5,635
src/multiplayer_director.h
// Copyright 2015 Google Inc. All rights reserved. // // 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 MULTIPLAYER_DIRECTOR_H_ #define MULTIPLAYER_DIRECTOR_H_ #include <vector> #include "common.h" #include "controller.h" #include "game_state.h" #include "multiplayer_controller.h" #include "multiplayer_generated.h" #include "pie_noon_game.h" #ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES #include "gpg_multiplayer.h" #endif namespace fpl { namespace pie_noon { // MultiplayerDirector is used for the multiscreen version of Pie Noon. // // It is responsible for managing the timings of all of the turns, receiving the // messages from clients saying what actions they wish to perform, and for the // formatting and sending of multiplayer messages between the host and client. // // When you create MultiplayerDirector, you must register multiple // MultiplayerControllers (one for each player), which is how // MultiplayerDirector can direct what the characters do each turn. class MultiplayerDirector { public: MultiplayerDirector(); // Give the multiplayer director everything it will need. void Initialize(GameState *gamestate_ptr, const Config *config); #ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES // Register a pointer to GPGMultiplayer, so we can send multiplayer messages. void RegisterGPGMultiplayer(GPGMultiplayer *gpg_multiplayer) { gpg_multiplayer_ = gpg_multiplayer; } #endif // Register one MultiplayerController assigned to each player. void RegisterController(MultiplayerController *); // Call this each frame if multiplayer gameplay is going on. void AdvanceFrame(WorldTime delta_time); // Start a new multi-screen game. void StartGame(); // End the multi-screen game. void EndGame(); // If testing on PC, pass in your PC keyboard input system to use debug // keys for testing turn-based timings. void SetDebugInputSystem(fplbase::InputSystem *input) { debug_input_system_ = input; } #ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES // Tell one of your connected players what his player number is. void SendPlayerAssignmentMsg(const std::string &instance, CharacterId id); // Broadcast start-of-turn to the players. void SendStartTurnMsg(unsigned int turn_seconds); // Broadcast end-of-game message to the players. void SendEndGameMsg(); // Broadcast player health to the players. void SendPlayerStatusMsg(); #endif // Takes effect when the next turn starts. void set_seconds_per_turn(unsigned int seconds) { seconds_per_turn_ = seconds; } unsigned int seconds_per_turn() { return seconds_per_turn_; } // First turn is numbered 1, second turn numbered 2, etc. // Is 0 before the first turn starts. unsigned int turn_number() { return turn_number_; } // Tell the multiplayer director about a player's input. void InputPlayerCommand(CharacterId id, const multiplayer::PlayerCommand &command); // Internally, call this when a player has been hit by a pie. The multiplayer // director will decide whether that player should be "stunned" by the hit // and have one or more of his buttons locked for a turn. void TriggerPlayerHitByPie(CharacterId player, int damage); // Is this an AI player or a human player? bool IsAIPlayer(CharacterId player); // How long until the current turn ends? 0 if outside a turn. WorldTime turn_timer() { return turn_timer_; } // How long until the next turn starts? 0 if in a turn. WorldTime start_turn_timer() { return start_turn_timer_; } // Set the number of AI players. The last N players are AIs. void set_num_ai_players(unsigned int n) { num_ai_players_ = n; } unsigned int num_ai_players() const { return num_ai_players_; } private: struct Command { CharacterId aim_at; bool is_firing; bool is_blocking; Command() : aim_at(-1), is_firing(false), is_blocking(false) {} }; void TriggerStartOfTurn(); void TriggerEndOfTurn(); unsigned int CalculateSecondsPerTurn(unsigned int turn_number); // Get all the players' healths so we can send them in an update std::vector<uint8_t> ReadPlayerHealth(); // Tell the multiplayer director to choose AI commands for this player. void ChooseAICommand(CharacterId id); void DebugInput(fplbase::InputSystem *input); // Get all the players' onscreen splats to send in an update std::vector<uint8_t> ReadPlayerSplats(); GameState *gamestate_; // Pointer to the gamestate object const Config *config_; // Pointer to the config structure std::vector<MultiplayerController *> controllers_; std::vector<uint8_t> character_splats_; // How long the current turn lasts. WorldTime turn_timer_; // In how long to start the next turn. WorldTime start_turn_timer_; unsigned int seconds_per_turn_; unsigned int turn_number_; unsigned int num_ai_players_; // the last N players are AI. fplbase::InputSystem *debug_input_system_; std::vector<Command> commands_; #ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES GPGMultiplayer *gpg_multiplayer_ = nullptr; #endif bool game_running_; }; } // pie_noon } // fpl #endif // MULTIPLAYER_DIRECTOR_H_
0
0.77658
1
0.77658
game-dev
MEDIA
0.640577
game-dev,networking
0.691551
1
0.691551
dr3ams/Roguelike-Adventures-and-Dungeons-2
1,177
scripts/noflying.zs
import crafttweaker.api.events.CTEventManager; import crafttweaker.api.entity.MCEntity; import crafttweaker.api.entity.MCLivingEntity; import crafttweaker.api.player.MCPlayerEntity; import crafttweaker.api.event.tick.MCPlayerTickEvent; import crafttweaker.api.data.IData; import crafttweaker.api.data.INumberData; import crafttweaker.api.potion.MCPotionEffectInstance; import crafttweaker.api.potion.MCPotionEffect; CTEventManager.register<MCPlayerTickEvent>((event) => { if (event.isEnd()) { return; } val player = event.player; if (player.world.gameTime % 100 != 0) { return; } if (player.isPotionActive(<effect:bountifulbaubles:flight>) && player.inventory.hasIItemStack(<item:apotheosis:potion_charm>.withTag({Potion: "bountifulbaubles:flight" as string}).mutable().anyDamage())) { player.removePotionEffect(<effect:bountifulbaubles:flight>); player.inventory.remove(<item:apotheosis:potion_charm>.withTag({Potion: "bountifulbaubles:flight" as string}).mutable().anyDamage()); player.sendMessage("§l§oA strange power causes the charm of flight to collapse in on itself destroying the item."); } }); //
0
0.781142
1
0.781142
game-dev
MEDIA
0.962859
game-dev
0.686589
1
0.686589
unascribed/Ears
6,469
platform-forge-1.2/src/main/java/com/unascribed/ears/LayerEars.java
package com.unascribed.ears; import static org.lwjgl.opengl.GL11.*; import java.awt.image.BufferedImage; import org.lwjgl.opengl.GL11; import com.unascribed.ears.common.EarsCommon; import com.unascribed.ears.common.EarsFeaturesStorage; import com.unascribed.ears.api.features.EarsFeatures; import com.unascribed.ears.common.debug.EarsLog; import com.unascribed.ears.common.legacy.UnmanagedEarsRenderDelegate; import com.unascribed.ears.common.render.EarsRenderDelegate.BodyPart; import com.unascribed.ears.common.util.Decider; import com.unascribed.ears.legacy.LegacyHelper; import cpw.mods.fml.client.FMLClientHandler; import net.minecraft.src.EntityPlayer; import net.minecraft.src.ItemArmor; import net.minecraft.src.ItemStack; import net.minecraft.src.ModelBiped; import net.minecraft.src.ModelBox; import net.minecraft.src.ModelRenderer; import net.minecraft.src.OpenGlHelper; import net.minecraft.src.RenderEngine; import net.minecraft.src.RenderPlayer; import net.minecraft.src.Tessellator; public class LayerEars { private RenderPlayer render; private float tickDelta; public void doRenderLayer(RenderPlayer render, EntityPlayer entity, float limbDistance, float partialTicks) { EarsLog.debug(EarsLog.Tag.PLATFORM_RENDERER, "render({}, {}, {})", entity, limbDistance, partialTicks); this.render = render; this.tickDelta = partialTicks; delegate.render(entity); } public void renderRightArm(RenderPlayer render, EntityPlayer entity) { EarsLog.debug(EarsLog.Tag.PLATFORM_RENDERER, "renderRightArm({}, {})", render, entity); this.render = render; this.tickDelta = 0; delegate.render(entity, BodyPart.RIGHT_ARM); } private final UnmanagedEarsRenderDelegate<EntityPlayer, ModelRenderer> delegate = new UnmanagedEarsRenderDelegate<EntityPlayer, ModelRenderer>() { @Override protected boolean isVisible(ModelRenderer modelPart) { return modelPart.showModel; } @Override public boolean isSlim() { return LegacyHelper.isSlimArms(peer.username); } @Override protected EarsFeatures getEarsFeatures() { if (Ears.earsSkinFeatures.containsKey(peer.skinUrl)) { EarsFeatures feat = Ears.earsSkinFeatures.get(peer.skinUrl); EarsFeaturesStorage.INSTANCE.put(peer.username, LegacyHelper.getUuid(peer.username), feat); return feat; } return EarsFeatures.DISABLED; } @Override protected void doBindSkin() { RenderEngine engine = FMLClientHandler.instance().getClient().p; int id = engine.getTextureForDownloadableImage(peer.skinUrl, peer.getTexture()); if (id < 0) return; engine.bindTexture(id); } @Override protected void doAnchorTo(BodyPart part, ModelRenderer modelPart) { modelPart.postRender(1/16f); ModelBox cuboid = (ModelBox)modelPart.cubeList.get(0); glScalef(1/16f, 1/16f, 1/16f); glTranslatef(cuboid.posX1, cuboid.posY2, cuboid.posZ1); } @Override protected Decider<BodyPart, ModelRenderer> decideModelPart(Decider<BodyPart, ModelRenderer> d) { ModelBiped model = Ears.getModelBipedMain(render); return d.map(BodyPart.HEAD, model.bipedHead) .map(BodyPart.LEFT_ARM, model.bipedLeftArm) .map(BodyPart.LEFT_LEG, model.bipedLeftLeg) .map(BodyPart.RIGHT_ARM, model.bipedRightArm) .map(BodyPart.RIGHT_LEG, model.bipedRightLeg) .map(BodyPart.TORSO, model.bipedBody); } @Override protected void beginQuad() { Tessellator.instance.startDrawing(GL_QUADS); } @Override protected void addVertex(float x, float y, int z, float r, float g, float b, float a, float u, float v, float nX, float nY, float nZ) { Tessellator.instance.setColorRGBA_F(r, g, b, a); Tessellator.instance.setNormal(nX, nY, nZ); Tessellator.instance.addVertexWithUV(x, y, z, u, v); } @Override public void setEmissive(boolean emissive) { super.setEmissive(emissive); OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); if (emissive) { GL11.glDisable(GL11.GL_TEXTURE_2D); } else { GL11.glEnable(GL11.GL_TEXTURE_2D); } OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); } @Override protected void drawQuad() { Tessellator.instance.draw(); } @Override protected String getSkinUrl() { return peer.skinUrl; } @Override protected int uploadImage(BufferedImage img) { return FMLClientHandler.instance().getClient().p.allocateAndSetupTexture(img); } @Override public float getTime() { return peer.ticksExisted+tickDelta; } @Override public boolean isFlying() { return peer.capabilities.isFlying; } @Override public boolean isGliding() { return false; } @Override public boolean isJacketEnabled() { return true; } @Override public boolean isWearingBoots() { ItemStack feet = peer.inventory.armorItemInSlot(0); return feet != null && feet.getItem() instanceof ItemArmor; } @Override public boolean isWearingChestplate() { ItemStack chest = peer.inventory.armorItemInSlot(2); return chest != null && chest.getItem() instanceof ItemArmor; } @Override public boolean isWearingElytra() { return false; } @Override public boolean needsSecondaryLayersDrawn() { return true; } @Override public float getHorizontalSpeed() { return EarsCommon.lerpDelta(peer.prevDistanceWalkedModified, peer.distanceWalkedModified, tickDelta); } @Override public float getLimbSwing() { return EarsCommon.lerpDelta(peer.field_705_Q, peer.field_704_R, tickDelta); } @Override public float getStride() { return EarsCommon.lerpDelta(peer.prevCameraYaw, peer.cameraYaw, tickDelta); } @Override public float getBodyYaw() { return EarsCommon.lerpDelta(peer.prevRenderYawOffset, peer.renderYawOffset, tickDelta); } @Override public double getCapeX() { return EarsCommon.lerpDelta(peer.field_20066_r, peer.field_20063_u, tickDelta); } @Override public double getCapeY() { return EarsCommon.lerpDelta(peer.field_20065_s, peer.field_20062_v, tickDelta); } @Override public double getCapeZ() { return EarsCommon.lerpDelta(peer.field_20064_t, peer.field_20061_w, tickDelta); } @Override public double getX() { return EarsCommon.lerpDelta(peer.prevPosX, peer.posX, tickDelta); } @Override public double getY() { return EarsCommon.lerpDelta(peer.prevPosY, peer.posY, tickDelta); } @Override public double getZ() { return EarsCommon.lerpDelta(peer.prevPosZ, peer.posZ, tickDelta); } }; }
0
0.766013
1
0.766013
game-dev
MEDIA
0.761905
game-dev,graphics-rendering
0.930804
1
0.930804
Layers-of-Railways/Railway
6,926
common/src/main/java/com/railwayteam/railways/mixin/client/MixinTrackInstance_BezierTrackInstance.java
/* * Steam 'n' Rails * Copyright (c) 2022-2024 The Railways Team * * 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, see <https://www.gnu.org/licenses/>. */ package com.railwayteam.railways.mixin.client; import com.jozufozu.flywheel.core.Materials; import com.jozufozu.flywheel.core.materials.model.ModelData; import com.jozufozu.flywheel.util.transform.TransformStack; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.vertex.PoseStack; import com.railwayteam.railways.mixin_interfaces.IMonorailBezier; import com.railwayteam.railways.mixin_interfaces.IMonorailBezier.MonorailAngles; import com.railwayteam.railways.registry.CRTrackMaterials; import com.simibubi.create.content.trains.track.BezierConnection; import com.simibubi.create.content.trains.track.TrackInstance; import com.simibubi.create.foundation.utility.Iterate; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static com.railwayteam.railways.registry.CRBlockPartials.MONORAIL_SEGMENT_BOTTOM; import static com.railwayteam.railways.registry.CRBlockPartials.MONORAIL_SEGMENT_MIDDLE; import static com.railwayteam.railways.registry.CRBlockPartials.MONORAIL_SEGMENT_TOP; @Environment(EnvType.CLIENT) @Mixin(targets = "com.simibubi.create.content.trains.track.TrackInstance$BezierTrackInstance", remap = false) public abstract class MixinTrackInstance_BezierTrackInstance { @Final @Shadow(remap = false) TrackInstance this$0; @Mutable @Shadow(remap = false) @Final private ModelData[] ties; @Shadow(remap = false) @Final @Mutable private ModelData[] right; @Shadow(remap = false) @Final @Mutable private ModelData[] left; @Shadow(remap = false) @Final @Mutable private BlockPos[] tiesLightPos; @Shadow(remap = false) @Final @Mutable private BlockPos[] leftLightPos; @Shadow(remap = false) @Final @Mutable private BlockPos[] rightLightPos; @Shadow(remap = false) abstract void updateLight(); @WrapOperation(method = "<init>", at = @At(value = "INVOKE", target = "Lcom/simibubi/create/content/trains/track/BezierConnection;getSegmentCount()I")) private int railways$messWithCtor(BezierConnection instance, Operation<Integer> original) { return instance.getMaterial().trackType == CRTrackMaterials.CRTrackType.MONORAIL ? 0 : original.call(instance); } @WrapOperation(method = "<init>", at = @At(value = "INVOKE", target = "Lcom/simibubi/create/content/trains/track/BezierConnection;getBakedSegments()[Lcom/simibubi/create/content/trains/track/BezierConnection$SegmentAngles;")) private BezierConnection.SegmentAngles[] railways$messWithCtor2(BezierConnection instance, Operation<BezierConnection.SegmentAngles[]> original) { return instance.getMaterial().trackType == CRTrackMaterials.CRTrackType.MONORAIL ? new BezierConnection.SegmentAngles[0] : original.call(instance); } @Inject(method = "<init>", at = @At("RETURN")) private void addActualMonorail(TrackInstance trackInstance, BezierConnection bc, CallbackInfo ci) { //Use right for top section //Use ties for center section //use left for bottom section if (bc.getMaterial().trackType == CRTrackMaterials.CRTrackType.MONORAIL) { BlockPos tePosition = bc.tePositions.getFirst(); PoseStack pose = new PoseStack(); TransformStack.cast(pose) .translate(this$0.getInstancePosition()) .nudge((int) bc.tePositions.getFirst() .asLong()); BlockState air = Blocks.AIR.defaultBlockState(); MonorailAngles[] monorails = ((IMonorailBezier) bc).getBakedMonorails(); var mat = ((AccessorInstance) this$0).getMaterialManager().cutout(RenderType.cutoutMipped()) .material(Materials.TRANSFORMED); right = new ModelData[monorails.length-1]; ties = new ModelData[monorails.length-1]; left = new ModelData[monorails.length-1]; tiesLightPos = new BlockPos[monorails.length-1]; leftLightPos = new BlockPos[monorails.length-1]; rightLightPos = new BlockPos[monorails.length-1]; ModelData[] top = right; ModelData[] middle = ties; ModelData[] bottom = left; BlockPos[] topLight = rightLightPos; BlockPos[] middleLight = tiesLightPos; BlockPos[] bottomLight = leftLightPos; mat.getModel(MONORAIL_SEGMENT_TOP).createInstances(top); mat.getModel(MONORAIL_SEGMENT_MIDDLE).createInstances(middle); mat.getModel(MONORAIL_SEGMENT_BOTTOM).createInstances(bottom); for (int i = 1; i < monorails.length; i++) { MonorailAngles segment = monorails[i]; int modelIndex = i - 1; PoseStack.Pose beamTransform = segment.beam; middle[modelIndex].setTransform(pose) .mulPose(beamTransform.pose()) .mulNormal(beamTransform.normal()); middleLight[modelIndex] = segment.lightPosition.offset(tePosition); for (boolean isTop : Iterate.trueAndFalse) { PoseStack.Pose beamCapTransform = segment.beamCaps.get(isTop); (isTop ? top : bottom)[modelIndex].setTransform(pose) .mulPose(beamCapTransform.pose()) .mulNormal(beamCapTransform.normal()); (isTop ? topLight : bottomLight)[modelIndex] = segment.lightPosition.offset(tePosition); } } updateLight(); } } }
0
0.875456
1
0.875456
game-dev
MEDIA
0.854406
game-dev
0.90804
1
0.90804
CraftTweaker/CraftTweaker-Documentation
11,171
docs_exported/1.19.3/crafttweaker/docs/vanilla/api/loot/LootContextBuilder.md
# LootContextBuilder Creates a new [LootContext](/vanilla/api/loot/LootContext) using a builder style pattern. ## Importing the class It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import at the very top of the file. ```zenscript import crafttweaker.api.loot.LootContextBuilder; ``` ## Static Methods :::group{name=copy} Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript LootContextBuilder.copy(context as LootContext) as LootContextBuilder ``` | Parameter | Type | |-----------|----------------------------------------------| | context | [LootContext](/vanilla/api/loot/LootContext) | ::: :::group{name=create} Creates a new builder with the given level. Returns: A new builder. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript LootContextBuilder.create(level as ServerLevel) as LootContextBuilder ``` | Parameter | Type | Description | |-----------|-----------------------------------------------|---------------------------------------| | level | [ServerLevel](/vanilla/api/world/ServerLevel) | The level the loot will be rolled in. | ::: ## Methods :::group{name=build} Creates a new [LootContext](/vanilla/api/loot/LootContext) with the given [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet). The given [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) is used to determine what values are required for the context to be used. Returns: a new [LootContext](/vanilla/api/loot/LootContext) Return Type: [LootContext](/vanilla/api/loot/LootContext) ```zenscript // LootContextBuilder.build(contextParamSet as LootContextParamSet) as LootContext new LootContextBuilder(level).build(LootContextParamSets.gift()); ``` | Parameter | Type | Description | |-----------------|--------------------------------------------------------------------|--------------------------------------------------------------------------------| | contextParamSet | [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) | The [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) to use. | ::: :::group{name=create} ::deprecated[Use [this](.)#build(LootContext.Builder, LootContextParamSet) instead to work around a bug in the ZenCode compiler.] Creates a new [LootContext](/vanilla/api/loot/LootContext) with the given [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet). The given [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) is used to determine what values are required for the context to be used. Returns: a new [LootContext](/vanilla/api/loot/LootContext) Return Type: [LootContext](/vanilla/api/loot/LootContext) ```zenscript // LootContextBuilder.create(contextParamSet as LootContextParamSet) as LootContext new LootContextBuilder(level).create(LootContextParamSets.gift()); ``` | Parameter | Type | Description | |-----------------|--------------------------------------------------------------------|--------------------------------------------------------------------------------| | contextParamSet | [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) | The [LootContextParamSet](/vanilla/api/loot/param/LootContextParamSet) to use. | ::: :::group{name=getLevel} Gets the level that this builder uses. Returns: The level that this builder uses. Return Type: [ServerLevel](/vanilla/api/world/ServerLevel) ```zenscript // LootContextBuilder.getLevel() as ServerLevel new LootContextBuilder(level).getLevel(); ``` ::: :::group{name=getOptionalParameter} Gets the provided value of the optional parameter. Returns: The value if found, null otherwise. Return Type: @org.openzen.zencode.java.ZenCodeType.Nullable T ```zenscript LootContextBuilder.getOptionalParameter<T : Object>(contextParam as LootContextParam<T>) as @org.openzen.zencode.java.ZenCodeType.Nullable T ``` | Parameter | Type | Description | |--------------|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------| | contextParam | [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; | The [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; to get the value of. | | T | Object | The type that the [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; uses | ::: :::group{name=getParameter} Gets the provided value of the parameter. Returns: The found value. Return Type: T ```zenscript LootContextBuilder.getParameter<T : Object>(contextParam as LootContextParam<T>) as T ``` | Parameter | Type | Description | |--------------|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------| | contextParam | [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; | The [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; to get the value of. | | T | Object | The type that the [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; uses | ::: :::group{name=withLuck} Provides the given luck value to the context. Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript // LootContextBuilder.withLuck(luck as float) as LootContextBuilder new LootContextBuilder(level).withLuck(0.5); ``` | Parameter | Type | Description | |-----------|-------|------------------------| | luck | float | The luck value to use. | ::: :::group{name=withOptionalParameter} Provides an optional parameter to this builder. Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript LootContextBuilder.withOptionalParameter<T : Object>(contextParam as LootContextParam<T>, actor as @org.openzen.zencode.java.ZenCodeType.Nullable T) as LootContextBuilder ``` | Parameter | Type | Description | |--------------|-----------------------------------------------------------------------|----------------------------------------| | contextParam | [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; | The param to add. | | actor | @org.openzen.zencode.java.ZenCodeType.Nullable T | The optional actor used by the param. | | T | Object | The type of actor that the param uses. | ::: :::group{name=withOptionalRandomSeed} Supplies a seed to be passed into a new [Random](/vanilla/api/util/math/Random). Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript // LootContextBuilder.withOptionalRandomSeed(seed as long) as LootContextBuilder new LootContextBuilder(level).withOptionalRandomSeed(0); ``` | Parameter | Type | Description | |-----------|------|------------------| | seed | long | The seed to use. | ::: :::group{name=withOptionalRandomSeed} Supplies either a seed to be passed into a new [Random](/vanilla/api/util/math/Random) or if the seed is `0` use the given [Random](/vanilla/api/util/math/Random) Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript // LootContextBuilder.withOptionalRandomSeed(seed as long, random as RandomSource) as LootContextBuilder new LootContextBuilder(level).withOptionalRandomSeed(1, level.random); ``` | Parameter | Type | Description | |-----------|-----------------------------------------------------|-------------------------------| | seed | long | The seed to use. | | random | [RandomSource](/vanilla/api/util/math/RandomSource) | The random source to provide. | ::: :::group{name=withParameter} Provides a parameter to this builder. Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript LootContextBuilder.withParameter<T : Object>(contextParam as LootContextParam<T>, actor as T) as LootContextBuilder ``` | Parameter | Type | Description | |--------------|-----------------------------------------------------------------------|----------------------------------------| | contextParam | [LootContextParam](/vanilla/api/loot/param/LootContextParam)&lt;T&gt; | The param to add. | | actor | T | The actor used by the param. | | T | Object | The type of actor that the param uses. | ::: :::group{name=withRandom} Supplies a [Random](/vanilla/api/util/math/Random) source to the built context. Returns: This builder for chaining purposes. Return Type: [LootContextBuilder](/vanilla/api/loot/LootContextBuilder) ```zenscript // LootContextBuilder.withRandom(random as RandomSource) as LootContextBuilder new LootContextBuilder(level).withRandom(level.random); ``` | Parameter | Type | Description | |-----------|-----------------------------------------------------|-------------------------------| | random | [RandomSource](/vanilla/api/util/math/RandomSource) | The random source to provide. | ::: ## Properties | Name | Type | Has Getter | Has Setter | Description | |-------|-----------------------------------------------|------------|------------|----------------------------------------| | level | [ServerLevel](/vanilla/api/world/ServerLevel) | true | false | Gets the level that this builder uses. |
0
0.922618
1
0.922618
game-dev
MEDIA
0.920062
game-dev
0.647936
1
0.647936
dudu502/littlebee_libs
2,283
Engine/Client/Ecsr/Components/MoveToPosition.cs
using Engine.Common.Protocol; using TrueSync; namespace Engine.Client.Ecsr.Components { public class MoveToPosition : AbstractComponent { byte __tag__; public FP Speed; public TSVector2 ToPosition { private set; get; } public MoveToPosition SetSpeed(FP speed) { Speed = speed;__tag__ |= 1;return this; } public bool HasSpeed() => (__tag__ & 1) == 1; public MoveToPosition SetToPosition(TSVector2 toPos) { ToPosition = toPos;__tag__ |= 2;return this; } public bool HasToPosition() => (__tag__ & 2) == 2; public override AbstractComponent Clone() { MoveToPosition position = new MoveToPosition(); position.__tag__ = __tag__; position.Speed = Speed; position.ToPosition = ToPosition; return position; } public override void CopyFrom(AbstractComponent component) { __tag__ = ((MoveToPosition)component).__tag__; Speed = ((MoveToPosition)component).Speed; ToPosition = ((MoveToPosition)component).ToPosition; } public override AbstractComponent Deserialize(byte[] bytes) { using(ByteBuffer buffer = new ByteBuffer(bytes)) { FP speed, tx, ty; __tag__ = buffer.ReadByte(); if(HasSpeed()) { speed._serializedValue = buffer.ReadInt64(); Speed = speed; } if (HasToPosition()) { tx._serializedValue = buffer.ReadInt64(); ty._serializedValue = buffer.ReadInt64(); ToPosition = new TSVector2(tx,ty); } return this; } } public override byte[] Serialize() { using (ByteBuffer buffer = new ByteBuffer()) { buffer.WriteByte(__tag__); if (HasSpeed()) buffer.WriteInt64(Speed._serializedValue); if (HasToPosition()) buffer.WriteInt64(ToPosition.x._serializedValue).WriteInt64(ToPosition.y._serializedValue); return buffer.GetRawBytes(); } } } }
0
0.9144
1
0.9144
game-dev
MEDIA
0.665026
game-dev,networking
0.979421
1
0.979421
ServUO/ServUO
21,755
Scripts/Services/Expansions/High Seas/Items/Fish/FishPies.cs
using Server; using System; using Server.Mobiles; using Server.Engines.Craft; using System.Collections.Generic; namespace Server.Items { public enum FishPieEffect { None, MedBoost, FocusBoost, ColdSoak, EnergySoak, FireSoak, PoisonSoak, PhysicalSoak, WeaponDam, HitChance, DefChance, SpellDamage, ManaRegen, HitsRegen, StamRegen, SoulCharge, CastFocus, } public class BaseFishPie : Item, IQuality { private ItemQuality _Quality; [CommandProperty(AccessLevel.GameMaster)] public ItemQuality Quality { get { return _Quality; } set { _Quality = value; InvalidateProperties(); } } public bool PlayerConstructed { get { return true; } } public virtual TimeSpan Duration { get { return TimeSpan.FromMinutes(5); } } public virtual int BuffName { get { return 0; } } public virtual int BuffAmount { get { return 0; } } public virtual FishPieEffect Effect { get { return FishPieEffect.None; } } public static Dictionary<Mobile, List<FishPieEffect>> m_EffectsList = new Dictionary<Mobile, List<FishPieEffect>>(); public BaseFishPie() : base(4161) { Stackable = true; } public virtual int OnCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, ITool tool, CraftItem craftItem, int resHue) { Quality = (ItemQuality)quality; return quality; } public static bool IsUnderEffects(Mobile from, FishPieEffect type) { if (!m_EffectsList.ContainsKey(from) || m_EffectsList[from] == null) return false; return m_EffectsList[from].Contains(type); } public static bool TryAddBuff(Mobile from, FishPieEffect type) { if (IsUnderEffects(from, type)) return false; if (!m_EffectsList.ContainsKey(from)) m_EffectsList.Add(from, new List<FishPieEffect>()); m_EffectsList[from].Add(type); return true; } public static void RemoveBuff(Mobile from, FishPieEffect type) { if(!m_EffectsList.ContainsKey(from)) return; if (m_EffectsList[from] != null && m_EffectsList[from].Contains(type)) m_EffectsList[from].Remove(type); if (m_EffectsList[from] == null || m_EffectsList[from].Count == 0) m_EffectsList.Remove(from); BuffInfo.RemoveBuff(from, BuffIcon.FishPie); from.Delta(MobileDelta.WeaponDamage); } public static void ScaleDamage(Mobile from, Mobile to, ref int totalDamage, int phys, int fire, int cold, int pois, int nrgy, int direct) { if (Core.EJ && from is PlayerMobile && to is PlayerMobile) { return; } if (IsUnderEffects(to, FishPieEffect.PhysicalSoak) && phys > 0) totalDamage -= (int)Math.Min(5.0, totalDamage * ((double)phys / 100.0)); if (IsUnderEffects(to, FishPieEffect.FireSoak) && fire > 0) totalDamage -= (int)Math.Min(5.0, totalDamage * ((double)fire / 100.0)); if (IsUnderEffects(to, FishPieEffect.ColdSoak) && cold > 0) totalDamage -= (int)Math.Min(5.0, totalDamage * ((double)cold / 100.0)); if (IsUnderEffects(to, FishPieEffect.PoisonSoak) && pois > 0) totalDamage -= (int)Math.Min(5.0, totalDamage * ((double)pois / 100.0)); if (IsUnderEffects(to, FishPieEffect.EnergySoak) && nrgy > 0) totalDamage -= (int)Math.Min(5.0, totalDamage * ((double)nrgy / 100.0)); } public virtual bool Apply(Mobile from) { if (TryAddBuff(from, Effect)) { switch (Effect) { default: case FishPieEffect.None: break; case FishPieEffect.MedBoost: TimedSkillMod mod1 = new TimedSkillMod(SkillName.Meditation, true, 10.0, Duration); mod1.ObeyCap = true; from.AddSkillMod(mod1); break; case FishPieEffect.FocusBoost: TimedSkillMod mod2 = new TimedSkillMod(SkillName.Focus, true, 10.0, Duration); mod2.ObeyCap = true; from.AddSkillMod(mod2); break; case FishPieEffect.ColdSoak: break; case FishPieEffect.EnergySoak: break; case FishPieEffect.PoisonSoak: break; case FishPieEffect.FireSoak: break; case FishPieEffect.PhysicalSoak: break; case FishPieEffect.WeaponDam: break; case FishPieEffect.HitChance: break; case FishPieEffect.DefChance: break; case FishPieEffect.SpellDamage: break; case FishPieEffect.ManaRegen: break; case FishPieEffect.StamRegen: break; case FishPieEffect.HitsRegen: break; case FishPieEffect.SoulCharge: break; case FishPieEffect.CastFocus: break; } if (Effect != FishPieEffect.None) { new InternalTimer(Duration, from, Effect); BuffInfo.AddBuff(from, new BuffInfo(BuffIcon.FishPie, 1116340, LabelNumber)); } return true; } else from.SendLocalizedMessage(502173); // You are already under a similar effect. return false; } private class InternalTimer : Timer { private Mobile m_From; private FishPieEffect m_EffectType; public InternalTimer(TimeSpan duration, Mobile from, FishPieEffect type) : base(duration) { m_From = from; m_EffectType = type; Start(); } protected override void OnTick() { BaseFishPie.RemoveBuff(m_From, m_EffectType); } } public override void AddCraftedProperties(ObjectPropertyList list) { if (_Quality == ItemQuality.Exceptional) { list.Add(1060636); // Exceptional } } public override void GetProperties(ObjectPropertyList list) { base.GetProperties(list); list.Add(BuffName, BuffAmount.ToString()); } public override void OnDoubleClick(Mobile from) { if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it. } else if (Apply(from)) { from.FixedEffect(0x375A, 10, 15); from.PlaySound(0x1E7); from.SendLocalizedMessage(1116285, String.Format("#{0}", LabelNumber)); //You eat the ~1_val~. Mmm, tasty! Delete(); } } public BaseFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); // version writer.Write((int)_Quality); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if (version > 0) _Quality = (ItemQuality)reader.ReadInt(); } } public class AutumnDragonfishPie : BaseFishPie { public override int LabelNumber { get { return 1116224; } } public override int BuffName { get { return 1116280; } } public override int BuffAmount { get { return 10; } } public override FishPieEffect Effect { get { return FishPieEffect.MedBoost; } } [Constructable] public AutumnDragonfishPie() { Hue = FishInfo.GetFishHue(typeof(AutumnDragonfish)); } public AutumnDragonfishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class BullFishPie : BaseFishPie { public override int LabelNumber { get { return 1116220; } } public override int BuffName { get { return 1116276; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.WeaponDam; } } [Constructable] public BullFishPie() { Hue = FishInfo.GetFishHue(typeof(BullFish)); } public BullFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class CrystalFishPie : BaseFishPie { public override int LabelNumber { get { return 1116219; } } public override int BuffName { get { return 1116275; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.EnergySoak; } } [Constructable] public CrystalFishPie() { Hue = FishInfo.GetFishHue(typeof(CrystalFish)); } public CrystalFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class FairySalmonPie : BaseFishPie { public override int LabelNumber { get { return 1116222; } } public override int BuffName { get { return 1116278; } } public override int BuffAmount { get { return 2; } } public override FishPieEffect Effect { get { return FishPieEffect.CastFocus; } } [Constructable] public FairySalmonPie() { Hue = FishInfo.GetFishHue(typeof(FairySalmon)); } public FairySalmonPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class FireFishPie : BaseFishPie { public override int LabelNumber { get { return 1116217; } } public override int BuffName { get { return 1116271; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.FireSoak; } } [Constructable] public FireFishPie() { Hue = FishInfo.GetFishHue(typeof(FireFish)); } public FireFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class GiantKoiPie : BaseFishPie { public override int LabelNumber { get { return 1116216; } } public override int BuffName { get { return 1116270; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.DefChance; } } [Constructable] public GiantKoiPie() { Hue = FishInfo.GetFishHue(typeof(GiantKoi)); } public GiantKoiPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class GreatBarracudaPie : BaseFishPie { public override int LabelNumber { get { return 1116214; } } public override int BuffName { get { return 1116269; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.HitChance; } } [Constructable] public GreatBarracudaPie() { Hue = 1287;// FishInfo.GetFishHue(typeof(GreatBarracuda)); } public GreatBarracudaPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class HolyMackerelPie : BaseFishPie { public override int LabelNumber { get { return 1116225; } } public override int BuffName { get { return 1116283; } } public override int BuffAmount { get { return 3; } } public override FishPieEffect Effect { get { return FishPieEffect.ManaRegen; } } [Constructable] public HolyMackerelPie() { Hue = FishInfo.GetFishHue(typeof(HolyMackerel)); } public HolyMackerelPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class LavaFishPie : BaseFishPie { public override int LabelNumber { get { return 1116223; } } public override int BuffName { get { return 1116279; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.SoulCharge; } } [Constructable] public LavaFishPie() { Hue = FishInfo.GetFishHue(typeof(LavaFish)); } public LavaFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class ReaperFishPie : BaseFishPie { public override int LabelNumber { get { return 1116218; } } public override int BuffName { get { return 1116274; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.PoisonSoak; } } [Constructable] public ReaperFishPie() { Hue = 1152;// FishInfo.GetFishHue(typeof(ReaperFish)); } public ReaperFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class SummerDragonfishPie : BaseFishPie { public override int LabelNumber { get { return 1116221; } } public override int BuffName { get { return 1116277; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.SpellDamage; } } [Constructable] public SummerDragonfishPie() { Hue = FishInfo.GetFishHue(typeof(SummerDragonfish)); } public SummerDragonfishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class UnicornFishPie : BaseFishPie { public override int LabelNumber { get { return 1116226; } } public override int BuffName { get { return 1116284; } } public override int BuffAmount { get { return 3; } } public override FishPieEffect Effect { get { return FishPieEffect.StamRegen; } } [Constructable] public UnicornFishPie() { Hue = FishInfo.GetFishHue(typeof(UnicornFish)); } public UnicornFishPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class YellowtailBarracudaPie : BaseFishPie { public override int LabelNumber { get { return 1116215; } } public override int BuffName { get { return 1116282; } } public override int BuffAmount { get { return 3; } } public override FishPieEffect Effect { get { return FishPieEffect.HitsRegen; } } [Constructable] public YellowtailBarracudaPie() { Hue = FishInfo.GetFishHue(typeof(YellowtailBarracuda)); } public YellowtailBarracudaPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class StoneCrabPie : BaseFishPie { public override int LabelNumber { get { return 1116227; } } public override int BuffName { get { return 1116272; } } public override int BuffAmount { get { return 3; } } public override FishPieEffect Effect { get { return FishPieEffect.PhysicalSoak; } } [Constructable] public StoneCrabPie() { Hue = FishInfo.GetFishHue(typeof(StoneCrab)); } public StoneCrabPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class SpiderCrabPie : BaseFishPie { public override int LabelNumber { get { return 1116229; } } public override int BuffName { get { return 1116281; } } public override int BuffAmount { get { return 10; } } public override FishPieEffect Effect { get { return FishPieEffect.FocusBoost; } } [Constructable] public SpiderCrabPie() { Hue = FishInfo.GetFishHue(typeof(SpiderCrab)); } public SpiderCrabPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class BlueLobsterPie : BaseFishPie { public override int LabelNumber { get { return 1116228; } } public override int BuffName { get { return 1116273; } } public override int BuffAmount { get { return 5; } } public override FishPieEffect Effect { get { return FishPieEffect.ColdSoak; } } [Constructable] public BlueLobsterPie() { Hue = FishInfo.GetFishHue(typeof(BlueLobster)); } public BlueLobsterPie(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
0
0.764978
1
0.764978
game-dev
MEDIA
0.970874
game-dev
0.993031
1
0.993031
McKay42/McEngine
4,000
McEngine/src/GUI/CBaseUIContainerHorizontalBox.cpp
/* * CBaseUIContainerHorizontalBox.cpp * * Created on: Jun 1, 2017 * Author: Psy */ #include "CBaseUIContainerHorizontalBox.h" #include "Engine.h" CBaseUIContainerHorizontalBox::CBaseUIContainerHorizontalBox(float posX, float posY, float sizeX, float sizeY, UString name) : CBaseUIContainerBase(name) { m_vPos.x = posX; m_vPos.y = posY; m_vmPos = m_vPos; m_vSize.x = sizeX; m_vSize.y = sizeY; m_vmSize = m_vSize; m_bWidthOverride = false; m_bScaleByHeightOnly = false; m_padding = 0; } CBaseUIContainerHorizontalBox::~CBaseUIContainerHorizontalBox() { } void CBaseUIContainerHorizontalBox::drawDebug(Graphics *g, Color color) { if (!m_bVisible) return; g->setColor(color); g->drawRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y); } void CBaseUIContainerHorizontalBox::updateLayout() { if (m_parent != nullptr) m_parent->updateLayout(); float widthStorage = 0; if (!m_bWidthOverride) widthStorage = (m_vSize.x - 2 * m_vMargin.x - (m_vElements.size() - 1) * m_padding) / m_vElements.size(); float posStorage = m_vPos.x; for (size_t i=0; i<m_vElements.size(); i++) { if (!m_bWidthOverride && !m_bScaleByHeightOnly) { m_vElements[i]->setSizeAbsolute(widthStorage, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(m_vPos.x + m_vMargin.x + (m_padding + widthStorage) * i, m_vPos.y + m_vMargin.y); } else { if (!m_bScaleByHeightOnly) m_vElements[i]->setSizeAbsolute(m_vSize.x * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); else m_vElements[i]->setSizeAbsolute(m_vSize.y / 9 * 16 * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(posStorage + (posStorage == m_vPos.x ? m_padding : m_vMargin.x), m_vPos.y + m_vMargin.y); posStorage = m_vElements[i]->getPos().x + m_vElements[i]->getSize().x; } } } void CBaseUIContainerHorizontalBox::updateElement(CBaseUIElement *element) { updateLayout(); } void CBaseUIContainerHorizontalBox::onMoved() { float widthStorage = 0; if (!m_bWidthOverride) widthStorage = (m_vSize.x - 2 * m_vMargin.x - (m_vElements.size() - 1) * m_padding) / m_vElements.size(); float posStorage = m_vPos.x; for (size_t i=0; i<m_vElements.size(); i++) { if (!m_bWidthOverride && !m_bScaleByHeightOnly) { m_vElements[i]->setSizeAbsolute(widthStorage, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(m_vPos.x + m_vMargin.x + (m_padding + widthStorage) * i, m_vPos.y + m_vMargin.y); } else { if (!m_bScaleByHeightOnly) m_vElements[i]->setSizeAbsolute(m_vSize.x * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); else m_vElements[i]->setSizeAbsolute(m_vSize.y / 9 * 16 * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(posStorage + (posStorage == m_vPos.x ? m_padding : m_vMargin.x), m_vPos.y + m_vMargin.y); posStorage = m_vElements[i]->getPos().x + m_vElements[i]->getSize().x; } } } void CBaseUIContainerHorizontalBox::onResized() { float widthStorage = 0; if (!m_bWidthOverride) widthStorage = (m_vSize.x - 2 * m_vMargin.x - (m_vElements.size() - 1) * m_padding) / m_vElements.size(); float posStorage = m_vPos.x; for (size_t i=0; i<m_vElements.size(); i++) { if (!m_bWidthOverride && !m_bScaleByHeightOnly) { m_vElements[i]->setSizeAbsolute(widthStorage, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(m_vPos.x + m_vMargin.x + (m_padding + widthStorage) * i, m_vPos.y + m_vMargin.y); } else { if (!m_bScaleByHeightOnly) m_vElements[i]->setSizeAbsolute(m_vSize.x * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); else m_vElements[i]->setSizeAbsolute(m_vSize.y / 9 * 16 * m_vElements[i]->getRelSize().x, m_vSize.y - 2 * m_vMargin.y); m_vElements[i]->setPosAbsolute(posStorage + (posStorage == m_vPos.x ? m_padding : m_vMargin.x), m_vPos.y + m_vMargin.y); posStorage = m_vElements[i]->getPos().x + m_vElements[i]->getSize().x; } } }
0
0.850652
1
0.850652
game-dev
MEDIA
0.858033
game-dev
0.96304
1
0.96304
Pawn-Appetit/pawn-appetit
9,034
src-tauri/src/chess/process.rs
//! UCI engine process abstraction and communication utilities. //! //! This module provides the `EngineProcess` struct for managing a UCI chess engine process, //! sending commands, updating options, and parsing engine output for best-move analysis. use std::path::PathBuf; use std::time::Instant; use tokio::io::AsyncWriteExt; use vampirc_uci::{uci::ScoreValue, UciInfoAttribute}; use crate::error::Error; use super::types::{BestMoves, EngineLog, EngineOptions, GoMode}; use super::uci::UciCommunicator; use shakmaty::{fen::Fen, san::SanPlus, uci::UciMove, CastlingMode, Chess, Color, Position}; #[cfg(target_os = "windows")] pub const CREATE_NO_WINDOW: u32 = 0x08000000; /// Represents a running UCI engine process and its state. pub struct EngineProcess { pub stdin: tokio::process::ChildStdin, pub last_depth: u32, pub best_moves: Vec<BestMoves>, pub last_best_moves: Vec<BestMoves>, pub last_progress: f32, pub options: EngineOptions, pub go_mode: GoMode, pub running: bool, pub real_multipv: u16, pub logs: Vec<EngineLog>, pub start: Instant, } impl EngineProcess { /// Spawn a new UCI engine process and initialize it. /// /// Returns the process and a line reader for its stdout. pub async fn new(path: PathBuf) -> Result<(Self, tokio::io::Lines<tokio::io::BufReader<tokio::process::ChildStdout>>), Error> { let mut comm = UciCommunicator::spawn(path).await?; let mut logs = Vec::new(); comm.write_line("uci\n").await?; logs.push(EngineLog::Gui("uci\n".to_string())); while let Some(line) = comm.stdout_lines.next_line().await? { logs.push(EngineLog::Engine(line.clone())); if line == "uciok" { comm.write_line("isready\n").await?; logs.push(EngineLog::Gui("isready\n".to_string())); while let Some(line_is_ready) = comm.stdout_lines.next_line().await? { logs.push(EngineLog::Engine(line_is_ready.clone())); if line_is_ready == "readyok" { break; } } break; } } Ok(( Self { stdin: comm.stdin, last_depth: 0, best_moves: Vec::new(), last_best_moves: Vec::new(), last_progress: 0.0, logs, options: EngineOptions::default(), real_multipv: 0, go_mode: GoMode::Infinite, running: false, start: Instant::now(), }, comm.stdout_lines, )) } /// Set a single UCI option for the engine. pub async fn set_option<T>(&mut self, name: &str, value: T) -> Result<(), Error> where T: std::fmt::Display, { let msg = format!("setoption name {} value {}\n", name, value); self.stdin.write_all(msg.as_bytes()).await?; self.logs.push(EngineLog::Gui(msg)); Ok(()) } /// Set all engine options, including FEN, moves, and extra UCI options. /// Updates multipv and resets best-move tracking. pub async fn set_options(&mut self, options: EngineOptions) -> Result<(), Error> { let fen: Fen = options.fen.parse()?; let mut pos: Chess = match fen.into_position(CastlingMode::Chess960) { Ok(p) => p, Err(e) => e.ignore_too_much_material()?, }; for m in &options.moves { let uci = UciMove::from_ascii(m.as_bytes())?; let mv = uci.to_move(&pos)?; pos.play_unchecked(&mv); } let multipv = options .extra_options .iter() .find(|x| x.name == "MultiPV") .map(|x| x.value.parse().unwrap_or(1)) .unwrap_or(1); self.real_multipv = multipv.min(pos.legal_moves().len() as u16); for option in &options.extra_options { if !self.options.extra_options.contains(option) { self.set_option(&option.name, &option.value).await?; } } if options.fen != self.options.fen || options.moves != self.options.moves { self.set_position(&options.fen, &options.moves).await?; } self.last_depth = 0; self.options = options.clone(); self.best_moves.clear(); self.last_best_moves.clear(); Ok(()) } /// Set the engine's position using FEN and move list. pub async fn set_position(&mut self, fen: &str, moves: &Vec<String>) -> Result<(), Error> { let msg = if moves.is_empty() { format!("position fen {}\n", fen) } else { format!("position fen {} moves {}\n", fen, moves.join(" ")) }; self.stdin.write_all(msg.as_bytes()).await?; self.options.fen = fen.to_string(); self.options.moves = moves.clone(); self.logs.push(EngineLog::Gui(msg)); Ok(()) } /// Start engine search with the given mode (depth, time, etc). pub async fn go(&mut self, mode: &GoMode) -> Result<(), Error> { self.go_mode = mode.clone(); let msg = match mode { GoMode::Depth(depth) => format!("go depth {}\n", depth), GoMode::Time(time) => format!("go movetime {}\n", time), GoMode::Nodes(nodes) => format!("go nodes {}\n", nodes), GoMode::PlayersTime(super::types::PlayersTime { white, black, winc, binc }) => { format!( "go wtime {} btime {} winc {} binc {} movetime 1000\n", white, black, winc, binc ) } GoMode::Infinite => "go infinite\n".to_string(), }; self.stdin.write_all(msg.as_bytes()).await?; self.logs.push(EngineLog::Gui(msg)); self.running = true; self.start = Instant::now(); Ok(()) } /// Stop the engine's current search. pub async fn stop(&mut self) -> Result<(), Error> { self.stdin.write_all(b"stop\n").await?; self.logs.push(EngineLog::Gui("stop\n".to_string())); self.running = false; Ok(()) } /// Kill the engine process. pub async fn kill(&mut self) -> Result<(), Error> { self.stdin.write_all(b"quit\n").await?; self.logs.push(EngineLog::Gui("quit\n".to_string())); self.running = false; Ok(()) } } /// Invert a UCI score (for black's perspective). fn invert_score(score: vampirc_uci::uci::Score) -> vampirc_uci::uci::Score { let new_value = match score.value { ScoreValue::Cp(x) => ScoreValue::Cp(-x), ScoreValue::Mate(x) => ScoreValue::Mate(-x), }; let new_wdl = score.wdl.map(|(w, d, l)| (l, d, w)); vampirc_uci::uci::Score { value: new_value, wdl: new_wdl, ..score } } /// Parse UCI info attributes into a `BestMoves` struct for the current position. /// /// # Arguments /// * `attrs` - UCI info attributes from the engine. /// * `fen` - FEN string for the position. /// * `moves` - List of moves leading to the position. /// /// # Returns /// `BestMoves` struct with parsed data. /// /// # Errors /// Returns `Error` if parsing fails or no moves are found. pub fn parse_uci_attrs( attrs: Vec<UciInfoAttribute>, fen: &Fen, moves: &Vec<String>, ) -> Result<BestMoves, Error> { let mut best_moves = BestMoves::default(); let mut pos: Chess = match fen.clone().into_position(CastlingMode::Chess960) { Ok(p) => p, Err(e) => e.ignore_too_much_material()?, }; for m in moves { let uci = UciMove::from_ascii(m.as_bytes())?; let mv = uci.to_move(&pos)?; pos.play_unchecked(&mv); } let turn = pos.turn(); for a in attrs { match a { UciInfoAttribute::Pv(m) => { for mv in m { let uci: UciMove = mv.to_string().parse()?; let m = uci.to_move(&pos)?; let san = SanPlus::from_move_and_play_unchecked(&mut pos, &m); best_moves.san_moves.push(san.to_string()); best_moves.uci_moves.push(uci.to_string()); } } UciInfoAttribute::Nps(nps) => { best_moves.nps = nps as u32; } UciInfoAttribute::Nodes(nodes) => { best_moves.nodes = nodes as u32; } UciInfoAttribute::Depth(depth) => { best_moves.depth = depth; } UciInfoAttribute::MultiPv(multipv) => { best_moves.multipv = multipv; } UciInfoAttribute::Score(score) => { best_moves.score = score; } _ => (), } } if best_moves.san_moves.is_empty() { return Err(Error::NoMovesFound); } if turn == Color::Black { best_moves.score = invert_score(best_moves.score); } Ok(best_moves) }
0
0.902505
1
0.902505
game-dev
MEDIA
0.245965
game-dev
0.915835
1
0.915835
Jameskmonger/creature-chess
2,478
modules/@creature-chess/gamemode/src/entities/player/state/playerInfo/reducer.ts
import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { MAX_HEALTH } from "@creature-chess/models/config"; import { PlayerStatus, PlayerBattle, } from "@creature-chess/models/game/playerList"; import { StreakType, PlayerStreak } from "@creature-chess/models/player"; export type PlayerMatchRewards = { damage: number; justDied: boolean; rewardMoney: { total: number; base: number; winBonus: number; streakBonus: number; interest: number; }; }; export interface PlayerInfoState { status: PlayerStatus; health: number; streak: PlayerStreak; battle: PlayerBattle | null; matchRewards: PlayerMatchRewards | null; opponentId: string | null; opponentIsClone: boolean; money: number; ready: boolean; level: number; xp: number; } const initialState: PlayerInfoState = { status: PlayerStatus.CONNECTED, health: MAX_HEALTH, streak: { type: StreakType.WIN, amount: 0, }, battle: null, matchRewards: null, opponentId: null, opponentIsClone: false, money: 0, ready: false, level: 0, xp: 0, }; const playerInfoSlice = createSlice({ name: "playerInfo", initialState, reducers: { playerMatchRewardsEvent: ( state, action: PayloadAction<PlayerMatchRewards | null> ) => { state.matchRewards = action.payload; }, updateStatusCommand: (state, action: PayloadAction<PlayerStatus>) => { state.status = action.payload; }, updateReadyCommand: (state, action: PayloadAction<boolean>) => { state.ready = action.payload; }, updateOpponentCommand: ( state, action: PayloadAction<{ id: string | null; isClone?: boolean; }> ) => { state.opponentId = action.payload.id; state.opponentIsClone = action.payload.isClone ?? false; }, updateBattleCommand: ( state, action: PayloadAction<PlayerBattle | null> ) => { state.battle = action.payload; }, updateHealthCommand: (state, action: PayloadAction<number>) => { state.health = action.payload; }, updateStreakCommand: (state, action: PayloadAction<PlayerStreak>) => { state.streak = action.payload; }, updateLevelCommand: ( state, action: PayloadAction<{ level: number; xp: number }> ) => { state.level = action.payload.level; state.xp = action.payload.xp; }, updateMoneyCommand: (state, action: PayloadAction<number>) => { state.money = action.payload; }, }, }); export const playerInfoReducer = playerInfoSlice.reducer; export const playerInfoCommands = playerInfoSlice.actions;
0
0.792086
1
0.792086
game-dev
MEDIA
0.643199
game-dev
0.956463
1
0.956463
p4lang/p4c
6,645
backends/tofino/bf-asm/synth2port.cpp
/** * Copyright (C) 2024 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. * * * SPDX-License-Identifier: Apache-2.0 */ #include "backends/tofino/bf-asm/stage.h" #include "backends/tofino/bf-asm/tables.h" #include "data_switchbox.h" #include "input_xbar.h" #include "lib/algorithm.h" #include "misc.h" void Synth2Port::common_init_setup(const VECTOR(pair_t) & data, bool, P4Table::type p4type) { setup_layout(layout, data); if (auto *fmt = get(data, "format")) { if (CHECKTYPEPM(*fmt, tMAP, fmt->map.size > 0, "non-empty map")) format.reset(new Format(this, fmt->map)); } } bool Synth2Port::common_setup(pair_t &kv, const VECTOR(pair_t) & data, P4Table::type p4type) { if (kv.key == "vpns") { if (kv.value == "null") { no_vpns = true; } else if (CHECKTYPE(kv.value, tVEC)) { setup_vpns(layout, &kv.value.vec, true); } } else if (kv.key == "maprams") { setup_maprams(kv.value); } else if (kv.key == "global_binding") { global_binding = get_bool(kv.value); } else if (kv.key == "per_flow_enable") { if (CHECKTYPE(kv.value, tSTR)) { per_flow_enable = 1; per_flow_enable_param = kv.value.s; } } else if (kv.key == "p4") { if (CHECKTYPE(kv.value, tMAP)) p4_table = P4Table::get(p4type, kv.value.map); } else if (kv.key == "context_json") { setup_context_json(kv.value); } else if (kv.key == "format" || kv.key == "row" || kv.key == "logical_row" || kv.key == "column" || kv.key == "bus") { /* already done in setup_layout */ } else if (kv.key == "logical_bus") { if (CHECKTYPE2(kv.value, tSTR, tVEC)) { if (kv.value.type == tSTR) { if (*kv.value.s != 'A' && *kv.value.s != 'O' && *kv.value.s != 'S') error(kv.value.lineno, "Invalid logical bus %s", kv.value.s); } else { for (auto &v : kv.value.vec) { if (CHECKTYPE(v, tSTR)) { if (*v.s != 'A' && *v.s != 'O' && *v.s != 'S') error(v.lineno, "Invalid logical bus %s", v.s); } } } } } else if (kv.key == "home_row") { home_lineno = kv.value.lineno; if (CHECKTYPE2(kv.value, tINT, tVEC)) { if (kv.value.type == tINT) { if (kv.value.i >= 0 || kv.value.i < LOGICAL_SRAM_ROWS) home_rows.insert(kv.value.i); else error(kv.value.lineno, "Invalid home row %" PRId64 "", kv.value.i); } else { for (auto &v : kv.value.vec) { if (CHECKTYPE(v, tINT)) { if (v.i >= 0 || v.i < LOGICAL_SRAM_ROWS) home_rows.insert(v.i); else error(v.lineno, "Invalid home row %" PRId64 "", v.i); } } } } } else { return false; } return true; } void Synth2Port::pass1() { LOG1("### Synth2Port table " << name() << " pass1 " << loc()); AttachedTable::pass1(); } void Synth2Port::alloc_vpns(Target::Tofino) { AttachedTable::alloc_vpns(); } void Synth2Port::pass2() { LOG1("### Synth2Port table " << name() << " pass2 " << loc()); } void Synth2Port::pass3() { LOG1("### Synth2Port table " << name() << " pass3 " << loc()); } json::map *Synth2Port::add_stage_tbl_cfg(json::map &tbl, const char *type, int size) const { json::map &stage_tbl = *AttachedTable::add_stage_tbl_cfg(tbl, type, size); std::string hr = how_referenced(); if (hr.empty()) hr = direct ? "direct" : "indirect"; tbl["how_referenced"] = hr; int entries = 1; if (format) { BUG_CHECK(format->log2size <= 7, "log2size %d > 7", format->log2size); if (format->groups() > 1) { BUG_CHECK(format->log2size == 7, "log2size %d != 7", format->log2size); entries = format->groups(); } else { entries = 128U >> format->log2size; } } add_pack_format(stage_tbl, 128, 1, entries); stage_tbl["memory_resource_allocation"] = gen_memory_resource_allocation_tbl_cfg("sram", layout, true); return &stage_tbl; } void Synth2Port::add_alu_indexes(json::map &stage_tbl, std::string alu_indexes) const { json::vector home_alu; for (auto row : home_rows) home_alu.push_back(row / 4U); stage_tbl[alu_indexes] = home_alu.clone(); } std::vector<int> Synth2Port::determine_spare_bank_memory_units(Target::Tofino) const { std::vector<int> spare_mem; int vpn_ctr = 0; int minvpn, spare_vpn; // Retrieve the Spare VPN layout_vpn_bounds(minvpn, spare_vpn, false); for (auto &row : layout) { auto vpn_itr = row.vpns.begin(); for (auto &ram : row.memunits) { BUG_CHECK(ram.stage == INT_MIN && ram.row == row.row, "bogus %s in row %d", ram.desc(), row.row); if (vpn_itr != row.vpns.end()) vpn_ctr = *vpn_itr++; if (spare_vpn == vpn_ctr) { spare_mem.push_back(json_memunit(ram)); if (table_type() == SELECTION || table_type() == COUNTER || table_type() == METER || table_type() == STATEFUL) continue; } } } return spare_mem; } int Synth2Port::get_home_row_for_row(int row) const { for (int home_row : home_rows) { // Tofino1 have an overflow bus in the middle of the SRAM array if (options.target == TOFINO) return home_row; else if (row / 8 == home_row / 8) return home_row; } BUG("Could not find home row for row %d", row); return -1; } template <class REGS> void Synth2Port::write_regs_vt(REGS &regs) { // FIXME move common Counter/Meter/StatefulTable::write_regs_vt stuff here } REGSETS_IN_CLASS(Tofino, TARGET_OVERLOAD, void Synth2Port::write_regs, (mau_regs & regs), { write_regs_vt(regs); })
0
0.955409
1
0.955409
game-dev
MEDIA
0.181829
game-dev
0.974493
1
0.974493
AnthonyTornetta/Cosmos
7,884
cosmos_server/src/shop/prices.rs
//! Temporary: generates default shop prices use std::fs; use bevy::{ app::App, ecs::system::Res, prelude::{Commands, Resource}, state::state::OnEnter, }; use cosmos_core::{ crafting::recipes::{RecipeItem, basic_fabricator::BasicFabricatorRecipes}, item::Item, registry::Registry, state::GameState, }; use cosmos_core::{registry::identifiable::Identifiable, shop::ShopEntry}; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize)] enum PrettyShopEntry { /// The shop is selling this Selling { /// The item's id item_id: String, /// The maximum amount the shop is selling max_quantity_selling: u32, /// The price per item price_per: u32, }, /// This shop is buying this Buying { /// The item's id item_id: String, /// The maximum amount of this item the shop is buying max_quantity_buying: Option<u32>, /// The price this shop is willing to pay per item price_per: u32, }, } fn compute_price(base: &[(u16, u32)], item: u16, fab_recipes: &BasicFabricatorRecipes) -> Option<u32> { if let Some((_, price)) = base.iter().find(|x| x.0 == item) { return Some(*price); } let recipe = fab_recipes.iter().find(|r| r.output.item == item)?; let result = recipe.inputs.iter().map(|i| match i.item { RecipeItem::Item(id) => compute_price(base, id, fab_recipes).map(|x| x * i.quantity as u32), }); if result.clone().any(|x| x.is_none()) { return None; } Some(result.flatten().sum()) } fn create_default_shop_entires(mut commands: Commands, items: Res<Registry<Item>>, fab_recipes: Res<BasicFabricatorRecipes>) { let price = |id: &str, price: u32| -> Option<(u16, u32)> { items.from_id(&format!("cosmos:{id}")).map(|x| (x.id(), price)) }; let base_prices = [ price("iron_bar", 10), price("copper_bar", 10), price("lead_bar", 100), price("uranium", 100), price("sulfur", 20), price("gravitron_crystal", 700), price("energite_crystal", 600), price("photonium_crystal", 200), price("grass", 4), price("dirt", 3), price("cherry_leaf", 50), price("cherry_log", 100), price("redwood_log", 30), price("redwood_leaf", 20), price("molten", 1), price("stone", 1), price("sand", 3), price("cactus", 20), ] .into_iter() .flatten() .collect::<Vec<_>>(); /* * COLORS.map(|c| PrettyShopEntry::Selling { item_id: format!("cosmos:glass_{c}"), max_quantity_selling: 10_000, price_per: $price, }).flatten(), */ // let entries = fab_recipes.iter().map(|recipe| { // recipe.inputs.iter().map(|x| match x.item {RecipeItem::Item(id) => { // items.from_id() // }}) // }) // let mut entries = vec![ // p!("iron_bar", 10), // p!("copper_bar", 5), // p!("lead_bar", 100), // p!("uranium", 300), // p!("sulfur", 40), // p!("gravitron_crystal", 1000), // p!("energite_crystal", 600), // p!("photonium_crystal", 300), // p!("uranium_fuel_cell", 3200), // p!("missile", 100), // p!("camera", 50), // p!("gravity_well", 1200), // p!("ramp", 10), // p!("ship_hull_grey", 10), // p!("grass", 20), // p!("stone", 10), // p!("dirt", 10), // p!("cherry_leaf", 50), // p!("cherry_log", 100), // p!("redwood_log", 100), // p!("redwood_leaf", 10), // p!("ship_core", 2000), // p!("energy_cell", 1000), // p!("passive_generator", 1000), // p!("laser_cannon", 1500), // p!("thruster", 400), // p!("light", 100), // p!("glass", 20), // p!("ice", 20), // p!("molten_rock", 10), // p!("sand", 10), // p!("cactus", 30), // p!("build_block", 1200), // p!("reactor_controller", 3000), // p!("reactor_casing", 600), // p!("reactor_window", 600), // p!("reactor_power_cell", 1500), // p!("storage", 50), // p!("station_core", 8000), // p!("plasma_drill", 500), // ]; let entries = items .iter() .flat_map(|item| compute_price(&base_prices, item.id(), &fab_recipes).map(|p| (item.id(), p))) .map(|(item, price)| { let item = items.from_numeric_id(item); PrettyShopEntry::Selling { item_id: item.unlocalized_name().into(), max_quantity_selling: 10_000, price_per: price, } }) .collect::<Vec<_>>(); // entries.append( // &mut COLORS // .map(|c| PrettyShopEntry::Selling { // item_id: format!("cosmos:glass_{c}"), // max_quantity_selling: 10_000, // price_per: 20, // }) // .into_iter() // .collect::<Vec<_>>(), // ); let new_entries = entries .into_iter() .flat_map(|x| { let PrettyShopEntry::Selling { item_id, max_quantity_selling, price_per, } = x else { unreachable!(); }; [ PrettyShopEntry::Selling { item_id: item_id.clone(), max_quantity_selling, price_per, }, PrettyShopEntry::Buying { item_id, max_quantity_buying: None, price_per: (price_per as f32 * 0.4) as u32, }, ] }) .collect::<Vec<PrettyShopEntry>>(); let json = serde_json::to_string_pretty(&new_entries).unwrap(); fs::write("./config/cosmos/default_shop.json", json).expect("Couldnt write config file to ./config/cosmos/default_shop.json"); commands.insert_resource(DefaultShopEntries(get_entries(new_entries, &items))); } fn load_default_shop_data(mut commands: Commands, items: Res<Registry<Item>>) { let json_data = std::fs::read_to_string("./config/cosmos/default_shop.json").expect("Unable to read config file!"); let data: Vec<PrettyShopEntry> = serde_json::from_str(&json_data).expect("Bad JSON data!"); commands.insert_resource(DefaultShopEntries(get_entries(data, &items))); } fn get_entries(entries: Vec<PrettyShopEntry>, items: &Registry<Item>) -> Vec<ShopEntry> { entries .into_iter() .map(|x| match x { PrettyShopEntry::Buying { item_id, max_quantity_buying, price_per, } => ShopEntry::Buying { item_id: items.from_id(&item_id).unwrap_or_else(|| panic!("Missing {item_id}")).id(), max_quantity_buying, price_per, }, PrettyShopEntry::Selling { item_id, max_quantity_selling, price_per, } => ShopEntry::Selling { item_id: items.from_id(&item_id).unwrap_or_else(|| panic!("Missing {item_id}")).id(), max_quantity_selling, price_per, }, }) .collect::<Vec<ShopEntry>>() } #[derive(Resource)] /// Contains the default entries for a shop pub struct DefaultShopEntries(pub Vec<ShopEntry>); pub(super) fn register(app: &mut App) { if !std::fs::exists("./config/cosmos/default_shop.json").unwrap_or(false) { app.add_systems(OnEnter(GameState::Playing), create_default_shop_entires); } else { app.add_systems(OnEnter(GameState::Playing), load_default_shop_data); } }
0
0.740404
1
0.740404
game-dev
MEDIA
0.856579
game-dev,web-backend
0.900675
1
0.900675
MinecraftTAS/LoTAS
1,201
src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinTimer.java
package com.minecrafttas.lotas.mixin.client.tickratechanger; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Timer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; import static com.minecrafttas.lotas.LoTAS.TICK_ADVANCE; /** * This mixin slows down the integrated Timer making the game run slower * * @author Pancake */ @Mixin(Timer.class) @Environment(EnvType.CLIENT) public class MixinTimer { @Shadow @Final @Mutable private float msPerTick; /** * Slow down the timer * * @param cir Returnable */ @Inject(method = "advanceTime", at = @At("HEAD")) public void onAdvanceTime(CallbackInfoReturnable<Integer> cir) { this.msPerTick = (float) (TICK_ADVANCE.isTickadvance() && !TICK_ADVANCE.shouldTickClient ? Float.MAX_VALUE : TICKRATE_CHANGER.getMsPerTick()); } }
0
0.835145
1
0.835145
game-dev
MEDIA
0.989139
game-dev
0.907754
1
0.907754
love2d/megasource
21,816
libs/SDL3/src/video/windows/SDL_windowsgameinput.cpp
/* Simple DirectMedia Layer Copyright (C) 1997-2025 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_windowsvideo.h" #ifdef HAVE_GAMEINPUT_H #include "../../core/windows/SDL_gameinput.h" extern "C" { #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/scancodes_windows.h" } #define MAX_GAMEINPUT_BUTTONS 7 // GameInputMouseWheelTiltRight is the highest button static const Uint8 GAMEINPUT_button_map[MAX_GAMEINPUT_BUTTONS] = { SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT, SDL_BUTTON_MIDDLE, SDL_BUTTON_X1, SDL_BUTTON_X2, 6, 7 }; typedef struct GAMEINPUT_Device { IGameInputDevice *pDevice; const GameInputDeviceInfo *info; char *name; Uint32 instance_id; // generated by SDL bool registered; bool delete_requested; IGameInputReading *last_mouse_reading; IGameInputReading *last_keyboard_reading; } GAMEINPUT_Device; struct WIN_GameInputData { IGameInput *pGameInput; GameInputCallbackToken gameinput_callback_token; int num_devices; GAMEINPUT_Device **devices; GameInputKind enabled_input; SDL_Mutex *lock; uint64_t timestamp_offset; }; static bool GAMEINPUT_InternalAddOrFind(WIN_GameInputData *data, IGameInputDevice *pDevice) { GAMEINPUT_Device **devicelist = NULL; GAMEINPUT_Device *device = NULL; const GameInputDeviceInfo *info; bool result = false; #if GAMEINPUT_API_VERSION >= 1 HRESULT hr = pDevice->GetDeviceInfo(&info); if (FAILED(hr)) { return WIN_SetErrorFromHRESULT("IGameInputDevice_GetDeviceInfo", hr); } #else info = pDevice->GetDeviceInfo(); #endif SDL_LockMutex(data->lock); { for (int i = 0; i < data->num_devices; ++i) { device = data->devices[i]; if (device && device->pDevice == pDevice) { // we're already added device->delete_requested = false; result = true; goto done; } } device = (GAMEINPUT_Device *)SDL_calloc(1, sizeof(*device)); if (!device) { goto done; } devicelist = (GAMEINPUT_Device **)SDL_realloc(data->devices, (data->num_devices + 1) * sizeof(*devicelist)); if (!devicelist) { SDL_free(device); goto done; } if (info->displayName) { // This could give us a product string, but it's NULL for all the devices I've tested } pDevice->AddRef(); device->pDevice = pDevice; device->instance_id = SDL_GetNextObjectID(); device->info = info; data->devices = devicelist; data->devices[data->num_devices++] = device; result = true; } done: SDL_UnlockMutex(data->lock); return result; } static bool GAMEINPUT_InternalRemoveByIndex(WIN_GameInputData *data, int idx) { GAMEINPUT_Device **devicelist = NULL; GAMEINPUT_Device *device; bool result = false; SDL_LockMutex(data->lock); { if (idx < 0 || idx >= data->num_devices) { result = SDL_SetError("GAMEINPUT_InternalRemoveByIndex argument idx %d is out of range", idx); goto done; } device = data->devices[idx]; if (device) { if (device->registered) { if (device->info->supportedInput & GameInputKindMouse) { SDL_RemoveMouse(device->instance_id, true); } if (device->info->supportedInput & GameInputKindKeyboard) { SDL_RemoveKeyboard(device->instance_id, true); } if (device->last_mouse_reading) { device->last_mouse_reading->Release(); device->last_mouse_reading = NULL; } if (device->last_keyboard_reading) { device->last_keyboard_reading->Release(); device->last_keyboard_reading = NULL; } } device->pDevice->Release(); SDL_free(device->name); SDL_free(device); } data->devices[idx] = NULL; if (data->num_devices == 1) { // last element in the list, free the entire list then SDL_free(data->devices); data->devices = NULL; } else { if (idx != data->num_devices - 1) { size_t bytes = sizeof(*devicelist) * (data->num_devices - idx - 1); SDL_memmove(&data->devices[idx], &data->devices[idx + 1], bytes); } } // decrement the count and return --data->num_devices; result = true; } done: SDL_UnlockMutex(data->lock); return result; } static void CALLBACK GAMEINPUT_InternalDeviceCallback( _In_ GameInputCallbackToken callbackToken, _In_ void *context, _In_ IGameInputDevice *pDevice, _In_ uint64_t timestamp, _In_ GameInputDeviceStatus currentStatus, _In_ GameInputDeviceStatus previousStatus) { WIN_GameInputData *data = (WIN_GameInputData *)context; int idx = 0; GAMEINPUT_Device *device = NULL; if (!pDevice) { // This should never happen, but ignore it if it does return; } if (currentStatus & GameInputDeviceConnected) { GAMEINPUT_InternalAddOrFind(data, pDevice); } else { for (idx = 0; idx < data->num_devices; ++idx) { device = data->devices[idx]; if (device && device->pDevice == pDevice) { // will be deleted on the next Detect call device->delete_requested = true; break; } } } } bool WIN_InitGameInput(SDL_VideoDevice *_this) { WIN_GameInputData *data; HRESULT hr; Uint64 now; uint64_t timestampUS; bool result = false; if (_this->internal->gameinput_context) { return true; } data = (WIN_GameInputData *)SDL_calloc(1, sizeof(*data)); if (!data) { goto done; } _this->internal->gameinput_context = data; data->lock = SDL_CreateMutex(); if (!data->lock) { goto done; } if (!SDL_InitGameInput(&data->pGameInput)) { goto done; } hr = data->pGameInput->RegisterDeviceCallback(NULL, (GameInputKindMouse | GameInputKindKeyboard), GameInputDeviceConnected, GameInputBlockingEnumeration, data, GAMEINPUT_InternalDeviceCallback, &data->gameinput_callback_token); if (FAILED(hr)) { WIN_SetErrorFromHRESULT("IGameInput::RegisterDeviceCallback", hr); goto done; } // Calculate the relative offset between SDL timestamps and GameInput timestamps now = SDL_GetTicksNS(); timestampUS = data->pGameInput->GetCurrentTimestamp(); data->timestamp_offset = (SDL_NS_TO_US(now) - timestampUS); result = true; done: if (!result) { WIN_QuitGameInput(_this); } return result; } static void GAMEINPUT_InitialMouseReading(WIN_GameInputData *data, SDL_Window *window, GAMEINPUT_Device *device, IGameInputReading *reading) { GameInputMouseState state; if (reading->GetMouseState(&state)) { Uint64 timestamp = SDL_US_TO_NS(reading->GetTimestamp() + data->timestamp_offset); SDL_MouseID mouseID = device->instance_id; for (int i = 0; i < MAX_GAMEINPUT_BUTTONS; ++i) { const GameInputMouseButtons mask = GameInputMouseButtons(1 << i); bool down = ((state.buttons & mask) != 0); SDL_SendMouseButton(timestamp, window, mouseID, GAMEINPUT_button_map[i], down); } // Invalidate mouse button flags window->internal->mouse_button_flags = (WPARAM)-1; } } static void GAMEINPUT_HandleMouseDelta(WIN_GameInputData *data, SDL_Window *window, GAMEINPUT_Device *device, IGameInputReading *last_reading, IGameInputReading *reading) { GameInputMouseState last; GameInputMouseState state; if (last_reading->GetMouseState(&last) && reading->GetMouseState(&state)) { Uint64 timestamp = SDL_US_TO_NS(reading->GetTimestamp() + data->timestamp_offset); SDL_MouseID mouseID = device->instance_id; GameInputMouseState delta; delta.buttons = (state.buttons ^ last.buttons); delta.positionX = (state.positionX - last.positionX); delta.positionY = (state.positionY - last.positionY); delta.wheelX = (state.wheelX - last.wheelX); delta.wheelY = (state.wheelY - last.wheelY); if (delta.positionX || delta.positionY) { SDL_SendMouseMotion(timestamp, window, mouseID, true, (float)delta.positionX, (float)delta.positionY); } if (delta.buttons) { for (int i = 0; i < MAX_GAMEINPUT_BUTTONS; ++i) { const GameInputMouseButtons mask = GameInputMouseButtons(1 << i); if (delta.buttons & mask) { bool down = ((state.buttons & mask) != 0); SDL_SendMouseButton(timestamp, window, mouseID, GAMEINPUT_button_map[i], down); } } // Invalidate mouse button flags window->internal->mouse_button_flags = (WPARAM)-1; } if (delta.wheelX || delta.wheelY) { float fAmountX = (float)delta.wheelX / WHEEL_DELTA; float fAmountY = (float)delta.wheelY / WHEEL_DELTA; SDL_SendMouseWheel(timestamp, SDL_GetMouseFocus(), device->instance_id, fAmountX, fAmountY, SDL_MOUSEWHEEL_NORMAL); } } } static SDL_Scancode GetScancodeFromKeyState(const GameInputKeyState *state) { Uint8 index = (Uint8)(state->scanCode & 0xFF); if ((state->scanCode & 0xFF00) == 0xE000) { index |= 0x80; } return windows_scancode_table[index]; } static bool KeysHaveScancode(const GameInputKeyState *keys, uint32_t count, SDL_Scancode scancode) { for (uint32_t i = 0; i < count; ++i) { if (GetScancodeFromKeyState(&keys[i]) == scancode) { return true; } } return false; } static void GAMEINPUT_InitialKeyboardReading(WIN_GameInputData *data, SDL_Window *window, GAMEINPUT_Device *device, IGameInputReading *reading) { Uint64 timestamp = SDL_US_TO_NS(reading->GetTimestamp() + data->timestamp_offset); SDL_KeyboardID keyboardID = device->instance_id; uint32_t max_keys = device->info->keyboardInfo->maxSimultaneousKeys; GameInputKeyState *keys = SDL_stack_alloc(GameInputKeyState, max_keys); if (!keys) { return; } uint32_t num_keys = reading->GetKeyState(max_keys, keys); if (!num_keys) { // FIXME: We probably need to track key state by keyboardID SDL_ResetKeyboard(); return; } // Go through and send key up events for any key that's not held down int num_scancodes; const bool *keyboard_state = SDL_GetKeyboardState(&num_scancodes); for (int i = 0; i < num_scancodes; ++i) { if (keyboard_state[i] && !KeysHaveScancode(keys, num_keys, (SDL_Scancode)i)) { SDL_SendKeyboardKey(timestamp, keyboardID, keys[i].scanCode, (SDL_Scancode)i, false); } } // Go through and send key down events for any key that's held down for (uint32_t i = 0; i < num_keys; ++i) { SDL_SendKeyboardKey(timestamp, keyboardID, keys[i].scanCode, GetScancodeFromKeyState(&keys[i]), true); } } #ifdef DEBUG_KEYS static void DumpKeys(const char *prefix, GameInputKeyState *keys, uint32_t count) { SDL_Log("%s", prefix); for (uint32_t i = 0; i < count; ++i) { char str[5]; *SDL_UCS4ToUTF8(keys[i].codePoint, str) = '\0'; SDL_Log(" Key 0x%.2x (%s)", keys[i].scanCode, str); } } #endif // DEBUG_KEYS static void GAMEINPUT_HandleKeyboardDelta(WIN_GameInputData *data, SDL_Window *window, GAMEINPUT_Device *device, IGameInputReading *last_reading, IGameInputReading *reading) { Uint64 timestamp = SDL_US_TO_NS(reading->GetTimestamp() + data->timestamp_offset); SDL_KeyboardID keyboardID = device->instance_id; uint32_t max_keys = device->info->keyboardInfo->maxSimultaneousKeys; GameInputKeyState *last = SDL_stack_alloc(GameInputKeyState, max_keys); GameInputKeyState *keys = SDL_stack_alloc(GameInputKeyState, max_keys); if (!last || !keys) { return; } uint32_t index_last = 0; uint32_t index_keys = 0; uint32_t num_last = last_reading->GetKeyState(max_keys, last); uint32_t num_keys = reading->GetKeyState(max_keys, keys); #ifdef DEBUG_KEYS SDL_Log("Timestamp: %llu", timestamp); DumpKeys("Last keys:", last, num_last); DumpKeys("New keys:", keys, num_keys); #endif while (index_last < num_last || index_keys < num_keys) { if (index_last < num_last && index_keys < num_keys) { if (last[index_last].scanCode == keys[index_keys].scanCode) { // No change ++index_last; ++index_keys; } else { // This key was released SDL_SendKeyboardKey(timestamp, keyboardID, last[index_last].scanCode, GetScancodeFromKeyState(&last[index_last]), false); ++index_last; } } else if (index_last < num_last) { // This key was released SDL_SendKeyboardKey(timestamp, keyboardID, last[index_last].scanCode, GetScancodeFromKeyState(&last[index_last]), false); ++index_last; } else { // This key was pressed SDL_SendKeyboardKey(timestamp, keyboardID, keys[index_keys].scanCode, GetScancodeFromKeyState(&keys[index_keys]), true); ++index_keys; } } } void WIN_UpdateGameInput(SDL_VideoDevice *_this) { WIN_GameInputData *data = _this->internal->gameinput_context; SDL_LockMutex(data->lock); { // Key events and relative mouse motion both go to the window with keyboard focus SDL_Window *window = SDL_GetKeyboardFocus(); for (int i = 0; i < data->num_devices; ++i) { GAMEINPUT_Device *device = data->devices[i]; IGameInputReading *reading; if (!device->registered) { if (device->info->supportedInput & GameInputKindMouse) { SDL_AddMouse(device->instance_id, device->name, true); } if (device->info->supportedInput & GameInputKindKeyboard) { SDL_AddKeyboard(device->instance_id, device->name, true); } device->registered = true; } if (device->delete_requested) { GAMEINPUT_InternalRemoveByIndex(data, i--); continue; } if (!(device->info->supportedInput & data->enabled_input)) { continue; } if (!window) { continue; } if (data->enabled_input & GameInputKindMouse) { if (device->last_mouse_reading) { HRESULT hr; while (SUCCEEDED(hr = data->pGameInput->GetNextReading(device->last_mouse_reading, GameInputKindMouse, device->pDevice, &reading))) { GAMEINPUT_HandleMouseDelta(data, window, device, device->last_mouse_reading, reading); device->last_mouse_reading->Release(); device->last_mouse_reading = reading; } if (hr != GAMEINPUT_E_READING_NOT_FOUND) { if (SUCCEEDED(data->pGameInput->GetCurrentReading(GameInputKindMouse, device->pDevice, &reading))) { GAMEINPUT_HandleMouseDelta(data, window, device, device->last_mouse_reading, reading); device->last_mouse_reading->Release(); device->last_mouse_reading = reading; } } } else { if (SUCCEEDED(data->pGameInput->GetCurrentReading(GameInputKindMouse, device->pDevice, &reading))) { GAMEINPUT_InitialMouseReading(data, window, device, reading); device->last_mouse_reading = reading; } } } if (data->enabled_input & GameInputKindKeyboard) { if (window->text_input_active) { // Reset raw input while text input is active if (device->last_keyboard_reading) { device->last_keyboard_reading->Release(); device->last_keyboard_reading = NULL; } } else { if (device->last_keyboard_reading) { HRESULT hr; while (SUCCEEDED(hr = data->pGameInput->GetNextReading(device->last_keyboard_reading, GameInputKindKeyboard, device->pDevice, &reading))) { GAMEINPUT_HandleKeyboardDelta(data, window, device, device->last_keyboard_reading, reading); device->last_keyboard_reading->Release(); device->last_keyboard_reading = reading; } if (hr != GAMEINPUT_E_READING_NOT_FOUND) { if (SUCCEEDED(data->pGameInput->GetCurrentReading(GameInputKindKeyboard, device->pDevice, &reading))) { GAMEINPUT_HandleKeyboardDelta(data, window, device, device->last_keyboard_reading, reading); device->last_keyboard_reading->Release(); device->last_keyboard_reading = reading; } } } else { if (SUCCEEDED(data->pGameInput->GetCurrentReading(GameInputKindKeyboard, device->pDevice, &reading))) { GAMEINPUT_InitialKeyboardReading(data, window, device, reading); device->last_keyboard_reading = reading; } } } } } } SDL_UnlockMutex(data->lock); } bool WIN_UpdateGameInputEnabled(SDL_VideoDevice *_this) { WIN_GameInputData *data = _this->internal->gameinput_context; bool raw_mouse_enabled = _this->internal->raw_mouse_enabled; bool raw_keyboard_enabled = _this->internal->raw_keyboard_enabled; SDL_LockMutex(data->lock); { data->enabled_input = (raw_mouse_enabled ? GameInputKindMouse : GameInputKindUnknown) | (raw_keyboard_enabled ? GameInputKindKeyboard : GameInputKindUnknown); // Reset input if not enabled for (int i = 0; i < data->num_devices; ++i) { GAMEINPUT_Device *device = data->devices[i]; if (device->last_mouse_reading && !raw_mouse_enabled) { device->last_mouse_reading->Release(); device->last_mouse_reading = NULL; } if (device->last_keyboard_reading && !raw_keyboard_enabled) { device->last_keyboard_reading->Release(); device->last_keyboard_reading = NULL; } } } SDL_UnlockMutex(data->lock); return true; } void WIN_QuitGameInput(SDL_VideoDevice *_this) { WIN_GameInputData *data = _this->internal->gameinput_context; if (!data) { return; } if (data->pGameInput) { // free the callback if (data->gameinput_callback_token) { #if GAMEINPUT_API_VERSION >= 1 data->pGameInput->UnregisterCallback(data->gameinput_callback_token); #else data->pGameInput->UnregisterCallback(data->gameinput_callback_token, 10000); #endif data->gameinput_callback_token = 0; } // free the list while (data->num_devices > 0) { GAMEINPUT_InternalRemoveByIndex(data, 0); } data->pGameInput->Release(); data->pGameInput = NULL; } if (data->pGameInput) { SDL_QuitGameInput(); data->pGameInput = NULL; } if (data->lock) { SDL_DestroyMutex(data->lock); data->lock = NULL; } SDL_free(data); _this->internal->gameinput_context = NULL; } #else // !HAVE_GAMEINPUT_H bool WIN_InitGameInput(SDL_VideoDevice *_this) { return SDL_Unsupported(); } bool WIN_UpdateGameInputEnabled(SDL_VideoDevice *_this) { return SDL_Unsupported(); } void WIN_UpdateGameInput(SDL_VideoDevice *_this) { return; } void WIN_QuitGameInput(SDL_VideoDevice *_this) { return; } #endif // HAVE_GAMEINPUT_H
0
0.932824
1
0.932824
game-dev
MEDIA
0.543227
game-dev
0.977817
1
0.977817
OpenRA/OpenRA
1,614
OpenRA.Mods.Common/Traits/CarryableHarvester.cs
#region Copyright & License Information /* * Copyright (c) The OpenRA Developers and Contributors * This file is part of OpenRA, which is free software. It is made * available to you 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 more * information, see COPYING. */ #endregion using System.Linq; using OpenRA.Traits; namespace OpenRA.Mods.Common.Traits { public class CarryableHarvesterInfo : TraitInfo { public override object Create(ActorInitializer init) { return new CarryableHarvester(); } } public class CarryableHarvester : INotifyCreated, INotifyHarvestAction, INotifyDockClientMoving { ICallForTransport[] transports; void INotifyCreated.Created(Actor self) { transports = self.TraitsImplementing<ICallForTransport>().ToArray(); } void INotifyHarvestAction.MovingToResources(Actor self, CPos targetCell) { foreach (var t in transports) t.RequestTransport(self, targetCell); } void INotifyHarvestAction.MovementCancelled(Actor self) { foreach (var t in transports) t.MovementCancelled(self); } void INotifyDockClientMoving.MovingToDock(Actor self, Actor hostActor, IDockHost host) { foreach (var t in transports) t.RequestTransport(self, self.World.Map.CellContaining(host.DockPosition)); } void INotifyDockClientMoving.MovementCancelled(Actor self) { foreach (var t in transports) t.MovementCancelled(self); } void INotifyHarvestAction.Harvested(Actor self, string resourceType) { } } }
0
0.721554
1
0.721554
game-dev
MEDIA
0.593893
game-dev
0.637019
1
0.637019
fsmosca/chess-artist
1,476
create_puzzle.bat
:: Generate puzzles chess_artist.py --infile ./PGN/skillingopp20.pgn --outfile out_skilling.pgn --enginename "Sf12" --enginefile ./Engine/stockfish/stockfish_12_x64_modern.exe --engineoptions "Threads value 1, Hash value 256" --movestart 12 --movetime 10000 --job createpuzzle --eval search --log :: Example command line :: chess_artist.py --infile pgn\tatagpa20.pgn --outfile out_tatagpa20.pgn --enginename "Lc0 v0.23.2 w591097 blas" --enginefile D:\Chess\Engines\Lc0\lc0-v0.23.2-591097-10X128\lc0.exe --engineoptions "Threads value 2, MinibatchSize value 8, MaxPrefetch value 0" --movestart 15 --movetime 10000 --job createpuzzle --eval search --log :: Create puzzle using atomic variant :: chess_artist.py --infile pgn\sample_atomic.pgn --outfile dummy.pgn --enginename "Stockfish_2020-06-13_Multi-Variant" --enginefile D:\github\chess-artist\Engine\Stockfish_2020-06-13_Multi-Variant.exe --engineoptions "Threads value 1, Hash value 128, UCI_Variant value Atomic" --movestart 2 --movetime 1000 --job createpuzzle --eval search --log :: Create puzzle from an atomic960 game :: chess_artist.py --game960 --infile ./PGN/sample_atomic_chess960.pgn --outfile dummy.pgn --enginename "Stockfish_2020-06-13_Multi-Variant" --enginefile ./Engine/stockfish/Stockfish_2020-06-13_Multi-Variant.exe --engineoptions "Threads value 1, Hash value 128, UCI_Variant value Atomic, UCI_Chess960 value true" --movestart 2 --movetime 10000 --job createpuzzle --eval search --log pause
0
0.635164
1
0.635164
game-dev
MEDIA
0.852241
game-dev
0.642163
1
0.642163
DeanRoddey/CIDLib
11,495
Source/AllProjects/CIDKernel/Linux/CIDKernel_SharedMemBuf_Linux.cpp
// // FILE NAME: CIDKernel_SharedMemBuf_Linux.Cpp // // AUTHOR: Will Mason // // CREATED: 12/16/1998 // // COPYRIGHT: Charmed Quark Systems, Ltd - 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file provides the Linux specific implementation of the class // TKrnlSharedMemBuf // // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CIDKernel_.hpp" #include "CIDKernel_InternalHelpers_.hpp" // --------------------------------------------------------------------------- // CLASS: TMemoryHandle // PREFIX: hev // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMemoryHandle: Constructors and Destructor // --------------------------------------------------------------------------- TMemoryHandle::TMemoryHandle() : m_phmemiThis(nullptr) { } TMemoryHandle::TMemoryHandle(const TMemoryHandle& hmemToCopy) : m_phmemiThis(hmemToCopy.m_phmemiThis) { } TMemoryHandle::~TMemoryHandle() { m_phmemiThis = nullptr; } // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TMemoryHandle& TMemoryHandle::operator=(const TMemoryHandle& hmemToAssign) { if (this == &hmemToAssign) return *this; m_phmemiThis = hmemToAssign.m_phmemiThis; return *this; } tCIDLib::TBoolean TMemoryHandle::operator==(const TMemoryHandle& hmemToCompare) const { return (m_phmemiThis == hmemToCompare.m_phmemiThis); } // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean TMemoryHandle::bIsValid() const { return (m_phmemiThis && m_phmemiThis->c4RefCount); } tCIDLib::TVoid TMemoryHandle::Clear() { m_phmemiThis = nullptr; } tCIDLib::TVoid TMemoryHandle::FormatToStr( tCIDLib::TCh* const pszToFill , const tCIDLib::TCard4 c4MaxChars) const { TRawStr::bFormatVal ( tCIDLib::TInt4(m_phmemiThis) , pszToFill , c4MaxChars , tCIDLib::ERadices::Hex ); } // --------------------------------------------------------------------------- // TKrnlSharedMemBuf: Constructors and Destructor // --------------------------------------------------------------------------- TKrnlSharedMemBuf::TKrnlSharedMemBuf() : m_c4AllocatedPages(0) , m_c4MaxSize(0) , m_eAccess(tCIDLib::EMemAccFlags::ReadOnly) , m_pBuffer(nullptr) , m_pszName(nullptr) { } TKrnlSharedMemBuf::~TKrnlSharedMemBuf() { if (!bFree()) { // // If it fails and we are debugging, then do a popup. Otherwise // there is not much we can do. // #if CID_DEBUG_ON kmodCIDKernel.KrnlErrorPopUp ( TKrnlError::kerrLast() , CID_FILE , CID_LINE , kmodCIDKernel.pszLoadCIDFacMsg(kKrnlErrs::errcGen_CloseHandle) ); #endif } } // --------------------------------------------------------------------------- // TKrnlSharedMemBuf: Public operators // --------------------------------------------------------------------------- tCIDLib::TBoolean TKrnlSharedMemBuf::operator==(const TKrnlSharedMemBuf& ksmbToCompare) const { // // We only compare the name and access at this level. The public CIDLib // class that uses us as its implementation, TSharedMemBuf, will handle // the actual memory comparison. // if (!TRawStr::bCompareStr(m_pszName, ksmbToCompare.m_pszName)) return kCIDLib::False; if (m_eAccess != ksmbToCompare.m_eAccess) return kCIDLib::False; return kCIDLib::True; } // --------------------------------------------------------------------------- // TKrnlSharedMemBuf: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TKrnlSharedMemBuf::bAlloc( const tCIDLib::TCh* const pszName , const tCIDLib::TCard4 c4MaxSize , const tCIDLib::EAllocTypes eAllocType , const tCIDLib::EMemAccFlags eAccess , tCIDLib::TBoolean& bCreated , const tCIDLib::ECreateActs eCreateFlags) { if (m_hmemThis.bIsValid()) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcGen_AlreadyAllocated); return kCIDLib::False; } if (!pszName) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcGen_NullName); return kCIDLib::False; } if (eCreateFlags == tCIDLib::ECreateActs::TruncateExisting) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcData_InvalidParameter); return kCIDLib::False; } // Replicate the name of the buffer m_pszName = TRawStr::pszReplicate(pszName); // Store the size and allocate type stuff m_c4MaxSize = c4MaxSize; m_eAccess = eAccess; m_eAllocType = eAllocType; // Calculate the maximum pages m_c4MaxPages = (c4MaxSize / kCIDLib::c4MemPageSize); if (c4MaxSize % kCIDLib::c4MemPageSize) m_c4MaxPages++; // <TBD> For now, just say all allocated. We need to come back to this m_c4AllocatedPages = m_c4MaxPages; // Translate the creation flags tCIDLib::TSInt iFlags; tCIDLib::TBoolean bOwner; if (eCreateFlags == tCIDLib::ECreateActs::CreateAlways || eCreateFlags == tCIDLib::ECreateActs::OpenOrCreate || eCreateFlags == tCIDLib::ECreateActs::CreateIfNew) { iFlags = IPC_CREAT | IPC_EXCL; bOwner = kCIDLib::True; } else { iFlags = 0; bOwner = kCIDLib::False; } // Translate the access flags if (m_eAccess == tCIDLib::EMemAccFlags::ReadOnly) iFlags |= S_IRUSR | S_IRGRP | S_IROTH; else if (m_eAccess == tCIDLib::EMemAccFlags::ReadWrite) iFlags |= S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IWGRP | S_IWOTH; else { TKrnlError::SetLastKrnlError(kKrnlErrs::errcAcc_InvalidAccess); return kCIDLib::False; } key_t key = TRawStr::hshHashStr(pszName, kCIDLib::i4MaxInt); tCIDLib::TSInt iTmpId = ::shmget(key, c4MaxSize, iFlags); if (iTmpId == -1) { if (errno == EEXIST && eCreateFlags == tCIDLib::ECreateActs::OpenOrCreate) { bOwner = kCIDLib::False; iFlags &= ~(IPC_CREAT | IPC_EXCL); iTmpId = ::shmget(key, c4MaxSize, iFlags); if (iTmpId == -1) { TKrnlError::SetLastHostError(errno); return kCIDLib::False; } } else { TKrnlError::SetLastHostError(errno); return kCIDLib::False; } } iFlags = (m_eAccess == tCIDLib::EMemAccFlags::ReadOnly) ? SHM_RDONLY : 0; tCIDLib::TVoid* pTmp = ::shmat(iTmpId, 0, iFlags); if (pTmp == reinterpret_cast<tCIDLib::TVoid*>(-1)) { TKrnlError::SetLastHostError(errno); if (bOwner) ::shmctl(iTmpId, IPC_RMID, 0); return kCIDLib::False; } m_pBuffer = pTmp; m_hmemThis.m_phmemiThis = new TMemoryHandleImpl; m_hmemThis.m_phmemiThis->c4RefCount = 1; m_hmemThis.m_phmemiThis->iShmId = iTmpId; m_hmemThis.m_phmemiThis->bOwner = bCreated = bOwner; m_hmemThis.m_phmemiThis->prmtxThis = new TKrnlLinux::TRecursiveMutex(); m_hmemThis.m_phmemiThis->prmtxThis->iInitialize(); return kCIDLib::True; } tCIDLib::TBoolean TKrnlSharedMemBuf::bDuplicate(const TKrnlSharedMemBuf& ksmbSrc) { // Can't do this if there is already a buffer in this object if (m_hmemThis.bIsValid()) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcGen_AlreadyAllocated); return kCIDLib::False; } m_pBuffer = ksmbSrc.m_pBuffer; m_eAccess = ksmbSrc.m_eAccess; m_c4AllocatedPages = ksmbSrc.m_c4AllocatedPages; m_c4MaxPages = ksmbSrc.m_c4MaxPages; m_c4MaxSize = ksmbSrc.m_c4MaxSize; if (ksmbSrc.m_pszName) { delete [] m_pszName; m_pszName = TRawStr::pszReplicate(ksmbSrc.m_pszName); } m_hmemThis = ksmbSrc.m_hmemThis; if (m_hmemThis.bIsValid()) { m_hmemThis.m_phmemiThis->prmtxThis->iLock(); m_hmemThis.m_phmemiThis->c4RefCount++; m_hmemThis.m_phmemiThis->prmtxThis->iUnlock(); } return kCIDLib::True; } // Fow now a no-op, since we are always fully committed tCIDLib::TBoolean TKrnlSharedMemBuf::bCommitToSize(const tCIDLib::TCard4 c4NewSize) { // If this is beyond the max size, its an error if (c4NewSize > m_c4MaxSize) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcData_BufferOverflow); return kCIDLib::False; } return kCIDLib::True; } tCIDLib::TBoolean TKrnlSharedMemBuf::bFree() { // If the name got allocated, then free it delete [] m_pszName; m_pszName = nullptr; if (m_hmemThis.bIsValid()) { m_hmemThis.m_phmemiThis->prmtxThis->iLock(); // Copy our buffer pointer and then zero it, so we ar esure it's cleraed tCIDLib::TVoid* pBuf = m_pBuffer; m_pBuffer = nullptr; if (!--m_hmemThis.m_phmemiThis->c4RefCount) { if (::shmdt(reinterpret_cast<tCIDLib::TSCh*>(pBuf))) { m_hmemThis.m_phmemiThis->c4RefCount++; m_hmemThis.m_phmemiThis->prmtxThis->iUnlock(); TKrnlError::SetLastHostError(errno); return kCIDLib::False; } if (m_hmemThis.m_phmemiThis->bOwner) { if (::shmctl(m_hmemThis.m_phmemiThis->iShmId, IPC_RMID, 0)) { m_hmemThis.m_phmemiThis->c4RefCount++; m_hmemThis.m_phmemiThis->prmtxThis->iUnlock(); TKrnlError::SetLastHostError(errno); return kCIDLib::False; } } m_hmemThis.m_phmemiThis->prmtxThis->iUnlock(); tCIDLib::TOSErrCode HostErr; HostErr = m_hmemThis.m_phmemiThis->prmtxThis->iDestroy(); if (HostErr) { TKrnlError::SetLastHostError(HostErr); return kCIDLib::False; } delete m_hmemThis.m_phmemiThis->prmtxThis; delete m_hmemThis.m_phmemiThis; } else { m_hmemThis.m_phmemiThis->prmtxThis->iUnlock(); } } return kCIDLib::True; } // <TBD> For now a no-op for us tCIDLib::TBoolean TKrnlSharedMemBuf::bSyncView() { return kCIDLib::True; } tCIDLib::TBoolean TKrnlSharedMemBuf::bZero() { if (!m_pBuffer) { TKrnlError::SetLastKrnlError(kKrnlErrs::errcGen_NotReady); return kCIDLib::False; } // Zero out the allocated pages TRawMem::SetMemBuf(m_pBuffer, tCIDLib::TCard1(0), m_c4AllocatedPages * kCIDLib::c4MemPageSize); return kCIDLib::True; }
0
0.905085
1
0.905085
game-dev
MEDIA
0.439838
game-dev
0.929646
1
0.929646
RCInet/LastEpoch_Mods
6,406
AssetBundleExport/Library/PackageCache/com.unity.ugui@9496653a3df6/Editor/UGUI/UI/InputFieldEditor.cs
using UnityEditor.AnimatedValues; using UnityEngine; using UnityEngine.UI; namespace UnityEditor.UI { [CanEditMultipleObjects] [CustomEditor(typeof(InputField), true)] /// <summary> /// Custom Editor for the InputField Component. /// Extend this class to write a custom editor for a component derived from InputField. /// </summary> public class InputFieldEditor : SelectableEditor { SerializedProperty m_TextComponent; SerializedProperty m_Text; SerializedProperty m_ContentType; SerializedProperty m_LineType; SerializedProperty m_InputType; SerializedProperty m_CharacterValidation; SerializedProperty m_KeyboardType; SerializedProperty m_CharacterLimit; SerializedProperty m_CaretBlinkRate; SerializedProperty m_CaretWidth; SerializedProperty m_CaretColor; SerializedProperty m_CustomCaretColor; SerializedProperty m_SelectionColor; SerializedProperty m_HideMobileInput; SerializedProperty m_Placeholder; SerializedProperty m_OnValueChanged; SerializedProperty m_OnSubmit; SerializedProperty m_OnDidEndEdit; SerializedProperty m_ReadOnly; SerializedProperty m_ShouldActivateOnSelect; AnimBool m_CustomColor; GUIContent m_EndEditContent = new GUIContent("On End Edit"); protected override void OnEnable() { base.OnEnable(); m_TextComponent = serializedObject.FindProperty("m_TextComponent"); m_Text = serializedObject.FindProperty("m_Text"); m_ContentType = serializedObject.FindProperty("m_ContentType"); m_LineType = serializedObject.FindProperty("m_LineType"); m_InputType = serializedObject.FindProperty("m_InputType"); m_CharacterValidation = serializedObject.FindProperty("m_CharacterValidation"); m_KeyboardType = serializedObject.FindProperty("m_KeyboardType"); m_CharacterLimit = serializedObject.FindProperty("m_CharacterLimit"); m_CaretBlinkRate = serializedObject.FindProperty("m_CaretBlinkRate"); m_CaretWidth = serializedObject.FindProperty("m_CaretWidth"); m_CaretColor = serializedObject.FindProperty("m_CaretColor"); m_CustomCaretColor = serializedObject.FindProperty("m_CustomCaretColor"); m_SelectionColor = serializedObject.FindProperty("m_SelectionColor"); m_HideMobileInput = serializedObject.FindProperty("m_HideMobileInput"); m_Placeholder = serializedObject.FindProperty("m_Placeholder"); m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged"); m_OnSubmit = serializedObject.FindProperty("m_OnSubmit"); m_OnDidEndEdit = serializedObject.FindProperty("m_OnDidEndEdit"); m_ReadOnly = serializedObject.FindProperty("m_ReadOnly"); m_ShouldActivateOnSelect = serializedObject.FindProperty("m_ShouldActivateOnSelect"); m_CustomColor = new AnimBool(m_CustomCaretColor.boolValue); m_CustomColor.valueChanged.AddListener(Repaint); } protected override void OnDisable() { base.OnDisable(); m_CustomColor.valueChanged.RemoveListener(Repaint); } public override void OnInspectorGUI() { serializedObject.Update(); base.OnInspectorGUI(); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_TextComponent); if (m_TextComponent != null && m_TextComponent.objectReferenceValue != null) { Text text = m_TextComponent.objectReferenceValue as Text; if (text.supportRichText) { EditorGUILayout.HelpBox("Using Rich Text with input is unsupported.", MessageType.Warning); } } using (new EditorGUI.DisabledScope(m_TextComponent == null || m_TextComponent.objectReferenceValue == null)) { EditorGUILayout.PropertyField(m_Text); EditorGUILayout.PropertyField(m_CharacterLimit); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_ContentType); if (!m_ContentType.hasMultipleDifferentValues) { EditorGUI.indentLevel++; if (m_ContentType.enumValueIndex == (int)InputField.ContentType.Standard || m_ContentType.enumValueIndex == (int)InputField.ContentType.Autocorrected || m_ContentType.enumValueIndex == (int)InputField.ContentType.Custom) EditorGUILayout.PropertyField(m_LineType); if (m_ContentType.enumValueIndex == (int)InputField.ContentType.Custom) { EditorGUILayout.PropertyField(m_InputType); EditorGUILayout.PropertyField(m_KeyboardType); EditorGUILayout.PropertyField(m_CharacterValidation); } EditorGUI.indentLevel--; } EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_Placeholder); EditorGUILayout.PropertyField(m_CaretBlinkRate); EditorGUILayout.PropertyField(m_CaretWidth); EditorGUILayout.PropertyField(m_CustomCaretColor); m_CustomColor.target = m_CustomCaretColor.boolValue; if (EditorGUILayout.BeginFadeGroup(m_CustomColor.faded)) { EditorGUILayout.PropertyField(m_CaretColor); } EditorGUILayout.EndFadeGroup(); EditorGUILayout.PropertyField(m_SelectionColor); EditorGUILayout.PropertyField(m_HideMobileInput); EditorGUILayout.PropertyField(m_ReadOnly); EditorGUILayout.PropertyField(m_ShouldActivateOnSelect); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_OnValueChanged); EditorGUILayout.PropertyField(m_OnSubmit); EditorGUILayout.PropertyField(m_OnDidEndEdit, m_EndEditContent); } serializedObject.ApplyModifiedProperties(); } } }
0
0.812269
1
0.812269
game-dev
MEDIA
0.925839
game-dev
0.912266
1
0.912266
dz333n/Singularity-OS
118,447
base/Applications/Runtime/Full/System/String.cs
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //============================================================ // // Class: String // // Purpose: Contains headers for the String class. Actual implementations // are in String.cpp // //=========================================================== namespace System { using System.Text; using System; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Bartok.Runtime; // // For Information on these methods, please see COMString.cpp // // The String class represents a static string of characters. Many of // the String methods perform some type of transformation on the current // instance and return the result as a new String. All comparison methods are // implemented as a part of String. As with arrays, character positions // (indices) are zero-based. // //| <include path='docs/doc[@for="String"]/*' /> public sealed partial class String : IComparable, ICloneable, IEnumerable { // //Native Static Methods // // Joins an array of strings together as one string with a separator between each original string. // //| <include path='docs/doc[@for="String.Join"]/*' /> public static String Join(String separator, String[] value) { if (value == null) { throw new ArgumentNullException("value"); } return Join(separator, value, 0, value.Length); } /// // Joins an array of strings together as one string with a separator // between each original string. // // @param separator the string used as a separator. // @param value the array of strings to be joined. // @param startIndex the position within the array to start using // strings. // @param count the number of strings to take from the array. // // @return a string consisting of the strings contained in <i>value</i> // from <EM>startIndex</EM> to <EM>startIndex</EM> + <EM>count</EM> // joined together to form a single string, with each of the original // strings separated by <i>separator</i>. // //| <include path='docs/doc[@for="String.Join1"]/*' /> public static String Join(String separator, String[] value, int startIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::JoinArray if (separator == null) { separator = String.Empty; } if (value == null) { throw new ArgumentNullException("value array is null"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex is negative"); } if (count < 0) { throw new ArgumentOutOfRangeException("count is negative"); } if (startIndex + count > value.Length) { throw new ArgumentOutOfRangeException("startIndex+count>value.Length"); } // Special case the empty list of strings if (count == 0) { return String.Empty; } // Compute the length of the new string int newLength = 0; int limit = startIndex + count; for (int i = startIndex; i < limit; i++) { String s = value[i]; if (s != null) { newLength += s.m_stringLength; } } newLength += (count - 1) * separator.m_stringLength; // Create a new String String result = FastAllocateString(newLength); if (newLength == 0) { return result; } // Fill in the string int dstIndex = 0; String firstString = value[startIndex]; if (firstString != null) { FillString(result, 0, firstString); dstIndex = firstString.m_stringLength; } for (int i = startIndex + 1; i < limit; i++) { FillString(result, dstIndex, separator); dstIndex += separator.m_stringLength; String elementString = value[i]; if (elementString != null) { FillString(result, dstIndex, elementString); dstIndex += elementString.m_stringLength; } } return result; } private unsafe static bool CaseInsensitiveCompHelper(char * strAChars, char * strBChars, int aLength, int bLength, out int result) { char charA; char charB; char *strAStart; strAStart = strAChars; result = 0; // setup the pointers so that we can always increment them. // We never access these pointers at the negative offset. strAChars--; strBChars--; do { strAChars++; strBChars++; charA = *strAChars; charB = *strBChars; //Case-insensitive comparison on chars greater than 0x80 requires //a locale-aware casing operation and we're not going there. if (charA >= 0x80 || charB >= 0x80) { // TODO: We should be able to fix this. return false; } // Do the right thing if they differ in case only. // We depend on the fact that the uppercase and lowercase letters // in the range which we care about (A-Z,a-z) differ only by the // 0x20 bit. // The check below takes the xor of the two characters and // determines if this bit is only set on one of them. // If they're different cases, we know that we need to execute // only one of the conditions within block. if (((charA^charB) & 0x20) != 0) { if (charA >='A' && charA <='Z') { charA |= (char)0x20; } else if (charB >='A' && charB <='Z') { charB |= (char)0x20; } } } while (charA == charB && charA != 0); // Return the (case-insensitive) difference between them. if (charA != charB) { result = (int)(charA-charB); return true; } // The length of b was unknown because it was just a pointer to a // null-terminated string. // If we get here, we know that both A and B are pointing at a null. // However, A can have an embedded null. Check the number of // characters that we've walked in A against the expected length. if (bLength == -1) { if ((strAChars - strAStart) != aLength) { result = 1; return true; } result=0; return true; } result = (aLength - bLength); return true; } internal unsafe static int nativeCompareOrdinal(String strA, String strB, bool bIgnoreCase) { // See also Lightning\Src\VM\COMString.cpp::FCCompareOrdinal int strALength = strA.Length; int strBLength = strB.Length; fixed(char * strAChars = &strA.m_firstChar) { fixed(char * strBCharsStart = &strB.m_firstChar) { // Need copy because fixed vars are readonly char * strBChars = strBCharsStart; // Handle the comparison where we wish to ignore case. if (bIgnoreCase) { int result; if (CaseInsensitiveCompHelper(strAChars, strBChars, strALength, strBLength, out result)) { return result; } else { // This will happen if we have characters greater // than 0x7F. throw new ArgumentException(); } } // If the strings are the same length, compare exactly the // right # of chars. If they are different, compare the // shortest # + 1 (the '\0'). int count = strALength; if (count > strBLength) count = strBLength; long diff = (byte*)strAChars - (byte*)strBChars; // Loop comparing a DWORD at a time. while ((count -= 2) >= 0) { if (((*(int*)((byte*)strBChars + diff)) - *(int*)strBChars) != 0) { char * ptr1 = (char*)((byte*)strBChars + diff); char * ptr2 = strBChars; if (*ptr1 != *ptr2) { return ((int)*ptr1 - (int)*ptr2); } return ((int)*(ptr1+1) - (int)*(ptr2+1)); } // differs from COMString.cpp because they have DWORD* // and we use char* strBChars += 2; } // Handle an extra WORD. int c; if (count == -1) { c = *((char*)((byte*)strBChars+diff)) - *strBChars; if (c != 0) { return c; } } return strALength - strBLength; } } } internal static int nativeCompareOrdinalEx(String strA, int indexA, String strB, int indexB, int count) { // See also Lightning\Src\VM\COMString.cpp::CompareOrdinalEx throw new Exception("System.String.nativeCompareOrdinalEx not implemented in Bartok!"); } // // This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less // than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's) // from the assembly. This provides a workaround for that problem and should NOT be used anywhere else. // internal static String SmallCharToUpper(String strA) { String newString = FastAllocateString(strA.Length); nativeSmallCharToUpper(strA, newString); return newString; } private static void nativeSmallCharToUpper(String strIn, String strOut) { // See also Lightning\Src\VM\COMString.cpp::SmallCharToUpper throw new Exception("System.String.nativeSmallCharToUpper not implemented in Bartok!"); } // This is a helper method for the security team. They need to construct strings from a char[] // within their homebrewed XML parser. They guarantee that the char[] they pass in isn't null and // that the provided indices are valid so we just stuff real fast. internal static String CreateFromCharArray(char[] array, int start, int count) { String newString = FastAllocateString(count); FillStringArray(newString, 0, array, start, count); return newString; } // // // NATIVE INSTANCE METHODS // // // // Search/Query methods // // Determines whether two strings match. //| <include path='docs/doc[@for="String.Equals"]/*' /> public override bool Equals(Object obj) { if (obj is String) { return this.Equals((String) obj); } else { return false; } } // Determines whether two strings match. //| <include path='docs/doc[@for="String.Equals1"]/*' /> public unsafe bool Equals(String value) { if (value == null) { return false; } if (this.m_stringLength != value.m_stringLength) { return false; } fixed (char *thisCharPtr = &this.m_firstChar) { fixed (char *valueCharPtr = &value.m_firstChar) { char *thisCursor = thisCharPtr; char *valueCursor = valueCharPtr; for (int i = this.m_stringLength; i > 0; i--) { if (*thisCursor != *valueCursor) { return false; } thisCursor++; valueCursor++; } } } return true; } // Determines whether two Strings match. //| <include path='docs/doc[@for="String.Equals2"]/*' /> public static bool Equals(String a, String b) { if ((Object)a ==(Object)b) { return true; } if ((Object)a == null || (Object)b == null) { return false; } return a.Equals(b); } //| <include path='docs/doc[@for="String.operatorEQ"]/*' /> public static bool operator == (String a, String b) { return String.Equals(a, b); } //| <include path='docs/doc[@for="String.operatorNE"]/*' /> public static bool operator != (String a, String b) { return !String.Equals(a, b); } internal unsafe char InternalGetChar(int index) { // See also Lightning\Src\VM\COMString.cpp::GetCharAt if ((uint) index >= (uint) this.m_stringLength) { throw new IndexOutOfRangeException(); } fixed (char *charPtr = &this.m_firstChar) { return charPtr[index]; } } // Gets the character at a specified position. // //| <include path='docs/doc[@for="String.this"]/*' /> public char this[int index] { get { return InternalGetChar(index); } } internal unsafe int InternalGetChars(char *output, int maxput) { fixed (char *charPtr = &this.m_firstChar) { int i; for (i = 0; i < m_stringLength && i < maxput; i++) { output[i] = charPtr[i]; } return i; } } // Converts a substring of this string to an array of characters. Copies the // characters of this string beginning at position startIndex and ending at // startIndex + length - 1 to the character array buffer, beginning // at bufferStartIndex. // //| <include path='docs/doc[@for="String.CopyTo"]/*' /> public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException("destination"); if (count < 0) throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_NegativeCount"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex", "ArgumentOutOfRange_Index"); if (count > Length - sourceIndex) throw new ArgumentOutOfRangeException("sourceIndex", "ArgumentOutOfRange_IndexCount"); if (destinationIndex > destination.Length - count || destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex", "ArgumentOutOfRange_IndexCount"); InternalCopyTo(sourceIndex, destination, destinationIndex, count); } internal unsafe void InternalCopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::GetPreallocatedCharArray if (sourceIndex + count > this.m_stringLength) { throw new ArgumentOutOfRangeException(); } if (count > 0) { // Necessary test as &destination[0] is illegal for empty array fixed (char *srcPtrFixed = &this.m_firstChar) { fixed (char *dstPtrFixed = destination) { char *srcPtr = srcPtrFixed + sourceIndex; char *dstPtr = dstPtrFixed + destinationIndex; Buffer.MoveMemory((byte *)dstPtr, (byte *)srcPtr, count * sizeof(char)); } } } } internal unsafe void CopyToByteArray(int sourceIndex, byte[] destination, int destinationIndex, int charCount) { // See also Lightning\Src\VM\COMString.cpp::InternalCopyToByteArray // Called by System.Text.UnicodeEncoding.GetBytes() for little-endian Unicode. if (destination == null) throw new ArgumentNullException("destination"); if (charCount < 0) throw new ArgumentOutOfRangeException("charCount"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (sourceIndex + charCount > this.m_stringLength) throw new ArgumentOutOfRangeException("charCount"); int byteCount = charCount * 2; if (destinationIndex + byteCount > destination.Length) throw new ArgumentOutOfRangeException("destinationLength"); if (charCount > 0) { fixed (byte* dest = &destination[destinationIndex]) fixed (char* src_char0 = &this.m_firstChar) { byte* src_bytes = (byte*)(&src_char0[sourceIndex]); Buffer.MoveMemory(dest, src_bytes, byteCount); } } } // Returns the entire string as an array of characters. //| <include path='docs/doc[@for="String.ToCharArray"]/*' /> public char[] ToCharArray() { return ToCharArray(0,Length); } // Returns a substring of this string as an array of characters. // //| <include path='docs/doc[@for="String.ToCharArray1"]/*' /> public char[] ToCharArray(int startIndex, int length) { // Range check everything. if (startIndex < 0 || startIndex > Length || startIndex > Length - length) throw new ArgumentOutOfRangeException("startIndex", "ArgumentOutOfRange_Index"); if (length < 0) throw new ArgumentOutOfRangeException("length", "ArgumentOutOfRange_Index"); char[] chars = new char[length]; InternalCopyTo(startIndex, chars, 0, length); return chars; } // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then // they will return the same hash code. //| <include path='docs/doc[@for="String.GetHashCode"]/*' /> public unsafe override int GetHashCode() { // See also Lightning\Src\VM\COMString.cpp::GetHashCode fixed (char *charPtrFixed = &this.m_firstChar) { char *charPtr = charPtrFixed; if (charPtr[this.m_stringLength] != 0) { throw new Exception("Bartok string is not null terminated"); } // See also Lightning\Src\UtilCode.h::HashString uint hash = 5381; char c = *charPtr; while (c != 0) { hash = ((hash << 5) + hash) ^ c; charPtr++; c = *charPtr; } return (int) hash; } } // Gets the length of this string //| <include path='docs/doc[@for="String.Length"]/*' /> public int Length { [NoHeapAllocation] get { return InternalLength(); } } ///<internalonly/> internal int ArrayLength { [NoHeapAllocation] get { return (m_arrayLength); } } // Used by StringBuilder internal int Capacity { [NoHeapAllocation] get { return (m_arrayLength - 1); } } // Creates an array of strings by splitting this string at each // occurrence of a separator. The separator is searched for, and if found, // the substring preceding the occurrence is stored as the first element in // the array of strings. We then continue in this manner by searching // the substring that follows the occurrence. On the other hand, if the separator // is not found, the array of strings will contain this instance as its only element. // If the separator is null // whitespace (i.e., Character.IsWhitespace) is used as the separator. // //| <include path='docs/doc[@for="String.Split"]/*' /> public String [] Split(params char [] separator) { return Split(separator, Int32.MaxValue); } //==============================MakeSeparatorList======================== //Args: baseString -- the string to parse for the given list of // separator chars. // Separator -- A string containing all of the split characters. // list -- a pointer to a caller-allocated array of ints for // split char indices. // listLength -- the number of slots allocated in list. //Returns: A list of all of the places within baseString where instances // of characters in Separator occur. //Exceptions: None. //N.B.: This just returns silently if the caller hasn't allocated // enough space for the int list. //======================================================================= // WCHAR * -> char * // int * -> int[] // CHARARRAYREF --> char[] // c->GetNumComponents --> c.Length // STRINGREF --> String // s->GetStringLength --> s.Length // s->GetBuffer --> fixed(&s.m_firstChar) // COMNlsInfo::nativeIsWhiteSpace --> Char.IsWhiteSpace // ArrayContains(char,char* start,char* end) // --> ArrayContains(char, char[] buf) private unsafe static int MakeSeparatorList(String baseString, char[] Separator, int[] list, int listLength) { // From Lightning\Src\VM\COMString.cpp::MakeSeparatorList int i; int foundCount=0; fixed (char *thisChars = &baseString.m_firstChar) { int thisLength = baseString.Length; if (Separator == null || Separator.Length == 0) { //If they passed null or an empty string, //look for whitespace. for (i = 0; i < thisLength && foundCount < listLength; i++) { // was nativeIsWhiteSpace() if (Char.IsWhiteSpace(thisChars[i])) { list[foundCount++]=i; } } } else { //WCHAR *searchChars = (WCHAR *)Separator->GetDataPtr(); int searchLength = Separator.Length; //If they passed in a string of chars, //actually look for those chars. for (i = 0; i < thisLength && foundCount < listLength; i++) { if (ArrayContains(thisChars[i],Separator) >= 0) { list[foundCount++]=i; } } } return foundCount; } } // Creates an array of strings by splitting this string at each // occurrence of a separator. The separator is searched for, and if found, // the substring preceding the occurrence is stored as the first element in // the array of strings. We then continue in this manner by searching // the substring that follows the occurrence. On the other hand, if the separator // is not found, the array of strings will contain this instance as its only element. // If the separator is the empty string (i.e., String.Empty), then // whitespace (i.e., Character.IsWhitespace) is used as the separator. // If there are more than count different strings, the last n-(count-1) // elements are concatenated and added as the last String. // //| <include path='docs/doc[@for="String.Split1"]/*' /> //| <include path='docs/doc[@for="String.Split1"]/*' /> // STRINGREF --> String // PTRARRAYREF --> String[] // p->SetAt(0, v) --> p[0] = v // // LPVOID --> gone // CQuickBytes --> gone // AllocateObjectArray(x,g_pStringClass) --> new String[x] // NewString(&ref, index, size) --> ref.Substring(index, size) public String[] Split(char[] separator, int count) { // See also Lightning\Src\VM\COMString.cpp::Split // This implementation based on COMString int numReplaces; int numActualReplaces; int[] sepList; int currIndex=0; int arrIndex=0; //char *thisChars; int thisLength; int i; String[] splitStrings; String temp; if (count < 0) { throw new ArgumentOutOfRangeException ("count", "ArgumentOutOfRange_Negative"); } //Allocate space and fill an array of ints with a list of everyplace //within our String that a separator character occurs. sepList = new int[this.Length]; numReplaces = MakeSeparatorList(this, separator, sepList, this.Length); //Handle the special case of no replaces. if (0 == numReplaces) { splitStrings = new String[1]; splitStrings[0] = this; return splitStrings; } thisLength = Length; count--; numActualReplaces = (numReplaces<count) ? numReplaces : count; //Allocate space for the new array. //+1 for the string from the end of the last replace to the end //of the String. splitStrings = new String[numActualReplaces+1]; for (i = 0; i < numActualReplaces && currIndex < thisLength; i++) { temp = this.Substring(currIndex, sepList[i]-currIndex); splitStrings[arrIndex++] = temp; currIndex=sepList[i]+1; } //Handle the last string at the end of the array if there is one. if (currIndex < thisLength) { temp = this.Substring(currIndex, thisLength-currIndex); splitStrings[arrIndex] = temp; } else if (arrIndex == numActualReplaces) { //We had a separator character at the end of a string. Rather than just allowing //a null character, we'll replace the last element in the array with an empty string. temp = Empty; splitStrings[arrIndex] = temp; } return splitStrings; } // Returns a substring of this string. // //| <include path='docs/doc[@for="String.Substring"]/*' /> public String Substring(int startIndex) { return this.Substring (startIndex, Length-startIndex); } // Returns a substring of this string. // //| <include path='docs/doc[@for="String.Substring1"]/*' /> public String Substring(int startIndex, int length) { int thisLength = Length; //Bounds Checking. if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", "ArgumentOutOfRange_StartIndex"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", "ArgumentOutOfRange_NegativeLength"); } if (startIndex > thisLength - length) { throw new ArgumentOutOfRangeException("length", "ArgumentOutOfRange_IndexLength"); } String s = FastAllocateString(length); FillSubstring(s, 0, this, startIndex, length); return s; } internal String TrimHelper(char[] trimChars, int trimType) { // See also Lighting\Src\VM\COMString.cpp::TrimHelper int stringLength = this.m_stringLength; int iLeft = 0; int iRight = stringLength - 1; this.TrimHelper(trimChars, trimType, ref iLeft, ref iRight); int newLength = iRight - iLeft + 1; if (newLength == stringLength) { return this; } else if (newLength == 0) { return String.Empty; } else { String result = FastAllocateString(newLength); FillSubstring(result, 0, this, iLeft, newLength); return result; } } private unsafe void TrimHelper(char[] trimChars, int trimType, ref int iLeft, ref int iRight) { fixed (char *charPtr = &this.m_firstChar) { if (trimType == String.TrimHead || trimType == String.TrimBoth) { while (iLeft <= iRight && ArrayContains(charPtr[iLeft], trimChars) >= 0) { iLeft++; } } if (trimType == String.TrimTail || trimType == String.TrimBoth) { while (iRight >= iLeft && ArrayContains(charPtr[iRight], trimChars) >= 0) { iRight--; } } } } private static int ArrayContains(char c, char[] charArray) { int limit = charArray.Length; for (int i = 0; i < limit; i++) { if (charArray[i] == c) { return i; } } return -1; } /// // Creates a new string from the characters in a subarray. The new // string will be created from the characters in <i>value</i> between // <i>startIndex</i> and <i>startIndex</i> + <i>length</i> - 1. // // @param value an array of characters. // @param startIndex the index at which the subarray begins. // @param length the length of the subarray. // // @exception ArgumentException if value is <b>null</b>. // @exception ArgumentException if <i>startIndex</i> or // <i>startIndex</i>+<i>length</i>-1 are not valid indices of // <i>value</i>. // //| <include path='docs/doc[@for="String.String7"]/*' /> public static String StringCTOR(char[] value, int startIndex, int length) { // See also Lightning\Src\VM\COMString.cpp::StringInitCharArray if (value == null) { throw new ArgumentNullException("array value is null"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex is negative"); } if (length < 0) { throw new ArgumentOutOfRangeException("length is negative"); } if (length == 0) { return String.Empty; } else { String result = FastAllocateString(length); FillStringArray(result, 0, value, startIndex, length); return result; } } /// // Creates a new string from the characters in a subarray. The new // string will be created from the characters in <i>value</i>. // // @param value an array of characters. // // @exception ArgumentException if value is <b>null</b>. // //| <include path='docs/doc[@for="String.String5"]/*' /> public static String StringCTOR(char[] value) { // See also Lightning\Src\VM\COMString.cpp::StringInitChars if (value == null) { return String.Empty; } int length = value.Length; if (length == 0) { return String.Empty; } String result = FastAllocateString(length); FillStringArray(result, 0, value, 0, length); return result; } internal static String NewString(String curr,int start,int copyLen, int capacity) { String result = FastAllocateString(capacity); FillSubstring(result, 0, curr, start, copyLen); return result; } //| <include path='docs/doc[@for="String.String6"]/*' /> public static String StringCTOR(char c, int count) { // See also Lightning\Src\VM\COMString.cpp::StringInitCharCount if (count < 0) { throw new ArgumentOutOfRangeException("count is negative"); } if (count == 0) { return String.Empty; } else { String result = FastAllocateString(count); FillStringChar(result, 0, c, count); return result; } } // Removes a string of characters from the ends of this string. //| <include path='docs/doc[@for="String.Trim"]/*' /> public String Trim(params char[] trimChars) { if (null == trimChars || trimChars.Length == 0) { trimChars=CharacterInfo.WhitespaceChars; } return TrimHelper(trimChars,TrimBoth); } // Removes a string of characters from the beginning of this string. //| <include path='docs/doc[@for="String.TrimStart"]/*' /> public String TrimStart(params char[] trimChars) { if (null == trimChars || trimChars.Length == 0) { trimChars=CharacterInfo.WhitespaceChars; } return TrimHelper(trimChars,TrimHead); } // Removes a string of characters from the end of this string. //| <include path='docs/doc[@for="String.TrimEnd"]/*' /> public String TrimEnd(params char[] trimChars) { if (null == trimChars || trimChars.Length == 0) { trimChars=CharacterInfo.WhitespaceChars; } return TrimHelper(trimChars,TrimTail); } unsafe static private String CreateString(sbyte *value, int startIndex, int length, Encoding enc) { if (enc == null) return new String(value, startIndex, length); // default to ANSI if (length < 0) throw new ArgumentOutOfRangeException("length","ArgumentOutOfRange_NeedNonNegNum"); if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex","ArgumentOutOfRange_StartIndex"); } if ((value + startIndex) < value) { // overflow check throw new ArgumentOutOfRangeException("startIndex","ArgumentOutOfRange_PartialWCHAR"); } byte [] b = new byte[length]; if (length > 0) { fixed(byte* pDest = b) { Buffer.MoveMemory(pDest, ((byte*)value)+startIndex, length); } } return enc.GetString(b); } // For ASCIIEncoding::GetString() unsafe static internal String CreateStringFromASCII(byte[] bytes, int startIndex, int length) { Debug.Assert(bytes != null, "need a byte[]."); Debug.Assert(startIndex >= 0 && (startIndex < bytes.Length || bytes.Length == 0), "startIndex >= 0 && startIndex < bytes.Length"); Debug.Assert(length >= 0 && length <= bytes.Length - startIndex, "length >= 0 && length <= bytes.Length - startIndex"); if (length == 0) return String.Empty; String s = FastAllocateString(length); fixed(char* pChars = &s.m_firstChar) { for (int i = 0; i < length; i++) pChars[i] = (char) (bytes[i+startIndex] & 0x7f); } return s; } // For Latin1Encoding::GetString() unsafe static internal String CreateStringFromLatin1(byte[] bytes, int startIndex, int length) { Debug.Assert(bytes != null, "need a byte[]."); Debug.Assert(startIndex >= 0 && (startIndex < bytes.Length || bytes.Length == 0), "startIndex >= 0 && startIndex < bytes.Length"); Debug.Assert(length >= 0 && length <= bytes.Length - startIndex, "length >= 0 && length <= bytes.Length - startIndex"); if (length == 0) return String.Empty; String s = FastAllocateString(length); fixed(char* pChars = &s.m_firstChar) { for (int i = 0; i < length; i++) pChars[i] = (char) (bytes[i+startIndex]); } return s; } private static String FastAllocateString(int stringLength) { return GC.AllocateString(stringLength); } [Inline] internal void InitializeStringLength(int stringLength) { this.m_arrayLength = stringLength+1; this.m_stringLength = stringLength; } private unsafe static void FillString(String dest, int destPos, String src) { fixed (char *srcPtr = &src.m_firstChar) { FillStringCharPtr(dest, destPos, srcPtr, src.m_stringLength); } } private unsafe static void FillStringChecked(String dest, int destPos, String src) { if (!(src.Length <= dest.ArrayLength - destPos)) { throw new IndexOutOfRangeException(); // REVIEW: param? } fixed (char *srcPtr = &src.m_firstChar) { FillStringCharPtr(dest, destPos, srcPtr, src.m_stringLength); } } private unsafe static void FillStringEx(String dest, int destPos, String src,int srcLength) { // ASSERT(srcLength <= dest.ArrayLength - destPos); fixed (char *srcPtr = &src.m_firstChar) { FillStringCharPtr(dest, destPos, srcPtr, srcLength); } } private unsafe static void FillStringChar(String dest, int destPos, char c, int count) { fixed (char *destPtr = &dest.m_firstChar) { char *charPtr = destPtr + destPos; // Set the odd leader char if necessary if (destPos % 2 == 1) { *charPtr = c; charPtr++; count--; } // Set the buffer 2 chars at a time int c2 = (c << 16) | c; int *intPtr = (int *) charPtr; count--; // Prevent overruns from odd lengths while (count > 0) { *intPtr = c2; intPtr++; count -= 2; } // Set the odd trailer char if necessary if (count == 0) { *((char *) intPtr) = c; } } } private unsafe static void FillStringCharPtr(String dest, int destPos, char *srcPtr, int count) { fixed (char *charPtr = &dest.m_firstChar) { char *destPtr = charPtr + destPos; Buffer.MoveMemory((byte *)destPtr, (byte *)srcPtr, count * sizeof(char)); } } private unsafe static void FillStringBytePtr(String dest, int destPos, byte *srcPtr, int count) { fixed (char *charPtr = &dest.m_firstChar) { char *destPtr = charPtr + destPos; for (int i = 0; i < count; i++) { *destPtr++ = (char)*srcPtr++; } } } private unsafe static void FillStringArray(String dest, int stringStart, char[] array, int charStart, int count) { fixed (char *destPtr = &array[charStart]) { FillStringCharPtr(dest, stringStart, destPtr, count); } } private unsafe static void FillSubstring(String dest, int destPos, String src, int startPos, int count) { fixed (char *srcPtr = &src.m_firstChar) { FillStringCharPtr(dest, destPos, srcPtr + startPos, count); } } // // // INSTANCE METHODS // // // Provides a culture-correct string comparison. StrA is compared to StrB // to determine whether it is lexicographically less, equal, or greater, and then returns // either a negative integer, 0, or a positive integer; respectively. // //| <include path='docs/doc[@for="String.Compare"]/*' /> public static int Compare(String strA, String strB) { return CompareInfo.Compare(strA, strB, CompareOptions.None); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase // //| <include path='docs/doc[@for="String.Compare1"]/*' /> public static int Compare(String strA, String strB, bool ignoreCase) { if (ignoreCase) { return CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase); } return CompareInfo.Compare(strA, strB, CompareOptions.None); } // [Bartok]: public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo info) { return Compare(strA, strB, ignoreCase); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. // //| <include path='docs/doc[@for="String.Compare3"]/*' /> public static int Compare(String strA, int indexA, String strB, int indexB, int length) { int lengthA = length; int lengthB = length; if (strA != null) { if (strA.Length - indexA < lengthA) { lengthA = (strA.Length - indexA); } } if (strB != null) { if (strB.Length - indexB < lengthB) { lengthB = (strB.Length - indexB); } } return CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. // //| <include path='docs/doc[@for="String.Compare4"]/*' /> public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { int lengthA = length; int lengthB = length; if (strA != null) { if (strA.Length - indexA < lengthA) { lengthA = (strA.Length - indexA); } } if (strB != null) { if (strB.Length - indexB < lengthB) { lengthB = (strB.Length - indexB); } } if (ignoreCase) { return CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase); } return CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); } // Compares this object to another object, returning an integer that // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 // if this is greater than value. Strings are considered to be // greater than all non-String objects. Note that this means sorted // arrays would contain nulls, other objects, then Strings in that order. // //| <include path='docs/doc[@for="String.CompareTo"]/*' /> public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is String)) { throw new ArgumentException("Arg_MustBeString"); } return String.Compare(this,(String)value); } // Determines the sorting relation of StrB to the current instance. // //| <include path='docs/doc[@for="String.CompareTo1"]/*' /> public int CompareTo(String strB) { if (strB == null) { return 1; } return CompareInfo.Compare(this, strB, 0); } // Compares strA and strB using an ordinal (code-point) comparison. // //| <include path='docs/doc[@for="String.CompareOrdinal"]/*' /> public static int CompareOrdinal(String strA, String strB) { if (strA == null || strB == null) { if ((Object)strA ==(Object)strB) { //they're both null; return 0; } return (strA==null)? -1 : 1; //-1 if A is null, 1 if B is null. } return nativeCompareOrdinal(strA, strB, false); } // Compares strA and strB using an ordinal (code-point) comparison. // //| <include path='docs/doc[@for="String.CompareOrdinal"]/*' /> public static int CompareOrdinal(String strA, String strB, bool ignoreCase) { if (strA == null || strB == null) { if ((Object)strA ==(Object)strB) { //they're both null; return 0; } return (strA==null)? -1 : 1; //-1 if A is null, 1 if B is null. } return nativeCompareOrdinal(strA, strB, ignoreCase); } // Compares strA and strB using an ordinal (code-point) comparison. // //| <include path='docs/doc[@for="String.CompareOrdinal1"]/*' /> public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { if (strA == null || strB == null) { if ((Object)strA ==(Object)strB) { //they're both null; return 0; } return (strA==null)? -1 : 1; //-1 if A is null, 1 if B is null. } return nativeCompareOrdinalEx(strA, indexA, strB, indexB, length); } // Determines whether a specified string is a suffix of the the current instance. // // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // //| <include path='docs/doc[@for="String.EndsWith"]/*' /> public bool EndsWith(String value) { if (null == value) { throw new ArgumentNullException("value"); } int valueLen = value.Length; int thisLen = this.Length; if (valueLen > thisLen) { return false; } return (0==Compare(this, thisLen-valueLen, value, 0, valueLen)); } public bool EndsWith(char value) { int thisLen = this.Length; if (thisLen != 0) { if (this[thisLen - 1] == value) return true; } return false; } // Returns the index of the first occurrence of value in the current instance. // The search starts at startIndex and runs thorough the next count characters. // //| <include path='docs/doc[@for="String.IndexOf"]/*' /> public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } //| <include path='docs/doc[@for="String.IndexOf1"]/*' /> public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } //| <include path='docs/doc[@for="String.IndexOf2"]/*' /> public unsafe int IndexOf(char value, int startIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::IndexOfChar if (startIndex < 0 || startIndex > this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex out of range"); } if (count < 0 || startIndex + count > this.m_stringLength) { throw new ArgumentOutOfRangeException("count out of range"); } fixed (char *charPtr = &this.m_firstChar) { char *cursor = charPtr + startIndex; for (int i = count; i > 0; i--) { if (*cursor == value) { return (startIndex + (count - i)); } cursor++; } } return -1; } // Returns the index of the first occurrence of any character in value in the current instance. // The search starts at startIndex and runs to endIndex-1. [startIndex,endIndex). // //| <include path='docs/doc[@for="String.IndexOfAny1"]/*' /> public int IndexOfAny(char [] anyOf) { return IndexOfAny(anyOf,0, this.Length); } //| <include path='docs/doc[@for="String.IndexOfAny2"]/*' /> public int IndexOfAny(char [] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } //| <include path='docs/doc[@for="String.IndexOfAny3"]/*' /> public unsafe int IndexOfAny(char [] anyOf, int startIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::IndexOfCharArray if (anyOf == null) { throw new ArgumentNullException("anyOf array is null"); } if (startIndex < 0 || startIndex > this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex out of range"); } if (count < 0 || startIndex + count > this.m_stringLength) { throw new ArgumentOutOfRangeException("count out of range"); } fixed (char *charPtr = &this.m_firstChar) { char *cursor = charPtr + startIndex; for (int i = count; i > 0; i--) { if (ArrayContains(*cursor, anyOf) >= 0) { return (startIndex + (count - i)); } cursor++; } } return -1; } // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // the first character of this string, it is case-sensitive and culture-sensitive, // and the default culture is used. // //| <include path='docs/doc[@for="String.IndexOf6"]/*' /> public int IndexOf(String value) { return CompareInfo.IndexOf(this,value); } // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // startIndex, it is case-sensitive and culture-sensitve, and the default culture is used. // //| <include path='docs/doc[@for="String.IndexOf7"]/*' /> public int IndexOf(String value, int startIndex){ return CompareInfo.IndexOf(this,value,startIndex); } // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // startIndex, ends at endIndex and the default culture is used. // //| <include path='docs/doc[@for="String.IndexOf8"]/*' /> public int IndexOf(String value, int startIndex, int count){ if (startIndex + count > this.Length) { throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_Index"); } return CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); } // Returns the index of the last occurrence of value in the current instance. // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //| <include path='docs/doc[@for="String.LastIndexOf"]/*' /> public int LastIndexOf(char value) { return LastIndexOf(value, this.Length-1, this.Length); } //| <include path='docs/doc[@for="String.LastIndexOf1"]/*' /> public int LastIndexOf(char value, int startIndex){ return LastIndexOf(value,startIndex,startIndex + 1); } //| <include path='docs/doc[@for="String.LastIndexOf2"]/*' /> public unsafe int LastIndexOf(char value, int startIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::LastIndexOfChar if (this.m_stringLength == 0) { return -1; } if (startIndex < 0 || startIndex >= this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex out of range"); } if (count < 0 || count - 1 > startIndex) { throw new ArgumentOutOfRangeException("count out of range"); } fixed (char *charPtr = &this.m_firstChar) { char *cursor = charPtr + startIndex; for (int i = count; i > 0; i--) { if (*cursor == value) { return (startIndex - (count - i)); } cursor--; } } return -1; } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //| <include path='docs/doc[@for="String.LastIndexOfAny1"]/*' /> public int LastIndexOfAny(char [] anyOf) { return LastIndexOfAny(anyOf,this.Length-1,this.Length); } //| <include path='docs/doc[@for="String.LastIndexOfAny2"]/*' /> public int LastIndexOfAny(char [] anyOf, int startIndex) { return LastIndexOfAny(anyOf,startIndex,startIndex + 1); } //| <include path='docs/doc[@for="String.LastIndexOfAny3"]/*' /> public unsafe int LastIndexOfAny(char [] anyOf, int startIndex, int count) { // See also Lightning\Src\VM\COMString.cpp::LastIndexOfCharArray if (anyOf == null) { throw new ArgumentNullException("anyOf array is null"); } if (this.m_stringLength == 0) { return -1; } if (startIndex < 0 || startIndex >= this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex out of range"); } if (count < 0 || count - 1 > startIndex) { throw new ArgumentOutOfRangeException("count out of range"); } fixed (char *charPtr = &this.m_firstChar) { char *cursor = charPtr + startIndex; for (int i = count; i > 0; i--) { if (ArrayContains(*cursor, anyOf) >= 0) { return (startIndex - (count - 1)); } cursor--; } } return -1; } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //| <include path='docs/doc[@for="String.LastIndexOf6"]/*' /> public int LastIndexOf(String value) { return LastIndexOf(value, this.Length-1,this.Length); } //| <include path='docs/doc[@for="String.LastIndexOf7"]/*' /> public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } //| <include path='docs/doc[@for="String.LastIndexOf8"]/*' /> public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count", "ArgumentOutOfRange_Count"); } return CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); } // // //| <include path='docs/doc[@for="String.PadLeft"]/*' /> public String PadLeft(int totalWidth) { return PadHelper(totalWidth, ' ', false); } //| <include path='docs/doc[@for="String.PadLeft1"]/*' /> public String PadLeft(int totalWidth, char paddingChar) { return PadHelper(totalWidth, paddingChar, false); } //| <include path='docs/doc[@for="String.PadRight"]/*' /> public String PadRight(int totalWidth) { return PadHelper(totalWidth, ' ', true); } //| <include path='docs/doc[@for="String.PadRight1"]/*' /> public String PadRight(int totalWidth, char paddingChar) { return PadHelper(totalWidth, paddingChar, true); } private String PadHelper(int totalWidth, char paddingChar, bool isRightPadded) { // See also Lightning\Src\VM\COMString.cpp::PadHelper if (totalWidth < 0) { throw new ArgumentOutOfRangeException("totalWidth is negative"); } if (totalWidth <= this.m_stringLength) { return this; } int padCount = totalWidth - this.m_stringLength; String result = FastAllocateString(totalWidth); if (isRightPadded) { FillString(result, 0, this); FillStringChar(result, this.m_stringLength, paddingChar, padCount); } else { FillStringChar(result, 0, paddingChar, padCount); FillString(result, padCount, this); } return result; } // Determines whether a specified string is a prefix of the current instance // //| <include path='docs/doc[@for="String.StartsWith"]/*' /> public bool StartsWith(String value) { if (null == value) { throw new ArgumentNullException("value"); } if (this.Length < value.Length) { return false; } return (0==Compare(this,0, value,0, value.Length)); } // Creates a copy of this string in lower case. //| <include path='docs/doc[@for="String.ToLower"]/*' /> public String ToLower() { return TextInfo.ToLower(this); } // Creates a copy of this string in upper case. //| <include path='docs/doc[@for="String.ToUpper"]/*' /> public String ToUpper() { return TextInfo.ToUpper(this); } // Returns this string. //| <include path='docs/doc[@for="String.ToString"]/*' /> public override String ToString() { return this; } // Method required for the ICloneable interface. // There's no point in cloning a string since they're immutable, so we simply return this. //| <include path='docs/doc[@for="String.Clone"]/*' /> public Object Clone() { return this; } // Trims the whitespace from both ends of the string. Whitespace is defined by // CharacterInfo.WhitespaceChars. // //| <include path='docs/doc[@for="String.Trim1"]/*' /> public String Trim() { return this.Trim(CharacterInfo.WhitespaceChars); } // // //| <include path='docs/doc[@for="String.Insert"]/*' /> public String Insert(int startIndex, String value) { // See also Lightning\Src\VM\COMString.cpp::Insert if (startIndex < 0 || startIndex > this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex out of range"); } if (value == null) { throw new ArgumentNullException("value string is null"); } int newLength = this.m_stringLength + value.m_stringLength; String result = FastAllocateString(newLength); FillSubstring(result, 0, this, 0, startIndex); FillSubstring(result, startIndex, value, 0, value.m_stringLength); FillSubstring(result, startIndex + value.m_stringLength, this, startIndex, this.m_stringLength - startIndex); return result; } internal unsafe void InsertHoleInString(int startIndex, int holeSize) { int tail = this.m_stringLength - startIndex; this.m_stringLength += holeSize; if (tail > 0) { fixed (char *charPtr = &this.m_firstChar) { char *srcPtr = charPtr + startIndex; char *dstPtr = charPtr + holeSize; Buffer.MoveMemory((byte *)dstPtr, (byte *)srcPtr, tail * sizeof(char)); } } } internal unsafe void InsertStringOverwrite(String value, int startIndex, int valueLength) { fixed (char *charPtr = &this.m_firstChar) { char *dstPtr = charPtr + startIndex; fixed (char *srcPtr = &value.m_firstChar) { Buffer.MoveMemory((byte *)dstPtr, (byte *)srcPtr, valueLength * sizeof(char)); } } } // Replaces all instances of oldChar with newChar. // //| <include path='docs/doc[@for="String.Replace"]/*' /> public String Replace(char oldChar, char newChar) { // See also Lightning\Src\VM\COMString.cpp::Replace String result = FastAllocateString(this.m_stringLength); this.Replace(oldChar, newChar, result); return result; } private unsafe void Replace(char oldChar, char newChar, String newString) { fixed (char *srcPtr = &this.m_firstChar) { fixed (char *destPtr = &newString.m_firstChar) { char *srcCursor = srcPtr; char *destCursor = destPtr; for (int i = this.m_stringLength; i > 0; i--) { char c = *srcCursor; *destCursor = (c == oldChar) ? newChar : c; srcCursor++; destCursor++; } } } } // This method contains the same functionality as StringBuilder Replace. The only difference is that // a new String has to be allocated since Strings are immutable //| <include path='docs/doc[@for="String.Replace1"]/*' /> public String Replace(String oldValue, String newValue) { // See also Lightning\Src\VM\COMString.cpp::ReplaceString if (oldValue == null) { throw new ArgumentNullException("oldString is null"); } if (newValue == null) { newValue = String.Empty; } if (oldValue.m_stringLength == 0) { throw new ArgumentException("oldString is empty string"); } int matchIndex = LocalIndexOfString(oldValue, 0); if (matchIndex < 0) { return this; } // Compute a table of where to insert newValue int replaceCount = 0; int[] replacementTable = new int[(this.m_stringLength - matchIndex) / oldValue.m_stringLength + 1]; do { replacementTable[replaceCount] = matchIndex; replaceCount++; matchIndex = LocalIndexOfString(oldValue, matchIndex+oldValue.m_stringLength); } while (matchIndex >= 0); int newLength = this.m_stringLength + replaceCount * (newValue.m_stringLength - oldValue.m_stringLength); String result = FastAllocateString(newLength); int srcIndex = 0; int destIndex = 0; for (int replIndex = 0; replIndex < replaceCount; replIndex++) { int count = replacementTable[replIndex] - srcIndex; FillSubstring(result, destIndex, this, srcIndex, count); srcIndex += count + oldValue.m_stringLength; destIndex += count; FillString(result, destIndex, newValue); destIndex += newValue.m_stringLength; } FillSubstring(result, destIndex, this, srcIndex, this.m_stringLength - srcIndex); return result; } private unsafe int LocalIndexOfString(String pattern, int startPos) { fixed (char *stringPtr = &this.m_firstChar) { fixed (char *patternPtr = &pattern.m_firstChar) { char *stringCharPtr = stringPtr + startPos; int count = this.m_stringLength - pattern.m_stringLength - startPos + 1; for (int index = 0; index < count; index++) { char *stringCursor = stringCharPtr + index; char *patternCursor = patternPtr; int i = pattern.m_stringLength; while (i > 0 && *stringCursor == *patternCursor) { i--; stringCursor++; patternCursor++; } if (i == 0) { return (startPos + index); } } } } return -1; } //| <include path='docs/doc[@for="String.Remove"]/*' /> public String Remove(int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count is negative"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex is negative"); } if (startIndex + count > this.m_stringLength) { throw new ArgumentOutOfRangeException("startIndex+count>Length"); } int newLength = this.m_stringLength - count; String result = FastAllocateString(newLength); FillSubstring(result, 0, this, 0, startIndex); FillSubstring(result, startIndex, this, startIndex + count, newLength - startIndex); return result; } internal unsafe void RemoveRange(int startIndex, int count) { int tail = this.m_stringLength - startIndex; this.m_stringLength -= count; if (tail > 0) { fixed (char *charPtr = &this.m_firstChar) { char *dstPtr = charPtr + startIndex; char *srcPtr = dstPtr + count; Buffer.MoveMemory((byte *)dstPtr, (byte *)srcPtr, tail * sizeof(char)); } } } //| <include path='docs/doc[@for="String.Format"]/*' /> public static String Format(String format, Object arg0) { return Format(format, new Object[] {arg0}); } //| <include path='docs/doc[@for="String.Format1"]/*' /> public static String Format(String format, Object arg0, Object arg1) { return Format(format, new Object[] {arg0, arg1}); } //| <include path='docs/doc[@for="String.Format2"]/*' /> public static String Format(String format, Object arg0, Object arg1, Object arg2) { return Format(format, new Object[] {arg0, arg1, arg2}); } //| <include path='docs/doc[@for="String.Format3"]/*' /> public static String Format(String format, params Object[] args) { if (format == null || args == null) throw new ArgumentNullException((format==null)?"format":"args"); StringBuilder sb = new StringBuilder(format.Length + args.Length * 8); sb.AppendFormat(format,args); return sb.ToString(); } //| <include path='docs/doc[@for="String.Copy"]/*' /> public static String Copy (String str) { if (str == null) { throw new ArgumentNullException("str"); } int length = str.Length; String result = FastAllocateString(length); FillString(result, 0, str); return result; } // Used by StringBuilder to avoid data corruption internal static String InternalCopy (String str) { int length = str.Length; String result = FastAllocateString(length); FillStringEx(result, 0, str, length); // The underlying's String can changed length is StringBuilder return result; } //| <include path='docs/doc[@for="String.Concat"]/*' /> public static String Concat(Object arg0) { if (arg0 == null) { return String.Empty; } return arg0.ToString(); } //| <include path='docs/doc[@for="String.Concat1"]/*' /> public static String Concat(Object arg0, Object arg1) { if (arg0 == null) { arg0 = String.Empty; } if (arg1 == null) { arg1 = String.Empty; } return Concat(arg0.ToString(), arg1.ToString()); } //| <include path='docs/doc[@for="String.Concat2"]/*' /> public static String Concat(Object arg0, Object arg1, Object arg2) { if (arg0 == null) { arg0 = String.Empty; } if (arg1 == null) { arg1 = String.Empty; } if (arg2 == null) { arg2 = String.Empty; } return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString()); } //| <include path='docs/doc[@for="String.Concat4"]/*' /> public static String Concat(params Object[] args) { if (args == null) { throw new ArgumentNullException("args"); } String[] sArgs = new String[args.Length]; int totalLength=0; for (int i = 0; i < args.Length; i++) { object value = args[i]; sArgs[i] = ((value==null)?(String.Empty):(value.ToString())); totalLength += sArgs[i].Length; // check for overflow if (totalLength < 0) { throw new OutOfMemoryException(); } } return ConcatArray(sArgs, totalLength); } //| <include path='docs/doc[@for="String.Concat5"]/*' /> public static String Concat(String str0, String str1) { if (str0 == null) { if (str1 == null) { return String.Empty; } return str1; } if (str1 == null) { return str0; } int str0Length = str0.Length; String result = FastAllocateString(str0Length + str1.Length); FillStringChecked(result, 0, str0); FillStringChecked(result, str0Length, str1); return result; } //| <include path='docs/doc[@for="String.Concat6"]/*' /> public static String Concat(String str0, String str1, String str2) { if (str0 == null && str1 == null && str2 == null) { return String.Empty; } if (str0 == null) { str0 = String.Empty; } if (str1 == null) { str1 = String.Empty; } if (str2 == null) { str2 = String.Empty; } int totalLength = str0.Length + str1.Length + str2.Length; String result = FastAllocateString(totalLength); FillStringChecked(result, 0, str0); FillStringChecked(result, str0.Length, str1); FillStringChecked(result, str0.Length + str1.Length, str2); return result; } //| <include path='docs/doc[@for="String.Concat7"]/*' /> public static String Concat(String str0, String str1, String str2, String str3) { if (str0 == null && str1 == null && str2 == null && str3 == null) { return String.Empty; } if (str0 == null) { str0 = String.Empty; } if (str1 == null) { str1 = String.Empty; } if (str2 == null) { str2 = String.Empty; } if (str3 == null) { str3 = String.Empty; } int totalLength = str0.Length + str1.Length + str2.Length + str3.Length; String result = FastAllocateString(totalLength); FillStringChecked(result, 0, str0); FillStringChecked(result, str0.Length, str1); FillStringChecked(result, str0.Length + str1.Length, str2); FillStringChecked(result, str0.Length + str1.Length + str2.Length, str3); return result; } private static String ConcatArray(String[] values, int totalLength) { String result = FastAllocateString(totalLength); int currPos=0; for (int i = 0; i < values.Length; i++) { Debug.Assert((currPos + values[i].Length <= totalLength), "[String.ConcatArray](currPos + values[i].Length <= totalLength)"); FillStringChecked(result, currPos, values[i]); currPos+=values[i].Length; } return result; } // poor man's varargs for String.Concat: 8 strings public static String Concat(object obj0, object obj1, object obj2, object obj3, string obj4, string obj5, string obj6, string obj7) { String[] strs = new String[8]; strs[0] = obj0.ToString(); strs[1] = obj1.ToString(); strs[2] = obj2.ToString(); strs[3] = obj3.ToString(); strs[4] = obj4.ToString(); strs[5] = obj5.ToString(); strs[6] = obj6.ToString(); strs[7] = obj7.ToString(); return Join(null,strs,0,8); } private static String[] CopyArrayOnNull(String[] values, out int totalLength) { totalLength = 0; String[] outValues = new String[values.Length]; for (int i = 0; i < values.Length; i++) { outValues[i] = ((values[i]==null)?String.Empty:values[i]); totalLength += outValues[i].Length; } return outValues; } //| <include path='docs/doc[@for="String.Concat8"]/*' /> public static String Concat(params String[] values) { int totalLength=0; if (values == null) { throw new ArgumentNullException("values"); } // Always make a copy to prevent changing the array on another thread. String[] internalValues = new String[values.Length]; for (int i = 0; i < values.Length; i++) { string value = values[i]; internalValues[i] = ((value==null)?(String.Empty):(value)); totalLength += internalValues[i].Length; // check for overflow if (totalLength < 0) { throw new OutOfMemoryException(); } } return ConcatArray(internalValues, totalLength); } //| <include path='docs/doc[@for="String.Intern"]/*' /> public static String Intern(String str) { str.CheckHighChars(); if (str == null) { throw new ArgumentNullException("str"); } if (internedStringVector == null) { InitializeInternedTable(); } int code = str.GetHashCode(); lock (internedStringVector) { int[] codeTable= internedStringHashCodes; String[] stringTable = internedStringVector; int tableSize = codeTable.Length; int indexMask = tableSize - 1; int hx = code & indexMask; //Scan up from our initial hash index guess while (true) { // It is guaranteed there are holes in table int tableCode = codeTable[hx]; if (tableCode == code) { String s = stringTable[hx]; if (str.Equals(s)) { return s; } } else if (tableCode == 0 && stringTable[hx] == null) { // We need to insert the string here! int stringLength = str.Length; if (str.m_arrayLength > stringLength + 1) { str = NewString(str, 0, stringLength, stringLength); } internedStringCount++; stringTable[hx] = str; // Set string entry first codeTable[hx] = code; // then set code! if (internedStringCount >= internedStringBound) { RehashInternedStrings(); } return str; } hx++; hx &= indexMask; } } } //| <include path='docs/doc[@for="String.IsInterned"]/*' /> public static String IsInterned(String str) { if (str == null) { throw new ArgumentNullException("str"); } if (internedStringVector == null) { InitializeInternedTable(); } int code = str.GetHashCode(); int[] codeTable; String[] stringTable; do { codeTable = internedStringHashCodes; stringTable = internedStringVector; } while (codeTable.Length != stringTable.Length); int tableSize = codeTable.Length; int indexMask = tableSize - 1; int hx = code & indexMask; // Scan up from our initial hash index guess while (true) { // It is guaranteed there are holes in table int tableCode = codeTable[hx]; if (tableCode == code) { String s = stringTable[hx]; if (str.Equals(s)) { return s; } } else if (tableCode == 0 && stringTable[hx] == null) { return null; } hx++; hx &= indexMask; } } private static void InitializeInternedTable() { lock (typeof(String)) { if (internedStringVector != null) { return; } int tableSize = 128; int constantCount = internedStringConstants.Length; while (tableSize <= constantCount) { tableSize <<= 1; } int indexMask = tableSize - 1; String[] stringTable = new String[tableSize]; int[] codeTable = new int[tableSize]; for (int i = 0; i < constantCount; i++) { String s = internedStringConstants[i]; int code = s.GetHashCode(); int hx = code & indexMask; while (true) { int tableCode = codeTable[hx]; VTable.Assert(tableCode != code || !s.Equals(stringTable[hx]), "Duplicate interned strings!"); if (tableCode == 0 && stringTable[hx] == null) { internedStringCount++; stringTable[hx] = s; codeTable[hx] = code; break; } hx++; hx &= indexMask; } } internedStringBound = tableSize >> 1; internedStringHashCodes = codeTable; internedStringVector = stringTable; } } private static void RehashInternedStrings() { int[] oldCodeTable = internedStringHashCodes; String[] oldStringTable = internedStringVector; int oldSize = oldCodeTable.Length; int oldIndexMask = oldSize - 1; int newSize = oldSize << 1; int newIndexMask = newSize -1; int[] newCodeTable = new int[newSize]; String[] newStringTable = new String[newSize]; for (int i = 0; i < oldSize; i++) { String s = oldStringTable[i]; if (s != null) { int code = oldCodeTable[i]; int hx = code & newIndexMask; while (true) { if (newCodeTable[hx] == 0 && newStringTable[hx] == null) { newStringTable[hx] = s; newCodeTable[hx] = code; break; } hx++; hx &= newIndexMask; } } } internedStringBound = newSize >> 1; internedStringHashCodes = newCodeTable; internedStringVector = newStringTable; } private static int internedStringCount; private static int internedStringBound; private static int[] internedStringHashCodes; private static String[] internedStringVector; private static String[] internedStringConstants; private static readonly bool [] HighCharTable = { false, // 0x00, 0x0 true, // 0x01, . true, // 0x02, . true, // 0x03, . true, // 0x04, . true, // 0x05, . true, // 0x06, . true, // 0x07, . true, // 0x08, . false, // 0x09, false, // 0x0A, false, // 0x0B, . false, // 0x0C, . false, // 0x0D, true, // 0x0E, . true, // 0x0F, . true, // 0x10, . true, // 0x11, . true, // 0x12, . true, // 0x13, . true, // 0x14, . true, // 0x15, . true, // 0x16, . true, // 0x17, . true, // 0x18, . true, // 0x19, . true, // 0x1A, true, // 0x1B, . true, // 0x1C, . true, // 0x1D, . true, // 0x1E, . true, // 0x1F, . false, // 0x20, false, // 0x21, ! false, // 0x22, " false, // 0x23, # false, // 0x24, $ false, // 0x25, % false, // 0x26, & true, // 0x27, ' false, // 0x28, ( false, // 0x29, ) false, // 0x2A * false, // 0x2B, + false, // 0x2C, , true, // 0x2D, - false, // 0x2E, . false, // 0x2F, / false, // 0x30, 0 false, // 0x31, 1 false, // 0x32, 2 false, // 0x33, 3 false, // 0x34, 4 false, // 0x35, 5 false, // 0x36, 6 false, // 0x37, 7 false, // 0x38, 8 false, // 0x39, 9 false, // 0x3A, : false, // 0x3B, ; false, // 0x3C, < false, // 0x3D, = false, // 0x3E, > false, // 0x3F, ? false, // 0x40, @ false, // 0x41, A false, // 0x42, B false, // 0x43, C false, // 0x44, D false, // 0x45, E false, // 0x46, F false, // 0x47, G false, // 0x48, H false, // 0x49, I false, // 0x4A, J false, // 0x4B, K false, // 0x4C, L false, // 0x4D, M false, // 0x4E, N false, // 0x4F, O false, // 0x50, P false, // 0x51, Q false, // 0x52, R false, // 0x53, S false, // 0x54, T false, // 0x55, U false, // 0x56, V false, // 0x57, W false, // 0x58, X false, // 0x59, Y false, // 0x5A, Z false, // 0x5B, [ false, // 0x5C, \ false, // 0x5D, ] false, // 0x5E, ^ false, // 0x5F, _ false, // 0x60, ` false, // 0x61, a false, // 0x62, b false, // 0x63, c false, // 0x64, d false, // 0x65, e false, // 0x66, f false, // 0x67, g false, // 0x68, h false, // 0x69, i false, // 0x6A, j false, // 0x6B, k false, // 0x6C, l false, // 0x6D, m false, // 0x6E, n false, // 0x6F, o false, // 0x70, p false, // 0x71, q false, // 0x72, r false, // 0x73, s false, // 0x74, t false, // 0x75, u false, // 0x76, v false, // 0x77, w false, // 0x78, x false, // 0x79, y false, // 0x7A, z false, // 0x7B, { false, // 0x7C, | false, // 0x7D, } false, // 0x7E, ~ true, // 0x7F,  }; // // IValue implementation // //| <include path='docs/doc[@for="String.GetTypeCode"]/*' /> [NoHeapAllocation] public override TypeCode GetTypeCode() { return TypeCode.String; } // Is this a string that can be compared quickly (that is it has only characters > 0x80 // and not a - or ' internal bool IsFastSort() { return ((StringState & StringState.SpecialSort) != 0); } internal bool IsSlowSort() { return !IsFastSort(); } internal bool IsFastOpsExceptSort() { return ((StringState & StringState.SpecialSort) != 0 || (StringState & StringState.FastOps) != 0); } internal bool IsFastCasing() { return ((StringState & StringState.SpecialSort) != 0 || (StringState & StringState.FastOps) != 0); } internal bool IsFastIndex() { return ((StringState & StringState.SpecialSort) != 0 || (StringState & StringState.FastOps) != 0); } internal bool IsStringStateUndetermined() { return (StringState == StringState.Undetermined); } internal bool HasHighChars() { return (StringState == StringState.HighChars); } /// <summary> /// Get or set the string state for this string. /// </summary> internal unsafe StringState StringState { [NoLoggingForUndo] get { StringState result = MultiUseWord.GetStringState(this); return (StringState)result; } [NoLoggingForUndo] set { MultiUseWord.SetStringState(this, value); } } internal unsafe StringState CheckHighChars() { char c; StringState ss = StringState.FastOps; int length = m_stringLength; fixed(char *charPtr = &this.m_firstChar) { for (int i = 0; i < length; i++) { c = charPtr[i]; if (c >= 0x80) { StringState = StringState.HighChars; return StringState; } else if (HighCharTable[(int)c]) { ss = StringState.SpecialSort; } } } StringState = ss; return StringState; } ///<internalonly/> unsafe internal void SetChar(int index, char value) { #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif //Bounds check and then set the actual bit. if ((UInt32)index >= (UInt32)Length) throw new ArgumentOutOfRangeException("index", "ArgumentOutOfRange_Index"); fixed (char *p = &this.m_firstChar) { // Set the character. p[index] = value; } } #if _DEBUG // Only used in debug build. Insure that the HighChar state information for a string is not set as known [MethodImpl(MethodImplOptions.InternalCall)] private bool ValidModifiableString() { throw new Exception("System.String.ValidModifiableString not implemented in Bartok!"); } #endif ///<internalonly/> unsafe internal void AppendInPlace(char value,int currentLength) { Debug.Assert(currentLength < m_arrayLength, "[String.AppendInPlace(char)currentLength < m_arrayLength"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif fixed (char *p = &this.m_firstChar) { // Append the character. p[currentLength] = value; p[++currentLength] = '\0'; m_stringLength = currentLength; } } ///<internalonly/> unsafe internal void AppendInPlace(char value, int repeatCount, int currentLength) { Debug.Assert(currentLength+repeatCount < m_arrayLength, "[String.AppendInPlace]currentLength+repeatCount < m_arrayLength"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif int newLength = currentLength + repeatCount; fixed (char *p = &this.m_firstChar) { int i; for (i = currentLength; i < newLength; i++) { p[i] = value; } p[i] = '\0'; } this.m_stringLength = newLength; } ///<internalonly/> internal unsafe void AppendInPlace(String value, int currentLength) { Debug.Assert(value!=null, "[String.AppendInPlace]value!=null"); Debug.Assert(value.Length + currentLength < this.m_arrayLength, "[String.AppendInPlace]Length is wrong."); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif FillString(this, currentLength, value); SetLength(currentLength + value.Length); NullTerminate(); } internal void AppendInPlace(String value, int startIndex, int count, int currentLength) { Debug.Assert(value!=null, "[String.AppendInPlace]value!=null"); Debug.Assert(count + currentLength < this.m_arrayLength, "[String.AppendInPlace]count + currentLength < this.m_arrayLength"); Debug.Assert(count>=0, "[String.AppendInPlace]count>=0"); Debug.Assert(startIndex>=0, "[String.AppendInPlace]startIndex>=0"); Debug.Assert(startIndex <= (value.Length - count), "[String.AppendInPlace]startIndex <= (value.Length - count)"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif FillSubstring(this, currentLength, value, startIndex, count); SetLength(currentLength + count); NullTerminate(); } internal unsafe void AppendInPlace(char *value, int count,int currentLength) { Debug.Assert(value!=null, "[String.AppendInPlace]value!=null"); Debug.Assert(count + currentLength < this.m_arrayLength, "[String.AppendInPlace]count + currentLength < this.m_arrayLength"); Debug.Assert(count>=0, "[String.AppendInPlace]count>=0"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif fixed(char *p = &this.m_firstChar) { int i; for (i = 0; i < count; i++) { p[currentLength+i] = value[i]; } } SetLength(currentLength + count); NullTerminate(); } ///<internalonly/> internal unsafe void AppendInPlace(char[] value, int start, int count, int currentLength) { Debug.Assert(value!=null, "[String.AppendInPlace]value!=null"); Debug.Assert(count + currentLength < this.m_arrayLength, "[String.AppendInPlace]Length is wrong."); Debug.Assert(value.Length-count>=start, "[String.AppendInPlace]value.Length-count>=start"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif FillStringArray(this, currentLength, value, start, count); this.m_stringLength = (currentLength + count); this.NullTerminate(); } ///<internalonly/> unsafe internal void ReplaceCharInPlace(char oldChar, char newChar, int startIndex, int count,int currentLength) { Debug.Assert(startIndex>=0, "[String.ReplaceCharInPlace]startIndex>0"); Debug.Assert(startIndex<=currentLength, "[String.ReplaceCharInPlace]startIndex>=Length"); Debug.Assert((startIndex<=currentLength-count), "[String.ReplaceCharInPlace]count>0 && startIndex<=currentLength-count"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif int endIndex = startIndex+count; fixed (char *p = &this.m_firstChar) { for (int i = startIndex; i < endIndex; i++) { if (p[i] == oldChar) { p[i]=newChar; } } } } ///<internalonly/> internal static String GetStringForStringBuilder(String value, int capacity) { Debug.Assert(value!=null, "[String.GetStringForStringBuilder]value!=null"); Debug.Assert(capacity>=value.Length, "[String.GetStringForStringBuilder]capacity>=value.Length"); String newStr = FastAllocateString(capacity); if (value.Length == 0) { newStr.m_stringLength=0; newStr.m_firstChar='\0'; return newStr; } FillString(newStr, 0, value); newStr.m_stringLength = value.m_stringLength; return newStr; } ///<internalonly/> private unsafe void NullTerminate() { fixed(char *p = &this.m_firstChar) { p[m_stringLength] = '\0'; } } ///<internalonly/> unsafe internal void ClearPostNullChar() { int newLength = Length+1; if (newLength < m_arrayLength) { fixed(char *p = &this.m_firstChar) { p[newLength] = '\0'; } } } ///<internalonly/> internal void SetLength(int newLength) { Debug.Assert(newLength <= m_arrayLength, "newLength<=m_arrayLength"); m_stringLength = newLength; } //| <include path='docs/doc[@for="String.GetEnumerator"]/*' /> public CharEnumerator GetEnumerator() { return new CharEnumerator(this); } //| <include path='docs/doc[@for="String.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return new CharEnumerator(this); } // // This is just designed to prevent compiler warnings. // This field is used from native, but we need to prevent the compiler warnings. // #if _DEBUG private void DontTouchThis() { m_arrayLength = 0; m_stringLength = 0; m_firstChar = m_firstChar; } #endif internal unsafe void InternalSetCharNoBoundsCheck(int index, char value) { fixed (char *p = &this.m_firstChar) { p[index] = value; } } #if false // Unused // NOTE: len is not the length in characters, but the length in bytes // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes. internal unsafe static void InternalCopy(String src, IntPtr dest,int len) { if (len == 0) return; fixed(char* charPtr = &src.m_firstChar) { byte* srcPtr = (byte*) charPtr; byte* dstPtr = (byte*) dest.ToPointer(); Buffer.MoveMemory(dstPtr, srcPtr, len); } } // memcopies characters inside a String. internal unsafe static void InternalMemCpy(String src, int srcOffset, String dst, int destOffset, int len) { if (len == 0) return; fixed(char* srcPtr = &src.m_firstChar) { fixed(char* dstPtr = &dst.m_firstChar) { Buffer.MoveMemory((byte*)(dstPtr + destOffset), (byte*)(srcPtr + srcOffset), len); } } } #endif // Copies the source String to the destination byte[] internal unsafe static void InternalCopy(String src, byte[] dest, int stringLength) { if (stringLength == 0) return; int len = stringLength * sizeof(char); Debug.Assert(dest.Length >= len); fixed(char* charPtr = &src.m_firstChar) { fixed(byte* destPtr = &dest[0]) { byte* srcPtr = (byte*) charPtr; Buffer.MoveMemory(destPtr, srcPtr, len); } } } internal unsafe void InsertInPlace(int index, String value, int repeatCount, int currentLength, int requiredLength) { Debug.Assert(requiredLength < m_arrayLength, "[String.InsertString] requiredLength < m_arrayLength"); Debug.Assert(index + value.Length * repeatCount < m_arrayLength, "[String.InsertString] index + value.Length * repeatCount < m_arrayLength"); #if _DEBUG Debug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif //Copy the old characters over to make room and then insert the new characters. fixed(char* srcPtr = &this.m_firstChar) { fixed(char* valuePtr = &value.m_firstChar) { Buffer.MoveMemory((byte*)(srcPtr + index + value.Length * repeatCount), (byte*)(srcPtr + index), (currentLength - index) * sizeof(char)); for (int i = 0; i < repeatCount; i++) { Buffer.MoveMemory((byte*)(srcPtr + index + i * value.Length), (byte*)valuePtr, value.Length * sizeof(char)); } } srcPtr[requiredLength] = '\0'; } this.m_stringLength = requiredLength; } [CLSCompliant(false)] [NoHeapAllocation] public unsafe int LimitedFormatTo(char *buffer, int length) { unchecked { fixed (char *fmtBeg = &m_firstChar) { char *fmtPtr = fmtBeg; char *fmtEnd = fmtBeg + m_stringLength; char *outPtr = buffer; char *outEnd = buffer + length; while (fmtPtr < fmtEnd && outPtr < outEnd) { *outPtr++ = *fmtPtr++; } return (int)(outPtr - buffer); } } } [CLSCompliant(false)] [NoHeapAllocation] public static unsafe int LimitedFormatTo(String format, ArgIterator args, char *buffer, int length) { unchecked { fixed (char *fmtBeg = &format.m_firstChar) { char *fmtPtr = fmtBeg; char *fmtEnd = fmtBeg + format.m_stringLength; char *outPtr = buffer; char *outEnd = buffer + length; while (fmtPtr < fmtEnd && outPtr < outEnd) { if (*fmtPtr == '{') { char * fmtPos = fmtPtr; bool bad = false; fmtPtr++; int ndx = 0; int aln = 0; int wid = 0; char fmt = 'd'; if (*fmtPtr == '{') { *outPtr++ = *fmtPtr++; } else if (*fmtPtr >= '0' && *fmtPtr <= '9') { // {index,alignment:type width} // Get Index while (*fmtPtr >= '0' && *fmtPtr <= '9') { ndx = ndx * 10 + (*fmtPtr++ - '0'); } // Get Alignment if (*fmtPtr == ',') { fmtPtr++; if (*fmtPtr == '-') { // We just ignore left alignment for now. fmtPtr++; } while (*fmtPtr >= '0' && *fmtPtr <= '9') { aln = aln * 10 + (*fmtPtr++ - '0'); } } // Get FormatString if (*fmtPtr == ':') { fmtPtr++; if (*fmtPtr >= 'a' && *fmtPtr <= 'z') { fmt = *fmtPtr++; } else if (*fmtPtr >= 'A' && *fmtPtr <= 'Z') { fmt = (char)(*fmtPtr++ - ('A' + 'a')); } while (*fmtPtr >= '0' && *fmtPtr <= '9') { wid = wid * 10 + (*fmtPtr++ - '0'); } } // Get closing brace. if (*fmtPtr == '}') { fmtPtr++; } else { bad = true; } if (ndx >= args.Length) { bad = true; } if (bad) { for (; fmtPos < fmtPtr; fmtPos++) { if (outPtr < outEnd) { *outPtr++ = *fmtPos; } } } else { // Get the value char cvalue = '\0'; long ivalue = 0; string svalue = null; ulong value = 0; IntPtr pvalue; RuntimeType type; type = args.GetArg(ndx, out pvalue); switch (type.classVtable.structuralView) { case StructuralType.Bool: svalue =*(bool *)pvalue ? "true" : "false"; break; case StructuralType.Char: cvalue = *(char *)pvalue; break; case StructuralType.Int8: ivalue = *(sbyte *)pvalue; break; case StructuralType.Int16: ivalue = *(short *)pvalue; break; case StructuralType.Int32: ivalue = *(int *)pvalue; break; case StructuralType.Int64: ivalue = *(long *)pvalue; break; case StructuralType.UInt8: value = *(byte *)pvalue; break; case StructuralType.UInt16: value = *(ushort *)pvalue; break; case StructuralType.UInt32: value = *(uint *)pvalue; break; case StructuralType.UInt64: value = *(ulong *)pvalue; break; case StructuralType.IntPtr: value = (ulong)*(IntPtr *)pvalue; break; case StructuralType.UIntPtr: value = (ulong)*(UIntPtr *)pvalue; break; case StructuralType.Reference: if (type == typeof(String)) { svalue = Magic.toString( Magic.fromAddress(*(UIntPtr *)pvalue)); } else { svalue = type.Name; } break; default: svalue = "???"; break; } if (cvalue != '\0') { outPtr = AddChar(outPtr, outEnd, *(char *)pvalue, aln); } else if (svalue != null) { outPtr = AddString(outPtr, outEnd, svalue, aln); } else { if (aln < wid) { aln = wid; } if (fmt == 'x') { if (ivalue != 0) { value = (ulong)ivalue; } outPtr = AddNumber(outPtr, outEnd, value, aln, 16, '0', '\0'); } else { char sign = '\0'; if (ivalue < 0) { sign = '-'; value = unchecked((ulong)-ivalue); } else if (ivalue > 0) { value = unchecked((ulong)ivalue); } outPtr = AddNumber(outPtr, outEnd, value, aln, 10, ' ', sign); } } } } } else if (*fmtPtr == '}') { if (outPtr < outEnd) { *outPtr++ = *fmtPtr; } fmtPtr++; } else { if (outPtr < outEnd) { *outPtr++ = *fmtPtr; } fmtPtr++; } } return (int)(outPtr - buffer); } } } [NoHeapAllocation] private static int CountDigits(ulong value, uint valueBase) { int used = 0; do { value /= valueBase; used++; } while (value != 0); return used; } [NoHeapAllocation] private static unsafe char * AddNumber(char *output, char *limit, ulong value, int width, uint valueBase, char fill, char sign) { // Make sure we won't overfill the buffer. if (output >= limit) { return output; } // Figure out how wide the string will be. int used = CountDigits(value, valueBase); // Check for overflow. if (output + used + ((sign != '\0') ? 1 : 0) > limit) { while (width > 0) { *output++ = '#'; width--; } return output; } // Handle sign and space fill. if (sign != '\0' && used < width) { if (fill == ' ') { while (width > used + 1) { *output++ = fill; width--; } fill = '\0'; } *output++ = sign; } // Handle other non-zero fills. if (fill != '\0') { while (width > used) { *output++ = fill; width--; } } // Write the characters into the buffer. char *outp = output + used; do { uint digit = (uint)(value % valueBase); value /= valueBase; if (digit >= 0 && digit <= 9) { *--outp = (char)('0' + digit); } else { *--outp = (char)('a' + (digit - 10)); } } while (value != 0); return output + used; } [NoHeapAllocation] private static unsafe char * AddString(char *output, char *limit, string value, int width) { fixed (char *pwString = &value.m_firstChar) { return AddString(output, limit, pwString, value.m_stringLength, width); } } [NoHeapAllocation] private static unsafe char * AddString(char *output, char *limit, char *pwString, int cwString, int width) { // width < 0: left justified at -width. // width = 0: no specified width. // width > 0: right justified at width. if (width == 0) { width = cwString; } else if (width < 0) { width = -width; for (; width > cwString; width--) { if (output < limit) { *output++ = ' '; } } } while (cwString > 0 && width > 0) { if (output < limit) { *output++ = (char)*pwString++; } width--; cwString--; } for (; width > 0; width--) { if (output < limit) { *output++ = ' '; } } return output; } [NoHeapAllocation] private static unsafe char * AddChar(char *output, char *limit, char value, int width) { // width < 0: left justified at -width. // width = 0: no specified width. // width > 0: right justified at width. if (width == 0) { width = 1; } else if (width < 0) { width = -width; for (; width > 1; width--) { if (output < limit) { *output++ = ' '; } } } if (width > 0) { if (output < limit) { *output++ = (char)value; } width--; } for (; width > 0; width--) { if (output < limit) { *output++ = ' '; } } return output; } } }
0
0.973744
1
0.973744
game-dev
MEDIA
0.201324
game-dev
0.961113
1
0.961113
cBournhonesque/lightyear
17,311
lightyear_replication/src/hierarchy.rs
//! This module is responsible for making sure that parent-children hierarchies are replicated correctly. use crate::prelude::{Replicate, ReplicationBufferSet}; use crate::registry::registry::AppComponentExt; use alloc::vec::Vec; use bevy_app::prelude::*; use bevy_ecs::component::Immutable; use bevy_ecs::entity::MapEntities; use bevy_ecs::prelude::*; use bevy_ecs::reflect::ReflectMapEntities; use bevy_ecs::relationship::Relationship; use bevy_reflect::Reflect; use core::fmt::Debug; use serde::Serialize; use serde::de::DeserializeOwned; use smallvec::SmallVec; use tracing::trace; #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum RelationshipSet { // PreUpdate Receive, // PostUpdate Send, } /// When the `DisableReplicateHierarchy` marker component is added to an entity, we will stop replicating their children. /// /// If the component is added on an entity with `Replicate`, it's children will be replicated using /// the same replication settings as the Parent. /// This is achieved via the marker component `ReplicateLikeParent` added on each child. /// You can remove the `ReplicateLikeParent` component to disable this on a child entity. You can then /// add the replication components on the child to replicate it independently from the parents. #[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)] #[reflect(Component)] pub struct DisableReplicateHierarchy; /// Marker component that indicates that this entity should be replicated similarly to the entity /// contained in the component. /// /// This will be inserted automatically on all children of an entity that has `Replicate` #[derive(Component, Clone, MapEntities, Copy, Reflect, PartialEq, Debug)] #[relationship(relationship_target=ReplicateLikeChildren)] #[reflect(Component, MapEntities, PartialEq, Debug)] pub struct ReplicateLike { #[entities] pub root: Entity, } #[derive(Component, Debug, Reflect)] #[relationship_target(relationship=ReplicateLike, linked_spawn)] #[reflect(Component)] pub struct ReplicateLikeChildren(Vec<Entity>); /// Plugin that helps lightyear propagate replication components through a relationship. /// /// The main idea is this: /// - when `Replicate` is added, we will add a `ReplicateLike` component to all children /// - we skip any child that have `DisableReplicateHierarchy` and its descendants /// - we also skip any child that has `Replicate` and its descendants, because those children /// will want to be replicated according to that child's replication components /// - in the replication send system, either an entity has `Replicate` and we use its replication /// components to determine how we do the sync. Or it could have the `ReplicateLike(root)` component and /// we will use the `root` entity's replication components to determine how the replication will happen. /// Any replication component (`ComponentReplicationOverrides`, etc.) can be added on the child entity to override the /// behaviour only for that child /// - this is mainly useful for replicating visibility components through the hierarchy. Instead of having to /// add all the child entities to a room, or propagating the `NetworkVisibility` through the hierarchy, /// the child entity can just use the root's `NetworkVisibility` value pub struct HierarchySendPlugin<R: Relationship> { marker: core::marker::PhantomData<R>, } impl<R: Relationship> Default for HierarchySendPlugin<R> { fn default() -> Self { Self { marker: core::marker::PhantomData, } } } impl< R: Relationship + Component<Mutability = Immutable> + PartialEq + Clone + Serialize + DeserializeOwned, > Plugin for HierarchySendPlugin<R> { fn build(&self, app: &mut App) { app.register_component::<R>() // need to remember to use the MapEntities implementation that is provided by the Relationship .add_component_map_entities(); // propagate ReplicateLike app.add_observer(Self::propagate_replicate_like_replication_marker_removed); app.add_systems( PostUpdate, Self::propagate_through_hierarchy // update replication components before we actually run the Buffer systems .in_set(ReplicationBufferSet::BeforeBuffer), ); } } impl<R: Relationship> HierarchySendPlugin<R> { /// Propagate certain replication components through the hierarchy. /// - If new children are added, `Replicate` is added, we recursively /// go through the descendants and add `ReplicateLike`, `ChildOfSync`, ... if the child does not have /// `DisableReplicateHierarchy` or `Replicate` already /// - We run this as a system and not an observer because observers cannot handle Children updates very well /// (if we trigger on ChildOf being added, there is no flush between the ChildOf Add hook and the observer /// so the `&Children` query won't be updated (or the component will not exist on the parent yet) fn propagate_through_hierarchy( mut commands: Commands, root_query: Query< (Entity, Option<&ReplicateLike>), ( Or<(With<Replicate>, With<ReplicateLike>)>, Without<DisableReplicateHierarchy>, With<R::RelationshipTarget>, Or<(Changed<R::RelationshipTarget>, Added<Replicate>)>, ), >, children_query: Query<&R::RelationshipTarget>, // exclude those that have `Replicate` (as we don't want to overwrite the `ReplicateLike` component // for their descendants, and we don't want to add `ReplicateLike` on them) child_filter: Query<(), (Without<DisableReplicateHierarchy>, Without<Replicate>)>, ) { root_query .iter() .for_each(|(mut root, maybe_replicate_like)| { // If we are already ReplicateLike another entity, we use it as root if let Some(ReplicateLike { root: new_root }) = maybe_replicate_like { root = *new_root; } // we go through all the descendants (instead of just the children) so that the root is added // and we don't need to search for the root ancestor in the replication systems let mut stack = SmallVec::<[Entity; 8]>::new(); stack.push(root); while let Some(parent) = stack.pop() { for child in children_query.relationship_sources(parent) { if let Ok(()) = child_filter.get(child) { // TODO: should we buffer those inside a SmallVec for batch insert? trace!("Adding ReplicateLike to child {child:?} with root {root:?}."); commands.entity(child).insert(ReplicateLike { root }); stack.push(child); } } } }) } // TODO: but are the children's despawn replicated? or maybe there's no need because the root's despawned // is replicated, and despawns are recursive /// If `Replicate` is removed on an entity that has `Children` /// then we remove `ReplicateLike(Entity)` on all the descendants. /// /// Note that this doesn't happen if the `DisableReplicateHierarchy` is present. /// /// If a child entity already has the `Replicate` component, we ignore it and its descendants. pub(crate) fn propagate_replicate_like_replication_marker_removed( trigger: On<Remove, Replicate>, root_query: Query< (), ( With<R::RelationshipTarget>, Without<DisableReplicateHierarchy>, With<Replicate>, ), >, children_query: Query<&R::RelationshipTarget>, // exclude those that have `Replicate` (as we don't want to remove the `ReplicateLike` component // for their descendants) child_filter: Query<(), (Without<Replicate>, With<ReplicateLike>)>, mut commands: Commands, ) { let root = trigger.entity; // if `DisableReplicateHierarchy` is present, return early since we don't need to propagate `ReplicateLike` let Ok(()) = root_query.get(root) else { return }; let children = children_query.get(root).unwrap(); // we go through all the descendants (instead of just the children) so that the root is added // and we don't need to search for the root ancestor in the replication systems let mut stack = SmallVec::<[Entity; 8]>::new(); stack.push(root); while let Some(parent) = stack.pop() { for child in children_query.relationship_sources(parent) { if let Ok(()) = child_filter.get(child) { stack.push(child); commands.entity(child).try_remove::<ReplicateLike>(); } } } } } #[cfg(test)] mod tests { use super::*; use crate::send::components::Replicate; use alloc::vec; fn setup_hierarchy() -> (App, Entity, Entity, Entity) { let mut app = App::default(); app.add_plugins(HierarchySendPlugin::<ChildOf>::default()); let grandparent = app.world_mut().spawn_empty().id(); let parent = app.world_mut().spawn(ChildOf(grandparent)).id(); let child = app.world_mut().spawn(ChildOf(parent)).id(); (app, grandparent, parent, child) } /// Check that ReplicateLike propagation works correctly when Children gets updated /// on an entity that has ReplicationMarker #[test] fn propagate_replicate_like_children_updated() { let mut app = App::default(); app.add_plugins(HierarchySendPlugin::<ChildOf>::default()); let grandparent = app.world_mut().spawn(Replicate::manual(vec![])).id(); // parent with no ReplicationMarker: ReplicateLike should be propagated let grandchild_1 = app.world_mut().spawn_empty().id(); let child_1 = app.world_mut().spawn_empty().id(); let parent_1 = app.world_mut().spawn_empty().add_child(child_1).id(); // parent with ReplicationMarker: the root ReplicateLike shouldn't be propagated // but the intermediary ReplicateLike should be propagated to child 2a let child_2a = app.world_mut().spawn_empty().id(); let child_2b = app.world_mut().spawn(Replicate::manual(vec![])).id(); let child_2c = app .world_mut() .spawn(ReplicateLike { root: grandparent }) .id(); let parent_2 = app .world_mut() .spawn(Replicate::manual(vec![])) .add_children(&[child_2a, child_2b, child_2c]) .id(); // parent has Replicate::manual(vec![]) and DisableReplicate so ReplicateLike is not propagated let child_3a = app.world_mut().spawn_empty().id(); let child_3b = app .world_mut() .spawn(ReplicateLike { root: grandparent }) .id(); let parent_3 = app .world_mut() .spawn((Replicate::manual(vec![]), DisableReplicateHierarchy)) .add_children(&[child_3a, child_3b]) .id(); // parent has DisableReplicate so ReplicateLike is not propagated let child_4 = app.world_mut().spawn_empty().id(); let parent_4 = app .world_mut() .spawn(DisableReplicateHierarchy) .add_child(child_4) .id(); // add Children to the entity which already has Replicate::manual(vec![]) app.world_mut() .entity_mut(grandparent) .add_children(&[parent_1, parent_2, parent_3, parent_4]); // flush commands app.update(); // Add grandchild which should also get ReplicateLike app.world_mut().entity_mut(parent_1).add_child(grandchild_1); app.update(); assert_eq!( app.world().get::<ReplicateLike>(parent_1).unwrap().root, grandparent ); assert_eq!( app.world().get::<ReplicateLike>(child_1).unwrap().root, grandparent ); assert!(app.world().get::<ReplicateLike>(parent_2).is_none()); assert_eq!( app.world().get::<ReplicateLike>(child_2a).unwrap().root, parent_2 ); assert!(app.world().get::<ReplicateLike>(child_2b).is_none()); // the Parent overrides the ReplicateLike of child_2c assert_eq!( app.world().get::<ReplicateLike>(child_2c).unwrap().root, parent_2 ); assert!(app.world().get::<ReplicateLike>(parent_3).is_none()); assert!(app.world().get::<ReplicateLike>(child_3a).is_none()); // the parent had DisableReplicateHierarchy so the existing ReplicateLike is not overwritten assert_eq!( app.world().get::<ReplicateLike>(child_3b).unwrap().root, grandparent ); // DisableReplicateHierarchy means that ReplicateLike is not propagated and is not added // on the entity itself either assert!(app.world().get::<ReplicateLike>(parent_4).is_none()); assert!(app.world().get::<ReplicateLike>(child_4).is_none()); // The grandchild should replicate like its parent -> grandparent assert_eq!( app.world().get::<ReplicateLike>(grandchild_1).unwrap().root, grandparent ); } /// Check that ReplicateLike propagation works correctly when ReplicationMarker gets added /// on an entity that already has children #[test] fn propagate_replicate_like_replication_marker_added() { let mut app = App::default(); app.add_plugins(HierarchySendPlugin::<ChildOf>::default()); let grandparent = app.world_mut().spawn_empty().id(); // parent with no ReplicationMarker: ReplicateLike should be propagated let child_1 = app.world_mut().spawn_empty().id(); let parent_1 = app.world_mut().spawn_empty().add_child(child_1).id(); // parent with ReplicationMarker: the root ReplicateLike shouldn't be propagated // but the intermediary ReplicateLike should be propagated to child 2a let child_2a = app.world_mut().spawn_empty().id(); let child_2b = app.world_mut().spawn(Replicate::manual(vec![])).id(); let child_2c = app .world_mut() .spawn(ReplicateLike { root: grandparent }) .id(); let parent_2 = app .world_mut() .spawn(Replicate::manual(vec![])) .add_children(&[child_2a, child_2b, child_2c]) .id(); // parent has ReplicationMarker and DisableReplicate so ReplicateLike is not propagated let child_3a = app.world_mut().spawn_empty().id(); let child_3b = app .world_mut() .spawn(ReplicateLike { root: grandparent }) .id(); let parent_3 = app .world_mut() .spawn((Replicate::manual(vec![]), DisableReplicateHierarchy)) .add_children(&[child_3a, child_3b]) .id(); // parent has DisableReplicate so ReplicateLike is not propagated let child_4 = app.world_mut().spawn_empty().id(); let parent_4 = app .world_mut() .spawn(DisableReplicateHierarchy) .add_child(child_4) .id(); app.world_mut() .entity_mut(grandparent) .add_children(&[parent_1, parent_2, parent_3, parent_4]); // add ReplicationMarker to an entity that already has children app.world_mut() .entity_mut(grandparent) .insert(Replicate::manual(vec![])); // flush commands app.update(); assert_eq!( app.world().get::<ReplicateLike>(parent_1).unwrap().root, grandparent ); assert_eq!( app.world().get::<ReplicateLike>(child_1).unwrap().root, grandparent ); assert!(app.world().get::<ReplicateLike>(parent_2).is_none()); assert_eq!( app.world().get::<ReplicateLike>(child_2a).unwrap().root, parent_2 ); assert!(app.world().get::<ReplicateLike>(child_2b).is_none()); // the Parent overrides the ReplicateLike of child_2c assert_eq!( app.world().get::<ReplicateLike>(child_2c).unwrap().root, parent_2 ); assert!(app.world().get::<ReplicateLike>(parent_3).is_none()); assert!(app.world().get::<ReplicateLike>(child_3a).is_none()); // the parent had DisableReplicateHierarchy so the existing ReplicateLike is not overwritten assert_eq!( app.world().get::<ReplicateLike>(child_3b).unwrap().root, grandparent ); // DisableReplicateHierarchy means that ReplicateLike is not propagated and is not added // on the entity itself either assert!(app.world().get::<ReplicateLike>(parent_4).is_none()); assert!(app.world().get::<ReplicateLike>(child_4).is_none()); } }
0
0.860349
1
0.860349
game-dev
MEDIA
0.32176
game-dev
0.781344
1
0.781344
RHAdvance/RhythmHeavenAdvance
8,730
src/scenes/studio_scene.c
#include "global.h" #include "studio.h" #include "graphics/studio/studio_graphics.h" /* STUDIO SCENE */ static u8 sCurrentDrumKit; // Selected Drum Kit ID static u8 sListSongSelItem; // Song Item Index (Total) static s8 sListSongSelLine; // Song Item Index (Screen) static u8 sListOptionSelItem; // Option Item Index static u8 sListDrumSelItem; // Drum Kit Item Index (Total) static u8 sListDrumSelLine; // Drum Kit Item Index (Screen) // Init. Static Variables void studio_scene_init_memory(void) { sCurrentDrumKit = 0; sListSongSelItem = 0; sListSongSelLine = 0; sListOptionSelItem = 0; sListDrumSelItem = 0; sListDrumSelLine = 0; } // Graphics Init. 4 void studio_scene_init_gfx4(void) { gStudio->replayMemoryGraph = create_new_replay_memory_graph(get_current_mem_id(), &D_030046a8->data.drumReplaysAlloc, 128, 5); update_replay_memory_graph_data_bars(gStudio->replayMemoryGraph); show_replay_memory_graph(gStudio->replayMemoryGraph, TRUE); set_pause_beatscript_scene(FALSE); } // Graphics Init. 3 void studio_scene_init_gfx3(void) { s32 task; func_0800c604(0); task = start_new_texture_loader(get_current_mem_id(), studio_buffered_textures); run_func_after_task(task, studio_scene_init_gfx4, 0); } // Graphics Init. 2 void studio_scene_init_gfx2(void) { s32 task; func_0800c604(0); task = func_08002ee0(get_current_mem_id(), studio_gfx_table, 0x3000); run_func_after_task(task, studio_scene_init_gfx3, 0); } // Graphics Init. 1 void studio_scene_init_gfx1(void) { schedule_function_call(get_current_mem_id(), studio_scene_init_gfx2, 0, 2); scene_show_obj_layer(); scene_set_bg_layer_display(BG_LAYER_0, FALSE, 0, 0, 0, 28, 0x4000 | BGCNT_PRIORITY(0)); scene_set_bg_layer_display(BG_LAYER_1, TRUE, 0, 0, 0, 29, 0x4000 | BGCNT_PRIORITY(1)); } // Scene Start void studio_scene_start(void *sVar, s32 dArg) { s32 entryPoint; s16 graph; entryPoint = get_current_scene_trans_var(); func_08007324(FALSE); func_080073f0(); studio_scene_init_gfx1(); init_drumtech(&gStudio->drumTech); studio_song_list_init(0, sListSongSelItem, sListSongSelLine); studio_option_list_init(0, sListOptionSelItem); studio_drum_list_init(0, sListDrumSelItem, sListDrumSelLine); switch (entryPoint) { case 1: gStudio->sceneState = STUDIO_STATE_NAV_DRUM_LIST; listbox_hide_sel_sprite(gStudio->songList); listbox_hide_sel_sprite(gStudio->optionList); listbox_show_sel_sprite(gStudio->drumList); studio_scene_set_current_menu(STUDIO_MENU_DRUM_LIST); break; case 0: default: gStudio->sceneState = STUDIO_STATE_NAV_SONG_LIST; listbox_show_sel_sprite(gStudio->songList); listbox_hide_sel_sprite(gStudio->optionList); listbox_hide_sel_sprite(gStudio->drumList); studio_scene_set_current_menu(STUDIO_MENU_SONG_LIST); break; } gStudio->unused380 = 0; gStudio->unused384 = 0; gStudio->unused388 = 0; gStudio->itemMoveHighlight = sprite_create(gSpriteHandler, anim_studio_item_move_highlight, 0, 64, 64, 0x8864, 0, 0, 0x8000); gStudio->replayDrumKit = STUDIO_DRUM_STANDARD; studio_warning_init(); gStudio->musicPlayer = play_sound(&s_studio_bgm_seqData); graph = sprite_create(gSpriteHandler, anim_studio_graphs_l, 0, 77, 66, 0x4800, 1, 0, 0); sprite_set_origin_x_y(gSpriteHandler, graph, &D_03004b10.BG_OFS[BG_LAYER_1].x, &D_03004b10.BG_OFS[BG_LAYER_1].y); graph = sprite_create(gSpriteHandler, anim_studio_graph_r, 0, 320, 130, 0x4800, 1, 0, 0); sprite_set_origin_x_y(gSpriteHandler, graph, &D_03004b10.BG_OFS[BG_LAYER_1].x, &D_03004b10.BG_OFS[BG_LAYER_1].y); gStudio->inputsEnabled = FALSE; gStudio->replaySeq = mem_heap_alloc_id(get_current_mem_id(), 0x3800); } // Get Currently Selected Drum Kit (Index) s32 studio_get_current_kit(void) { return sCurrentDrumKit; } // Set Currently Selected Drum Kit (Index) void studio_set_current_kit(s32 id) { sCurrentDrumKit = id; } // Set Currently Selected Song (Index) void studio_set_current_song(s32 id, s32 line) { sListSongSelItem = id; sListSongSelLine = line; } // Save List Positions void studio_remember_list_positions(void) { s32 songItem, songLine; songItem = listbox_get_sel_item(gStudio->songList); songLine = listbox_get_sel_line(gStudio->songList); studio_set_current_song(songItem, songLine); sListOptionSelItem = listbox_get_sel_item(gStudio->optionList); sListDrumSelItem = listbox_get_sel_item(gStudio->drumList); sListDrumSelLine = listbox_get_sel_line(gStudio->drumList); } // Scene Update (Paused) void studio_scene_paused(void *sVar, s32 dArg) { } // Update Menu Scrolling void studio_scene_update_panning(void) { u32 busy = FALSE; s16 x; if (listbox_is_busy(gStudio->songList)) { busy = TRUE; } if (listbox_is_busy(gStudio->optionList)) { busy = TRUE; } if (listbox_is_busy(gStudio->drumList)) { busy = TRUE; } if (!busy) { gStudio->panProgress = FIXED_POINT_MUL(gStudio->panProgress, 200); } x = math_lerp(gStudio->panStartX, gStudio->panTargetX, INT_TO_FIXED(1.0) - gStudio->panProgress, INT_TO_FIXED(1.0)); D_03004b10.BG_OFS[BG_LAYER_1].x = x; listbox_offset_x_y(gStudio->songList, x, 0); listbox_offset_x_y(gStudio->drumList, x, 0); listbox_offset_x_y(gStudio->optionList, x, 0); } // Set Current Menu void studio_scene_set_current_menu(u32 menu) { gStudio->panTargetX = studio_menu_x_ofs[menu]; gStudio->panStartX = studio_menu_x_ofs[menu]; gStudio->panProgress = 0; gStudio->currentMenu = menu; } // Pan Screen to Menu void studio_scene_pan_to_menu(u32 menu) { gStudio->panStartX = gStudio->panTargetX; gStudio->panTargetX = studio_menu_x_ofs[menu]; gStudio->panProgress = 0x100; gStudio->currentMenu = menu; } // Start Music Playback void studio_scene_play_music(s32 item) { struct StudioSongData *data; u32 length; data = &D_030046a8->data.studioSongs[item]; if (data->unk3 & 1) { dma3_fill(0, gStudio->replaySeq, 0x3800, 0x20, 0x200); set_studio_drummer_mode(STUDIO_DRUMMER_MODE_PLAYBACK); length = get_saved_replay_data(&D_030046a8->data.drumReplaysAlloc, data->replayID, gStudio->replaySeq); key_rec_set_mode(3, 0x3FF, gStudio->replaySeq, length / sizeof(u16)); gStudio->replayDrumKit = data->drumKitID; } else { set_studio_drummer_mode(STUDIO_DRUMMER_MODE_LISTEN); } gStudio->drumScript = studio_song_table[data->songID].script; func_0801d978(); func_0801d968(script_scene_studio_start_song); } // Reset Music Playback void studio_scene_clear_music(void) { scene_stop_music(); func_0801d978(); func_0801d968(script_scene_studio_idle); key_rec_set_mode(0, 0x3FF, 0, 0); } // Update Nothing void studio_scene_update_stub(void) { } // Scene Update void studio_scene_update(void *sVar, s32 dArg) { switch (gStudio->sceneState) { case STUDIO_STATE_NAV_SONG_LIST: studio_song_list_update(); break; case STUDIO_STATE_EDIT_VIA_SONG_LIST: studio_song_list_update_w_selection(); break; case STUDIO_STATE_NAV_OPTION_LIST: studio_option_list_update(); break; case STUDIO_STATE_EDIT_VIA_OPTION_LIST: studio_option_list_update_w_selection(); break; case STUDIO_STATE_NAV_DRUM_LIST: studio_drum_list_update(); break; case STUDIO_STATE_WARNING_DISPLAY: studio_warning_update(); break; } studio_scene_update_panning(); studio_scene_update_stub(); update_listbox(gStudio->songList); update_listbox(gStudio->optionList); update_listbox(gStudio->drumList); func_08029cac(gStudio->replayDrumKit, D_030046b8, D_03005378, D_030046b4); update_drumtech(); } // Check if Scene Can Receive Inputs u32 studio_scene_inputs_enabled(void) { u32 busy; if (!gStudio->inputsEnabled) { return FALSE; } busy = FALSE; if (listbox_is_busy(gStudio->songList)) { busy = TRUE; } if (listbox_is_busy(gStudio->optionList)) { busy = TRUE; } if (listbox_is_busy(gStudio->drumList)) { busy = TRUE; } if (busy) { return FALSE; } return TRUE; } // Scene Stop void studio_scene_stop(void *sVar, s32 dArg) { func_08008628(); func_08004058(); studio_remember_list_positions(); scene_flush_save_buffer(); }
0
0.884153
1
0.884153
game-dev
MEDIA
0.656569
game-dev
0.685098
1
0.685098
mastercomfig/tf2-patches-old
7,192
src/game/server/tf/bot/tf_bot_squad.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // tf_bot_squad.h // Small groups of TFBot, managed as a unit // Michael Booth, November 2009 #include "cbase.h" #include "tf_bot.h" #include "tf_bot_squad.h" //---------------------------------------------------------------------- CTFBotSquad::CTFBotSquad( void ) { m_leader = NULL; m_formationSize = -1.0f; m_bShouldPreserveSquad = false; } //---------------------------------------------------------------------- void CTFBotSquad::Join( CTFBot *bot ) { // first member is the leader if ( m_roster.Count() == 0 ) { m_leader = bot; } else if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() ) { bot->SetFlagTarget( NULL ); } m_roster.AddToTail( bot ); } //---------------------------------------------------------------------- void CTFBotSquad::Leave( CTFBot *bot ) { m_roster.FindAndRemove( bot ); if ( bot == m_leader.Get() ) { m_leader = NULL; // pick the next living leader that's left in the squad if ( m_bShouldPreserveSquad ) { CUtlVector< CTFBot* > members; CollectMembers( &members ); if ( members.Count() ) { m_leader = members[0]; } } } else if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() ) { AssertMsg( !bot->HasFlagTaget(), "Squad member shouldn't have a flag target. Always follow the leader." ); CCaptureFlag *pFlag = bot->GetFlagToFetch(); if ( pFlag ) { bot->SetFlagTarget( pFlag ); } } if ( GetMemberCount() == 0 ) { DisbandAndDeleteSquad(); } } //---------------------------------------------------------------------- INextBotEventResponder *CTFBotSquad::FirstContainedResponder( void ) const { return m_roster.Count() ? m_roster[0] : NULL; } //---------------------------------------------------------------------- INextBotEventResponder *CTFBotSquad::NextContainedResponder( INextBotEventResponder *current ) const { CTFBot *currentBot = (CTFBot *)current; int i = m_roster.Find( currentBot ); if ( i == m_roster.InvalidIndex() ) return NULL; if ( ++i >= m_roster.Count() ) return NULL; return (CTFBot *)m_roster[i]; } //---------------------------------------------------------------------- CTFBot *CTFBotSquad::GetLeader( void ) const { return m_leader; } //---------------------------------------------------------------------- void CTFBotSquad::CollectMembers( CUtlVector< CTFBot * > *memberVector ) const { for( int i=0; i<m_roster.Count(); ++i ) { if ( m_roster[i] != NULL && m_roster[i]->IsAlive() ) { memberVector->AddToTail( m_roster[i] ); } } } //---------------------------------------------------------------------- CTFBotSquad::Iterator CTFBotSquad::GetFirstMember( void ) const { // find first non-NULL member for( int i=0; i<m_roster.Count(); ++i ) if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) return Iterator( m_roster[i], i ); return InvalidIterator(); } //---------------------------------------------------------------------- CTFBotSquad::Iterator CTFBotSquad::GetNextMember( const Iterator &it ) const { // find next non-NULL member for( int i=it.m_index+1; i<m_roster.Count(); ++i ) if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) return Iterator( m_roster[i], i ); return InvalidIterator(); } //---------------------------------------------------------------------- int CTFBotSquad::GetMemberCount( void ) const { // count the non-NULL members int count = 0; for( int i=0; i<m_roster.Count(); ++i ) if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) ++count; return count; } //---------------------------------------------------------------------- // Return the speed of the slowest member of the squad float CTFBotSquad::GetSlowestMemberSpeed( bool includeLeader ) const { float speed = FLT_MAX; int i = includeLeader ? 0 : 1; for( ; i<m_roster.Count(); ++i ) { if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) { float memberSpeed = m_roster[i]->MaxSpeed(); if ( memberSpeed < speed ) { speed = memberSpeed; } } } return speed; } //---------------------------------------------------------------------- // Return the speed of the slowest member of the squad, // considering their ideal class speed. float CTFBotSquad::GetSlowestMemberIdealSpeed( bool includeLeader ) const { float speed = FLT_MAX; int i = includeLeader ? 0 : 1; for( ; i<m_roster.Count(); ++i ) { if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) { float memberSpeed = m_roster[i]->GetPlayerClass()->GetMaxSpeed(); if ( memberSpeed < speed ) { speed = memberSpeed; } } } return speed; } //---------------------------------------------------------------------- // Return the maximum formation error of the squad's memebers. float CTFBotSquad::GetMaxSquadFormationError( void ) const { float maxError = 0.0f; // skip the leader since he's what the formation forms around for( int i=1; i<m_roster.Count(); ++i ) { if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) { float error = m_roster[i]->GetSquadFormationError(); if ( error > maxError ) { maxError = error; } } } return maxError; } //---------------------------------------------------------------------- // Return true if the squad leader needs to wait for members to catch up, ignoring those who have broken ranks bool CTFBotSquad::ShouldSquadLeaderWaitForFormation( void ) const { // skip the leader since he's what the formation forms around for( int i=1; i<m_roster.Count(); ++i ) { // the squad leader should wait if any member is out of position, but not yet broken ranks if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) { if ( m_roster[i]->GetSquadFormationError() >= 1.0f && !m_roster[i]->HasBrokenFormation() && !m_roster[i]->GetLocomotionInterface()->IsStuck() && !m_roster[i]->IsPlayerClass( TF_CLASS_MEDIC ) ) // Medics do their own thing { // wait for me! return true; } } } return false; } //---------------------------------------------------------------------- // Return true if the squad is in formation (everyone is in or nearly in their desired positions) bool CTFBotSquad::IsInFormation( void ) const { // skip the leader since he's what the formation forms around for( int i=1; i<m_roster.Count(); ++i ) { if ( m_roster[i].Get() != NULL && m_roster[i]->IsAlive() ) { if ( m_roster[i]->HasBrokenFormation() || m_roster[i]->GetLocomotionInterface()->IsStuck() || m_roster[i]->IsPlayerClass( TF_CLASS_MEDIC ) ) // Medics do their own thing { // I'm not "in formation" continue; } if ( m_roster[i]->GetSquadFormationError() > 0.75f ) { // I'm not in position yet return false; } } } return true; } //---------------------------------------------------------------------- // Tell all members to leave the squad and then delete itself void CTFBotSquad::DisbandAndDeleteSquad( void ) { // Tell each member of the squad to remove this reference for( int i=0; i < m_roster.Count(); ++i ) { if ( m_roster[i].Get() != NULL ) { m_roster[i]->DeleteSquad(); } } delete this; }
0
0.886509
1
0.886509
game-dev
MEDIA
0.861624
game-dev
0.989244
1
0.989244
Up-Mods/OkZoomer
1,291
mod_common/src/main/java/io/github/ennuil/ok_zoomer/mixin/common/config/EditBoxMixin.java
package io.github.ennuil.ok_zoomer.mixin.common.config; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import io.github.ennuil.ok_zoomer.config.screen.components.LabelledEditBox; import net.minecraft.client.gui.components.EditBox; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @Mixin(EditBox.class) public abstract class EditBoxMixin { @ModifyExpressionValue( method = "renderWidget", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/gui/components/EditBox;getY()I" ) ) private int modifyGetY(int original) { return (EditBox) (Object) this instanceof LabelledEditBox ? original + 12 : original; } @ModifyExpressionValue( method = "renderWidget", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/gui/components/EditBox;getHeight()I" ) ) private int modifyHeight(int original) { return (EditBox) (Object) this instanceof LabelledEditBox ? original - 12 : original; } @ModifyExpressionValue( method = "updateTextPosition", at = @At( value = "FIELD", target = "Lnet/minecraft/client/gui/components/EditBox;height:I" ) ) private int modifyHeight2(int original) { return (EditBox) (Object) this instanceof LabelledEditBox ? original + 12 : original; } }
0
0.653881
1
0.653881
game-dev
MEDIA
0.677981
game-dev
0.845867
1
0.845867
Isidorsson/Eluna-scripts
18,955
AIO Scripts/GameMasterSystem/GameMasterUI/Client/03_Systems/04_Teleport/GMClient_TeleportContextMenu.lua
local AIO = AIO or require("AIO") if AIO.AddAddon() then return -- Exit if on server end -- Get module references local GameMasterSystem = _G.GameMasterSystem if not GameMasterSystem then print("[ERROR] GameMasterSystem namespace not found! Check load order.") return end -- Create Teleport namespace if it doesn't exist (in case this loads before TeleportList) GameMasterSystem.Teleport = GameMasterSystem.Teleport or {} local Teleport = GameMasterSystem.Teleport local GMConfig = _G.GMConfig local GMUtils = _G.GMUtils local PlayerInventory = _G.PlayerInventory -- Teleport Context Menu Module local TeleportContextMenu = {} Teleport.ContextMenu = TeleportContextMenu -- Store reference to current location local currentLocation = nil local contextMenuFrame = nil -- Create the context menu function Teleport.ShowContextMenu(anchor, location) currentLocation = location -- Close any existing context menu if contextMenuFrame and contextMenuFrame:IsShown() then contextMenuFrame:Hide() end -- Build menu items local menuItems = TeleportContextMenu.BuildMenuItems(location) -- Show the menu using the styled easy menu system if ShowStyledEasyMenu then ShowStyledEasyMenu(menuItems, "cursor") else -- Fallback to creating custom menu TeleportContextMenu.CreateCustomMenu(menuItems, anchor) end end -- Build context menu items function TeleportContextMenu.BuildMenuItems(location) local menuItems = {} -- Teleport submenu table.insert(menuItems, { text = "Teleport", hasArrow = true, notCheckable = true, menuList = { { text = "Teleport Here", notCheckable = true, func = function() Teleport.TeleportToLocation(location) CloseDropDownMenus() end }, { text = "Teleport Player...", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowTeleportPlayerDialog(location) end }, { text = "Port Party Here", notCheckable = true, func = function() AIO.Handle("GameMasterSystem", "TeleportPartyToLocation", location.id) CloseDropDownMenus() end }, { text = "", disabled = true, notCheckable = true }, -- Separator { text = "Summon Player to Here", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowSummonPlayerDialog(location) end } } }) -- Manage submenu table.insert(menuItems, { text = "Manage", hasArrow = true, notCheckable = true, menuList = { { text = "Edit Location...", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowEditDialog(location) end }, { text = "Duplicate...", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowDuplicateDialog(location) end }, { text = "|cffff0000Delete|r", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowDeleteConfirmation(location) end }, { text = "", disabled = true, notCheckable = true }, -- Separator { text = "Set as Favorite", notCheckable = true, func = function() AIO.Handle("GameMasterSystem", "SetTeleportFavorite", location.id) CloseDropDownMenus() end }, { text = "Add to Quick Access", notCheckable = true, func = function() AIO.Handle("GameMasterSystem", "AddTeleportQuickAccess", location.id) CloseDropDownMenus() end } } }) -- Copy submenu table.insert(menuItems, { text = "Copy", hasArrow = true, notCheckable = true, menuList = { { text = "Copy Coordinates", notCheckable = true, func = function() TeleportContextMenu.CopyCoordinates(location) CloseDropDownMenus() end }, { text = "Copy Teleport Command", notCheckable = true, func = function() TeleportContextMenu.CopyCommand(location) CloseDropDownMenus() end }, { text = "Copy GPS Command", notCheckable = true, func = function() TeleportContextMenu.CopyGPSCommand(location) CloseDropDownMenus() end }, { text = "", disabled = true, notCheckable = true }, -- Separator { text = "Export as SQL", notCheckable = true, func = function() TeleportContextMenu.ExportAsSQL(location) CloseDropDownMenus() end } } }) -- Advanced submenu table.insert(menuItems, { text = "Advanced", hasArrow = true, notCheckable = true, menuList = { { text = "View Details", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowDetailsDialog(location) end }, { text = "Test Location (10 sec)", notCheckable = true, func = function() AIO.Handle("GameMasterSystem", "TestTeleportLocation", location.id) CloseDropDownMenus() end }, { text = "Set as Home", notCheckable = true, func = function() AIO.Handle("GameMasterSystem", "SetHomeLocation", location.id) CloseDropDownMenus() end }, { text = "", disabled = true, notCheckable = true }, -- Separator { text = "Add Current Position", notCheckable = true, func = function() CloseDropDownMenus() TeleportContextMenu.ShowAddCurrentPositionDialog() end } } }) -- Separator table.insert(menuItems, { text = "", disabled = true, notCheckable = true }) -- Cancel table.insert(menuItems, { text = "Cancel", notCheckable = true, func = function() CloseDropDownMenus() end }) return menuItems end -- Copy coordinates to clipboard function TeleportContextMenu.CopyCoordinates(location) local coords = string.format("%.2f, %.2f, %.2f", location.position_x, location.position_y, location.position_z) -- Create temporary EditBox for copying local editBox = CreateFrame("EditBox") editBox:SetText(coords) editBox:HighlightText() editBox:SetScript("OnEscapePressed", function(self) self:ClearFocus() self:Hide() end) editBox:Show() editBox:SetFocus() print("|cff00ff00Coordinates copied:|r " .. coords) print("Press Ctrl+C to copy to clipboard") end -- Copy teleport command function TeleportContextMenu.CopyCommand(location) local command = ".tele " .. location.name local editBox = CreateFrame("EditBox") editBox:SetText(command) editBox:HighlightText() editBox:SetScript("OnEscapePressed", function(self) self:ClearFocus() self:Hide() end) editBox:Show() editBox:SetFocus() print("|cff00ff00Command copied:|r " .. command) print("Press Ctrl+C to copy to clipboard") end -- Copy GPS command function TeleportContextMenu.CopyGPSCommand(location) local command = string.format(".gps %.2f %.2f %.2f %d", location.position_x, location.position_y, location.position_z, location.map) local editBox = CreateFrame("EditBox") editBox:SetText(command) editBox:HighlightText() editBox:SetScript("OnEscapePressed", function(self) self:ClearFocus() self:Hide() end) editBox:Show() editBox:SetFocus() print("|cff00ff00GPS command copied:|r " .. command) print("Press Ctrl+C to copy to clipboard") end -- Export location as SQL function TeleportContextMenu.ExportAsSQL(location) local sql = string.format( "INSERT INTO `game_tele` (`position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (%.6f, %.6f, %.6f, %.6f, %d, '%s');", location.position_x, location.position_y, location.position_z, location.orientation, location.map, location.name:gsub("'", "''") ) local editBox = CreateFrame("EditBox") editBox:SetText(sql) editBox:HighlightText() editBox:SetScript("OnEscapePressed", function(self) self:ClearFocus() self:Hide() end) editBox:Show() editBox:SetFocus() print("|cff00ff00SQL exported:|r Press Ctrl+C to copy") end -- Show edit dialog function TeleportContextMenu.ShowEditDialog(location) if PlayerInventory and PlayerInventory.CreateInputDialog then local dialog = PlayerInventory.CreateInputDialog({ title = "Edit Teleport Location", message = "Enter new name for the location:", placeholder = location.name, width = 400, height = 180, buttons = { { text = "Save", onClick = function(frame, newName) if newName and newName ~= "" then AIO.Handle("GameMasterSystem", "UpdateTeleportLocation", location.id, newName) frame:Hide() -- Refresh the list if Teleport.RequestTeleportData then Teleport.RequestTeleportData() end end end }, { text = "Cancel", onClick = function(frame) frame:Hide() end } } }) dialog:Show() end end -- Show duplicate dialog function TeleportContextMenu.ShowDuplicateDialog(location) if PlayerInventory and PlayerInventory.CreateInputDialog then local dialog = PlayerInventory.CreateInputDialog({ title = "Duplicate Teleport Location", message = "Enter name for the duplicate:", placeholder = location.name .. " (Copy)", width = 400, height = 180, buttons = { { text = "Create", onClick = function(frame, newName) if newName and newName ~= "" then AIO.Handle("GameMasterSystem", "DuplicateTeleportLocation", location.id, newName) frame:Hide() -- Refresh the list if Teleport.RequestTeleportData then Teleport.RequestTeleportData() end end end }, { text = "Cancel", onClick = function(frame) frame:Hide() end } } }) dialog:Show() end end -- Show delete confirmation function TeleportContextMenu.ShowDeleteConfirmation(location) StaticPopupDialogs["CONFIRM_DELETE_TELEPORT"] = { text = "Are you sure you want to delete the teleport location:\n\n|cffff0000" .. location.name .. "|r\n\nThis action cannot be undone!", button1 = "Delete", button2 = "Cancel", timeout = 0, whileDead = true, hideOnEscape = true, OnAccept = function() AIO.Handle("GameMasterSystem", "DeleteTeleportLocation", location.id) -- Refresh the list if Teleport.RequestTeleportData then Teleport.RequestTeleportData() end end, } StaticPopup_Show("CONFIRM_DELETE_TELEPORT") end -- Show teleport player dialog function TeleportContextMenu.ShowTeleportPlayerDialog(location) if PlayerInventory and PlayerInventory.CreateInputDialog then local dialog = PlayerInventory.CreateInputDialog({ title = "Teleport Player to " .. location.name, message = "Enter player name:", placeholder = "Player name", width = 400, height = 180, buttons = { { text = "Teleport", onClick = function(frame, playerName) if playerName and playerName ~= "" then AIO.Handle("GameMasterSystem", "TeleportPlayerToLocation", playerName, location.id) frame:Hide() end end }, { text = "Cancel", onClick = function(frame) frame:Hide() end } } }) dialog:Show() end end -- Show summon player dialog function TeleportContextMenu.ShowSummonPlayerDialog(location) if PlayerInventory and PlayerInventory.CreateInputDialog then local dialog = PlayerInventory.CreateInputDialog({ title = "Summon Player to " .. location.name, message = "Enter player name to summon:", placeholder = "Player name", width = 400, height = 180, buttons = { { text = "Summon", onClick = function(frame, playerName) if playerName and playerName ~= "" then AIO.Handle("GameMasterSystem", "SummonPlayerToLocation", playerName, location.id) frame:Hide() end end }, { text = "Cancel", onClick = function(frame) frame:Hide() end } } }) dialog:Show() end end -- Show details dialog function TeleportContextMenu.ShowDetailsDialog(location) -- Create a styled frame for details local dialog = CreateStyledFrame(UIParent, UISTYLE_COLORS.DarkGrey) dialog:SetSize(400, 300) dialog:SetPoint("CENTER") dialog:SetFrameStrata("DIALOG") dialog:SetFrameLevel(100) -- Make it movable dialog:SetMovable(true) dialog:EnableMouse(true) dialog:RegisterForDrag("LeftButton") dialog:SetScript("OnDragStart", dialog.StartMoving) dialog:SetScript("OnDragStop", dialog.StopMovingOrSizing) -- Title local title = dialog:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge") title:SetPoint("TOP", 0, -15) title:SetText("Location Details") title:SetTextColor(UISTYLE_COLORS.Blue[1], UISTYLE_COLORS.Blue[2], UISTYLE_COLORS.Blue[3]) -- Close button local closeBtn = CreateStyledButton(dialog, "X", 24, 24) closeBtn:SetPoint("TOPRIGHT", -5, -5) closeBtn:SetScript("OnClick", function() dialog:Hide() end) -- Details text local details = dialog:CreateFontString(nil, "OVERLAY", "GameFontNormal") details:SetPoint("TOPLEFT", 20, -50) details:SetJustifyH("LEFT") details:SetWidth(360) local detailText = string.format( "|cff00ff00Name:|r %s\n\n" .. "|cff00ff00ID:|r %d\n" .. "|cff00ff00Map:|r %d\n\n" .. "|cff00ff00Coordinates:|r\n" .. " X: %.6f\n" .. " Y: %.6f\n" .. " Z: %.6f\n" .. " O: %.6f", location.name, location.id, location.map, location.position_x, location.position_y, location.position_z, location.orientation ) details:SetText(detailText) -- OK button local okBtn = CreateStyledButton(dialog, "OK", 80, 30) okBtn:SetPoint("BOTTOM", 0, 20) okBtn:SetScript("OnClick", function() dialog:Hide() end) dialog:Show() end -- Show add current position dialog function TeleportContextMenu.ShowAddCurrentPositionDialog() if PlayerInventory and PlayerInventory.CreateInputDialog then local dialog = PlayerInventory.CreateInputDialog({ title = "Add Current Position", message = "Enter name for the new teleport location:", placeholder = "Location name", width = 400, height = 180, buttons = { { text = "Create", onClick = function(frame, name) if name and name ~= "" then AIO.Handle("GameMasterSystem", "CreateTeleportAtCurrentPosition", name) frame:Hide() -- Refresh the list if Teleport.RequestTeleportData then Teleport.RequestTeleportData() end end end }, { text = "Cancel", onClick = function(frame) frame:Hide() end } } }) dialog:Show() end end -- Debug message if GMConfig and GMConfig.config and GMConfig.config.debug then print("[GameMasterUI] Teleport context menu module loaded") end
0
0.871819
1
0.871819
game-dev
MEDIA
0.728069
game-dev,desktop-app
0.85638
1
0.85638
rockbite/talos
4,086
editor/src/com/talosvfx/talos/editor/addons/scene/apps/spriteeditor/SpriteEditor.java
package com.talosvfx.talos.editor.addons.scene.apps.spriteeditor; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasSprite; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Scaling; import com.talosvfx.talos.editor.addons.scene.apps.spriteeditor.widgets.VerticalIconMenu; import com.talosvfx.talos.runtime.assets.GameAsset; import com.talosvfx.talos.editor.project2.SharedResources; import com.talosvfx.talos.editor.widgets.ui.common.ColorLibrary; public class SpriteEditor extends Table { private final VerticalIconMenu<Actor, SpriteEditorWindow> editorMenu; private final Table container; private final Cell contentCell; private SpriteEditorWindowMenuTab currentTab; public SpriteEditor() { editorMenu = new VerticalIconMenu<>(); final SpriteEditorWindowMenuTab propertiesTab = new SpriteEditorWindowMenuTab("ic-menu-image-settings"); final SpriteEditorWindowMenuTab ninePatchTab = new SpriteEditorWindowMenuTab("ic-menu-ninepatch"); editorMenu.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (actor instanceof SpriteEditorWindowMenuTab) { setCurrentTab((SpriteEditorWindowMenuTab) actor); } } }); container = new Table(); container.setBackground(ColorLibrary.obtainBackground(ColorLibrary.SHAPE_SQUARE, ColorLibrary.BackgroundColor.SUPER_DARK_GRAY)); contentCell = container.add().grow(); add(editorMenu).width(35).padTop(5).growY(); add(container).grow(); // populate windows editorMenu.addTab(propertiesTab, new SpritePropertiesEditorWindow(this)); editorMenu.addTab(ninePatchTab, new NinepatchEditingWindow(this)); // set first opened tab the properties tab setCurrentTab(propertiesTab); } private void setCurrentTab (SpriteEditorWindowMenuTab tab) { if (currentTab != null) currentTab.spriteEditorTab.setChecked(false); currentTab = tab; currentTab.spriteEditorTab.setChecked(true); SpriteEditorWindow window = editorMenu.getWindow(currentTab); contentCell.setActor(window); setScrollFocus(); window.show(); } public void updateForGameAsset (GameAsset<AtlasSprite> gameAsset) { for (SpriteEditorWindow spriteEditorWindow : editorMenu.getTabWindowMap().values()) { spriteEditorWindow.updateForGameAsset(gameAsset); } } public void setScrollFocus() { editorMenu.getWindow(currentTab).setScrollFocus(); } public class SpriteEditorWindowMenuTab extends Table { private final Button spriteEditorTab; public SpriteEditorWindowMenuTab(String iconName) { spriteEditorTab = new Button(SharedResources.skin); final Button.ButtonStyle buttonStyle = new Button.ButtonStyle(SharedResources.skin.get(Button.ButtonStyle.class)); buttonStyle.up = ColorLibrary.obtainBackground(ColorLibrary.SHAPE_SQUIRCLE_LEFT_2, ColorLibrary.BackgroundColor.ULTRA_DARK_GRAY); buttonStyle.over = ColorLibrary.obtainBackground(ColorLibrary.SHAPE_SQUIRCLE_LEFT_2, ColorLibrary.BackgroundColor.DARK_GRAY); buttonStyle.checked = ColorLibrary.obtainBackground(ColorLibrary.SHAPE_SQUIRCLE_LEFT_2, ColorLibrary.BackgroundColor.SUPER_DARK_GRAY); spriteEditorTab.setStyle(buttonStyle); final Table iconWrapper = new Table(); final Image icon = new Image(SharedResources.skin.getDrawable(iconName), Scaling.fit); iconWrapper.add(icon).grow().pad(4); iconWrapper.setTouchable(Touchable.disabled); stack(spriteEditorTab, iconWrapper).grow().padLeft(10); } } }
0
0.932151
1
0.932151
game-dev
MEDIA
0.806205
game-dev
0.980493
1
0.980493
fuji-fabric/fuji
2,614
fabric/src/main/java/mod/fuji/module/mixin/color/sign/ServerPlayerEntityMixin.java
package mod.fuji.module.mixin.color.sign; import mod.fuji.core.structure.GlobalBlockPos; import mod.fuji.module.initializer.color.sign.ColorSignInitializer; import mod.fuji.module.initializer.color.sign.structure.SignCache; import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.block.entity.SignText; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; @Mixin(ServerPlayerEntity.class) public abstract class ServerPlayerEntityMixin { @Unique @NotNull final ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; // NOTE: In lower MC versions like MC 1.20.1, if there are `<rb>` tag in the sign, then the `openEditSignScreen` method will not be called. @Inject(method = "openEditSignScreen", at = @At("HEAD")) private void sendBlockStateUpdatePacketOfSerializedTextBeforeTheClientOpenTheEditScreen(@NotNull SignBlockEntity signBlockEntity, boolean isFront, @NotNull CallbackInfo ci) { /* Update the sign text in server-side with the SignCache value before the client-side open the sign editor screen. */ SignCache signCache = ColorSignInitializer.readSignCache(new GlobalBlockPos(signBlockEntity.getWorld(), signBlockEntity.getPos())); if (signCache == null) return; /* Modify the text of the sign. */ List<String> trueLines = isFront ? signCache.getFrontLines() : signCache.getBackLines(); Text[] newTextList = {Text.empty(), Text.empty(), Text.empty(), Text.empty()}; for (int i = 0; i < trueLines.size(); i++) { String line = trueLines.get(i); // Escape from mojang sign editor. line = line.replace("<", "\\<") .replace(">", "\\>"); // Restore the raw string. newTextList[i] = Text.literal(line); } /* Send update packet. */ boolean facingFront = signBlockEntity.isPlayerFacingFront(player); SignText originalSignText = signBlockEntity.getText(facingFront); SignText newSignText = new SignText(newTextList, newTextList, originalSignText.getColor(), originalSignText.isGlowing()); signBlockEntity.setText(newSignText, facingFront); player.networkHandler.sendPacket(signBlockEntity.toUpdatePacket()); } }
0
0.863239
1
0.863239
game-dev
MEDIA
0.813689
game-dev
0.942851
1
0.942851
CalamityTeam/CalamityModPublic
5,830
Projectiles/Ranged/MaelstromHoldout.cs
using CalamityMod.Items.Weapons.Ranged; using CalamityMod.Particles; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Ranged { public class MaelstromHoldout : ModProjectile { public override LocalizedText DisplayName => CalamityUtils.GetItemName<TheMaelstrom>(); private Player Owner => Main.player[Projectile.owner]; private ref float CurrentChargingFrames => ref Projectile.ai[0]; private ref float FramesToLoadNextArrow => ref Projectile.localAI[0]; public override string Texture => "CalamityMod/Items/Weapons/Ranged/TheMaelstrom"; public override void SetDefaults() { Projectile.width = 78; Projectile.height = 137; Projectile.friendly = true; Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.DamageType = DamageClass.Ranged; } public override void AI() { Vector2 armPosition = Owner.RotatedRelativePoint(Owner.MountedCenter, true); Vector2 shootPosition = armPosition + Projectile.velocity * Projectile.width * 0.5f; // Destroy the holdout projectile if the owner is no longer eligible to hold it. if (Owner.CantUseHoldout() || !Owner.HasAmmo(Owner.ActiveItem())) { Projectile.Kill(); return; } // Frame 1 effects: Record how fast the hold item being used is, to determine how fast to load arrows. if (FramesToLoadNextArrow == 0f) { SoundEngine.PlaySound(SoundID.Item20, Projectile.Center); FramesToLoadNextArrow = Owner.ActiveItem().useAnimation; } // Actually make progress towards loading more arrows. CurrentChargingFrames++; // If it is time to do so, produce a pulse of particles and shoot an arrow. if (CurrentChargingFrames % FramesToLoadNextArrow == FramesToLoadNextArrow - 1) ShootProjectiles(shootPosition); UpdateProjectileHeldVariables(armPosition); ManipulatePlayerVariables(); } public void ShootProjectiles(Vector2 shootPosition) { // Create electric particles. if (Main.netMode != NetmodeID.Server) { for (int i = 0; i < 16; i++) { int sparkLifetime = Main.rand.Next(22, 36); float sparkScale = Main.rand.NextFloat(1f, 1.3f); Color sparkColor = Color.Lerp(Color.Cyan, Color.AliceBlue, Main.rand.NextFloat(0.35f)); Vector2 sparkVelocity = (MathHelper.TwoPi * i / 16f + Main.rand.NextFloat(0.09f)).ToRotationVector2() * Main.rand.NextFloat(6f, 14f); sparkVelocity.Y -= Owner.gravDir * 4f; SparkParticle spark = new SparkParticle(shootPosition, sparkVelocity, false, sparkLifetime, sparkScale, sparkColor); GeneralParticleHandler.SpawnParticle(spark); } } // Play a shoot sound. SoundEngine.PlaySound(SoundID.Item66, Projectile.Center); SoundEngine.PlaySound(SoundID.Item96, Projectile.Center); if (Main.myPlayer != Projectile.owner) return; Item heldItem = Owner.ActiveItem(); // Calculate damage at the instant the arrow is fired int arrowDamage = heldItem is null ? 0 : Owner.GetWeaponDamage(heldItem); float shootSpeed = heldItem.shootSpeed; float knockback = heldItem.knockBack; int projectileType = 0; Owner.PickAmmo(heldItem, out projectileType, out shootSpeed, out arrowDamage, out knockback, out _); projectileType = ModContent.ProjectileType<TheMaelstromShark>(); knockback = Owner.GetWeaponKnockback(heldItem, knockback); Vector2 shootVelocity = Projectile.velocity.SafeNormalize(Vector2.UnitY) * shootSpeed; Projectile.NewProjectile(Projectile.GetSource_FromThis(), shootPosition, shootVelocity, projectileType, arrowDamage, knockback, Projectile.owner, 0f, 0f); } private void UpdateProjectileHeldVariables(Vector2 armPosition) { if (Main.myPlayer == Projectile.owner) { float aimInterpolant = Utils.GetLerpValue(5f, 25f, Projectile.Distance(Main.MouseWorld), true); Vector2 oldVelocity = Projectile.velocity; Projectile.velocity = Vector2.Lerp(Projectile.velocity, Projectile.SafeDirectionTo(Main.MouseWorld), aimInterpolant); if (Projectile.velocity != oldVelocity) { Projectile.netSpam = 0; Projectile.netUpdate = true; } } Projectile.position = armPosition - Projectile.Size * 0.5f + Projectile.velocity * 24f; Projectile.rotation = Projectile.velocity.ToRotation(); if (Projectile.spriteDirection == -1) Projectile.rotation += MathHelper.Pi; Projectile.spriteDirection = Projectile.direction; Projectile.timeLeft = 2; } private void ManipulatePlayerVariables() { Owner.ChangeDir(Projectile.direction); Owner.heldProj = Projectile.whoAmI; Owner.itemTime = 2; Owner.itemAnimation = 2; Owner.itemRotation = (Projectile.velocity * Projectile.direction).ToRotation(); } public override bool? CanDamage() => false; } }
0
0.879233
1
0.879233
game-dev
MEDIA
0.998397
game-dev
0.965205
1
0.965205
glKarin/com.n0n3m4.diii4a
4,301
Q3E/src/main/jni/source/game/server/te_physicsprop.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basetempentity.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: create clientside physics prop, as breaks model if needed //----------------------------------------------------------------------------- class CTEPhysicsProp : public CBaseTempEntity { public: DECLARE_CLASS( CTEPhysicsProp, CBaseTempEntity ); CTEPhysicsProp( const char *name ); virtual ~CTEPhysicsProp( void ); virtual void Test( const Vector& current_origin, const QAngle& current_angles ); virtual void Precache( void ); DECLARE_SERVERCLASS(); public: CNetworkVector( m_vecOrigin ); CNetworkQAngle( m_angRotation ); CNetworkVector( m_vecVelocity ); CNetworkVar( int, m_nModelIndex ); CNetworkVar( int, m_nSkin ); CNetworkVar( int, m_nFlags ); CNetworkVar( int, m_nEffects ); }; //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- CTEPhysicsProp::CTEPhysicsProp( const char *name ) : CBaseTempEntity( name ) { m_vecOrigin.Init(); m_angRotation.Init(); m_vecVelocity.Init(); m_nModelIndex = 0; m_nSkin = 0; m_nFlags = 0; m_nEffects = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTEPhysicsProp::~CTEPhysicsProp( void ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTEPhysicsProp::Precache( void ) { CBaseEntity::PrecacheModel( "models/gibs/hgibs.mdl" ); } //----------------------------------------------------------------------------- // Purpose: // Input : *current_origin - // *current_angles - //----------------------------------------------------------------------------- void CTEPhysicsProp::Test( const Vector& current_origin, const QAngle& current_angles ) { // Fill in data m_nModelIndex = CBaseEntity::PrecacheModel( "models/gibs/hgibs.mdl" ); m_nSkin = 0; m_vecOrigin = current_origin; m_angRotation = current_angles; m_vecVelocity.Init( random->RandomFloat( -10, 10 ), random->RandomFloat( -10, 10 ), random->RandomFloat( 0, 20 ) ); m_nFlags = 0; m_nEffects = 0; Vector forward, right; m_vecOrigin += Vector( 0, 0, 24 ); AngleVectors( current_angles, &forward, &right, 0 ); forward[2] = 0.0; VectorNormalize( forward ); VectorMA( m_vecOrigin, 50.0, forward, m_vecOrigin.GetForModify() ); VectorMA( m_vecOrigin, 25.0, right, m_vecOrigin.GetForModify() ); CBroadcastRecipientFilter filter; Create( filter, 0.0 ); } IMPLEMENT_SERVERCLASS_ST(CTEPhysicsProp, DT_TEPhysicsProp) SendPropVector( SENDINFO(m_vecOrigin), -1, SPROP_COORD), SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 0), 13 ), SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 1), 13 ), SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 2), 13 ), SendPropVector( SENDINFO(m_vecVelocity), -1, SPROP_COORD), SendPropModelIndex( SENDINFO(m_nModelIndex) ), SendPropInt( SENDINFO(m_nSkin), ANIMATION_SKIN_BITS), SendPropInt( SENDINFO(m_nFlags), 2, SPROP_UNSIGNED ), SendPropInt( SENDINFO(m_nEffects), EF_MAX_BITS, SPROP_UNSIGNED), END_SEND_TABLE() // Singleton to fire TEBreakModel objects static CTEPhysicsProp s_TEPhysicsProp( "physicsprop" ); void TE_PhysicsProp( IRecipientFilter& filter, float delay, int modelindex, int skin, const Vector& pos, const QAngle &angles, const Vector& vel, int flags, int effects ) { s_TEPhysicsProp.m_vecOrigin = pos; s_TEPhysicsProp.m_angRotation = angles; s_TEPhysicsProp.m_vecVelocity = vel; s_TEPhysicsProp.m_nModelIndex = modelindex; s_TEPhysicsProp.m_nSkin = skin; s_TEPhysicsProp.m_nFlags = flags; s_TEPhysicsProp.m_nEffects = effects; // Send it over the wire s_TEPhysicsProp.Create( filter, delay ); }
0
0.8773
1
0.8773
game-dev
MEDIA
0.695063
game-dev
0.671015
1
0.671015
xfw5/Fear-SDK-1.08
4,865
Game/ObjectDLL/AISensorSeekEnemy.cpp
// ----------------------------------------------------------------------- // // // MODULE : AISensorSeekEnemy.cpp // // PURPOSE : AISensorSeekEnemy class implementation // // CREATED : 12/16/03 // // (c) 2003 Monolith Productions, Inc. All Rights Reserved // ----------------------------------------------------------------------- // #include "Stdafx.h" #include "AISensorSeekEnemy.h" #include "AI.h" #include "AIDB.h" #include "AISensorMgr.h" #include "AIStimulusMgr.h" #include "AIBlackBoard.h" #include "AIWorkingMemory.h" DEFINE_AI_FACTORY_CLASS_SPECIFIC( Sensor, CAISensorSeekEnemy, kSensor_SeekEnemy ); // ----------------------------------------------------------------------- // // // ROUTINE: CAISensorSeekEnemy::CAISensorSeekEnemy // // PURPOSE: Constructor. // // ----------------------------------------------------------------------- // CAISensorSeekEnemy::CAISensorSeekEnemy() { m_hEnemy = NULL; m_bEnemyReset = false; m_bSeekSquadEnemy = false; } //---------------------------------------------------------------------------- // // ROUTINE: CAISensorSeekEnemy::Save/Load // // PURPOSE: Handle saving and restoring the CAISensorSeekEnemy // //---------------------------------------------------------------------------- void CAISensorSeekEnemy::Save(ILTMessage_Write *pMsg) { super::Save(pMsg); SAVE_HOBJECT( m_hEnemy ); SAVE_bool( m_bEnemyReset ); SAVE_bool( m_bSeekSquadEnemy ); } void CAISensorSeekEnemy::Load(ILTMessage_Read *pMsg) { super::Load(pMsg); LOAD_HOBJECT( m_hEnemy ); LOAD_bool( m_bEnemyReset ); LOAD_bool( m_bSeekSquadEnemy ); } // ----------------------------------------------------------------------- // // // ROUTINE: CAISensorSeekEnemy::UpdateSensor // // PURPOSE: Return true if this sensor updated, and the SensorMgr // should wait to update others. // // ----------------------------------------------------------------------- // bool CAISensorSeekEnemy::UpdateSensor() { if( !super::UpdateSensor() ) { return false; } // Bail if enemy is gone. if( !m_hEnemy ) { SeekEnemy( false ); m_pAI->GetAISensorMgr()->RemoveAISensor( kSensor_SeekEnemy ); return false; } // Enemy may be a character, or something else (e.g. Turret). ENUM_AIWMFACT_TYPE eFactType = IsCharacter( m_hEnemy ) ? kFact_Character : kFact_Object; // Find an existing memory for this character, // or create a new memory for this character. CAIWMFact factQuery; factQuery.SetFactType( eFactType ); factQuery.SetTargetObject( m_hEnemy ); CAIWMFact* pFact = m_pAI->GetAIWorkingMemory()->FindWMFact( factQuery ); if( !pFact ) { pFact = m_pAI->GetAIWorkingMemory()->CreateWMFact( eFactType ); // Setup faked stimulus with 0.0 confidence, to differentiate from a real stimulus. pFact->SetStimulus( kStim_CharacterVisible, g_pAIStimulusMgr->GetNextStimulusID(), 0.f ); pFact->SetTargetObject( m_hEnemy, 1.f ); pFact->SetFactFlags( 0 ); // Set the stimulus distance and direction. AIDB_StimulusRecord* pAIDB_Stimulus = g_pAIDB->GetAIStimulusRecord( kStim_CharacterVisible ); if( pAIDB_Stimulus ) { pFact->SetRadius( pAIDB_Stimulus->fDistance, 1.f ); pFact->SetDir( LTVector( 0.f, 1.f, 0.f ), 1.f ); } // Re-evaluate targets when a new enemy is discovered. m_pAI->GetAIBlackBoard()->SetBBInvalidateTarget( true ); } // Clear any stimulus confidence when an enemy is set. if( m_bEnemyReset ) { SeekEnemy( true ); pFact->SetConfidence( CAIWMFact::kFactMask_Stimulus, 0.f ); m_bEnemyReset = false; } // Destroy sensor if AI has actually sensed the enemy. else if( pFact->GetConfidence( CAIWMFact::kFactMask_Stimulus ) > 0.f ) { SeekEnemy( false ); m_pAI->GetAISensorMgr()->RemoveAISensor( kSensor_SeekEnemy ); return false; } // Sensor forces AI to be 100% sure of target's location. LTVector vPos; g_pLTServer->GetObjectPos( m_hEnemy, &vPos ); pFact->SetPos( vPos, 1.f ); // Set the update time. pFact->SetUpdateTime( g_pLTServer->GetTime() ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: CAISensorSeekEnemy::SeekEnemy // // PURPOSE: Set variables for seeking an enemy, or not. // // ----------------------------------------------------------------------- // void CAISensorSeekEnemy::SeekEnemy( bool bSeek ) { // Stop tracking the target position if no longer seeking. uint32 dwFlags = m_pAI->GetAIBlackBoard()->GetBBTargetPosTrackingFlags(); // Seeking a squad enemy. if( m_bSeekSquadEnemy ) { if( bSeek ) { dwFlags = kTargetTrack_Squad; } else { dwFlags = kTargetTrack_Normal; } } // Default behavior. else { if( bSeek ) { dwFlags |= kTargetTrack_SeekEnemy; } else { dwFlags = dwFlags & ~kTargetTrack_SeekEnemy; } } m_pAI->GetAIBlackBoard()->SetBBTargetPosTrackingFlags( dwFlags ); }
0
0.876795
1
0.876795
game-dev
MEDIA
0.921911
game-dev
0.97296
1
0.97296
Pizzalol/SpellLibrary
3,860
game/scripts/vscripts/items/item_abyssal_blade.lua
--[[ ============================================================================================================ Author: Rook Date: February 1, 2015 Called when a unit with Abyssal Blade lands an attack. Calculates whether a stun should occur, and applies one if so. Additional parameters: keys.BashChanceMelee and keys.BashChanceRanged ================================================================================================================= ]] function modifier_item_abyssal_blade_datadriven_bash_chance_on_attack_landed(keys) if not keys.caster:HasModifier("bash_cooldown_modifier") then local random_int = RandomInt(1, 100) local is_ranged_attacker = keys.caster:IsRangedAttacker() if (is_ranged_attacker and random_int <= keys.BashChanceRanged) or (not is_ranged_attacker and random_int <= keys.BashChanceMelee) then keys.target:EmitSound("DOTA_Item.SkullBasher") keys.ability:ApplyDataDrivenModifier(keys.caster, keys.target, "modifier_item_abyssal_blade_datadriven_bash", nil) --Give the caster a generic "bash cooldown" modifier so they cannot bash in the next couple of seconds due to any item. keys.ability:ApplyDataDrivenModifier(keys.caster, keys.caster, "bash_cooldown_modifier", nil) end end end --[[ ============================================================================================================ Author: Rook Date: February 1, 2015 Called when Abyssal Blade is cast. Stuns the target unit. ================================================================================================================= ]] function item_abyssal_blade_datadriven_on_spell_start(keys) keys.target:EmitSound("DOTA_Item.AbyssalBlade.Activate") keys.ability:ApplyDataDrivenModifier(keys.caster, keys.target, "modifier_item_abyssal_blade_datadriven_active", nil) ParticleManager:CreateParticle("particles/items_fx/abyssal_blade.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.target) end --[[ ============================================================================================================ Author: Rook Date: February 1, 2015 Called when a bash chance modifier is created or destroyed on the unit. Ensures that only one of these modifiers is active on the unit, since they should not stack. ================================================================================================================= ]] function modifier_item_abyssal_blade_datadriven_recalculate_bash_chance(keys) Timers:CreateTimer({ callback = function() --Temporarily remove all Skull Basher and Abyssal Blade bash chance modifiers. while keys.caster:HasModifier("modifier_item_basher_datadriven_bash_chance") do keys.caster:RemoveModifierByName("modifier_item_basher_datadriven_bash_chance") end while keys.caster:HasModifier("modifier_item_abyssal_blade_datadriven_bash_chance") do keys.caster:RemoveModifierByName("modifier_item_abyssal_blade_datadriven_bash_chance") end --Find out if there is a Skull Basher or Abyssal Blade in the player's inventory. local skull_basher = nil local abyssal_blade = nil for i=0, 5, 1 do local current_item = keys.caster:GetItemInSlot(i) if current_item ~= nil then local item_name = current_item:GetName() if item_name == "item_basher_datadriven" then skull_basher = current_item elseif item_name == "item_abyssal_blade_datadriven" then abyssal_blade = current_item end end end if abyssal_blade ~= nil then --Prioritize the Abyssal Blade bash chance modifier. abyssal_blade:ApplyDataDrivenModifier(keys.caster, keys.caster, "modifier_item_abyssal_blade_datadriven_bash_chance", {duration = -1}) elseif skull_basher ~= nil then skull_basher:ApplyDataDrivenModifier(keys.caster, keys.caster, "modifier_item_basher_datadriven_bash_chance", {duration = -1}) end end }) end
0
0.747363
1
0.747363
game-dev
MEDIA
0.630631
game-dev
0.829059
1
0.829059
ChaoticOnyx/OnyxBay
1,498
code/game/machinery/vending/_vending_cartridge.dm
/obj/item/vending_cartridge name = "generic cartridge" desc = "Simple, yet bulky piece of tech that used to store ite" icon = 'icons/obj/vending_restock.dmi' icon_state = "refill_generic" w_class = ITEM_SIZE_LARGE /// Determines what kind of vending machine we want to build. var/build_path = /obj/machinery/vending var/list/legal = list() var/list/extra = list() var/list/illegal = list() var/list/premium = list() var/list/prices = list() /// List of `datum/stored_items/vending_products` used by vending machines. var/list/product_records = list() /obj/item/vending_cartridge/Initialize() . = ..() name = "[initial(build_path["name"])] cartridge" build_inventory() /obj/item/vending_cartridge/Destroy() QDEL_NULL_LIST(product_records) return ..() /obj/item/vending_cartridge/proc/build_inventory(random = FALSE) if(length(extra)) legal |= extra var/list/all_products = list(list(legal, CAT_NORMAL), list(illegal, CAT_HIDDEN), list(premium, CAT_COIN)) for(var/current_list in all_products) var/category = current_list[2] for(var/entry in current_list[1]) var/datum/stored_items/vending_products/product = new /datum/stored_items/vending_products(src, entry) product.price = (entry in prices) ? prices[entry] : 0 product.category = category var/amount = current_list[1][entry] if(random) product.amount = amount ? max(0, amount - rand(0, round(amount * 1.5))) : 1 else product.amount = amount || 1 product_records.Add(product)
0
0.731126
1
0.731126
game-dev
MEDIA
0.979096
game-dev
0.851631
1
0.851631
AndnixSH/Free-Shared-Mod-Codes-Collections
1,339
Unity DLL modding (C#)/Light Fellowship Of Loux.cs
//Game: Light Fellowship of Loux //Version: 2.2.1 //APK: https://apkpure.com/light-fellowship-of-loux/com.com2us.thelight.normal.freefull.google.global.android.common //Dump hidden dll from memory. Assembly name called xgame1.6.01535942274. Rename it to Assembly-UnityScript.dll //Note: It have Appguard protection but we will not give bypass method unless the service has been discontinued //Calling Mod menu //Class: BattleStage, GameMgr, Lobby, MainWindow public void OnGUI() { ModMenu.ButtonMenu(); } //Class: ActorStatus public void AddDamage(HitType hitType, int damage, InfluenceType influenceType = InfluenceType.None) { if (!base.owner.IsPlaying) { return; } int num; //1 hit kill if (ModMenu.hack1 && base.owner.actorType == ActorType.Enemy) { num = ((hitType != HitType.Heal) ? (this.basicStat.curHP - this.maxHP) : (this.basicStat.curHP + damage)); } //God mode else if (ModMenu.hack2 && base.owner.actorType == ActorType.Player) { num = ((hitType != HitType.Heal) ? (this.basicStat.curHP + this.maxHP) : (this.basicStat.curHP + damage)); } //Normal else { num = ((hitType != HitType.Heal) ? (this.basicStat.curHP - damage) : (this.basicStat.curHP + damage)); } if (num < 0) { num = 0; } this.PrintInfluence(hitType, damage, influenceType); this.SetCurHP(num); }
0
0.776543
1
0.776543
game-dev
MEDIA
0.959629
game-dev
0.695213
1
0.695213
griefly/griefly
4,982
sources/core/ObjectFactory.cpp
#include "ObjectFactory.h" #include "KvAbort.h" #include "objects/Object.h" #include "objects/MaterialObject.h" #include "objects/PhysicsEngine.h" #include "Map.h" #include "SynchronizedRandom.h" #include "AutogenMetadata.h" #include "WorldLoaderSaver.h" #include "objects/GlobalObjectsHolder.h" ObjectFactory::ObjectFactory(GameInterface* game) { objects_table_.resize(100); id_ = 1; is_world_generating_ = true; game_ = game; id_ptr_id_table = &objects_table_; } ObjectFactory::~ObjectFactory() { ProcessDeletion(); for (auto& info : objects_table_) { if (info.object) { delete info.object; } } } std::vector<ObjectInfo>& ObjectFactory::GetIdTable() { return objects_table_; } const std::vector<ObjectInfo>& ObjectFactory::GetIdTable() const { return objects_table_; } kv::Object* ObjectFactory::NewVoidObject(const QString& type) { auto creator = GetItemsCreators()->find(type); if (creator == GetItemsCreators()->end()) { kv::Abort(QString("Unable to find creator for type: %1").arg(type)); } return creator->second(); } kv::Object* ObjectFactory::NewVoidObjectSaved(const QString& type) { auto creator = GetVoidItemsCreators()->find(type); if (creator == GetVoidItemsCreators()->end()) { kv::Abort(QString("Unable to find void creator for type: %1").arg(type)); } return creator->second(); } void ObjectFactory::Clear() { const quint32 table_size = static_cast<quint32>(objects_table_.size()); for (quint32 i = 1; i < table_size; ++i) { if (objects_table_[i].object != nullptr) { delete objects_table_[i].object; } } if (table_size != objects_table_.size()) { qDebug() << "WARNING: table_size != idTable_.size()!"; } ids_to_delete_.clear(); id_ = 1; } void ObjectFactory::BeginWorldCreation() { is_world_generating_ = true; } void ObjectFactory::FinishWorldCreation() { MarkWorldAsCreated(); const quint32 table_size = static_cast<quint32>(objects_table_.size()); for (quint32 i = 1; i < table_size; ++i) { if (objects_table_[i].object != nullptr) { objects_table_[i].object->AfterWorldCreation(); } } } void ObjectFactory::MarkWorldAsCreated() { is_world_generating_ = false; } quint32 ObjectFactory::CreateImpl(const QString &type, quint32 owner_id) { kv::Object* item = NewVoidObject(type); kv::internal::GetObjectGame(item) = game_; if (id_ >= objects_table_.size()) { objects_table_.resize(id_ * 2); } objects_table_[id_].object = item; kv::internal::GetObjectId(item) = id_; item->SetFreq(item->GetFreq()); quint32 retval = id_; ++id_; IdPtr<kv::MapObject> owner = owner_id; if (owner.IsValid()) { if (CastTo<kv::Turf>(item) != nullptr) { owner->SetTurf(item->GetId()); } else if (!owner->AddObject(item->GetId())) { kv::Abort("AddItem failed"); } } if (item->ToHearer()) { game_->GetGlobals()->hearers.append(retval); } if (!is_world_generating_) { item->AfterWorldCreation(); } return retval; } kv::Object* ObjectFactory::CreateVoid(const QString &hash, quint32 id_new) { kv::Object* item = NewVoidObjectSaved(hash); kv::internal::GetObjectGame(item) = game_; if (id_new >= objects_table_.size()) { objects_table_.resize(id_new * 2); } if (id_new >= id_) { id_ = id_new + 1; } objects_table_[id_new].object = item; kv::internal::GetObjectId(item) = id_new; item->SetFreq(item->GetFreq()); return item; } quint32 ObjectFactory::CreateAssetImpl(const kv::Asset& asset, quint32 owner_id) { auto object = kv::world::LoadObject(game_, asset.ToJsonForObjectCreation()); IdPtr<kv::MapObject> owner = owner_id; if (owner.IsValid()) { if (CastTo<kv::Turf>(object.operator->()) != nullptr) { owner->SetTurf(object->GetId()); } else if (!owner->AddObject(object->GetId())) { kv::Abort("AddItem failed"); } } return object->GetId(); } void ObjectFactory::DeleteLater(quint32 id) { ids_to_delete_.push_back(objects_table_[id].object); objects_table_[id].object = nullptr; } void ObjectFactory::ProcessDeletion() { for (auto it = ids_to_delete_.begin(); it != ids_to_delete_.end(); ++it) { delete *it; } ids_to_delete_.clear(); } quint32 ObjectFactory::Hash() const { unsigned int h = 0; const quint32 table_size = static_cast<quint32>(objects_table_.size()); for (quint32 i = 1; i < table_size; ++i) { if (objects_table_[i].object != nullptr) { // TODO (?): i to hash h += objects_table_[i].object->HashMembers(); } } return h; }
0
0.882363
1
0.882363
game-dev
MEDIA
0.861946
game-dev
0.925894
1
0.925894
iw4x/iw4x-client
1,670
src/Game/Engine/LargeLocal.cpp
#include "LargeLocal.hpp" namespace Game::Engine { LargeLocal::LargeLocal(int sizeParam) { assert(sizeParam); assert(Sys_IsMainThread() || CanUseServerLargeLocal()); sizeParam = ((sizeParam + (128 - 1)) & ~(128 - 1)); if (Sys_IsMainThread()) { this->startPos = LargeLocalBegin(sizeParam); } else { this->startPos = LargeLocalBeginRight(sizeParam); } this->size = sizeParam; } LargeLocal::~LargeLocal() { if (this->size) { this->PopBuf(); } } void LargeLocal::PopBuf() { assert(this->size); assert(Sys_IsMainThread() || CanUseServerLargeLocal()); if (Sys_IsMainThread()) { LargeLocalEnd(this->startPos); } else { LargeLocalEndRight(this->startPos); } this->size = 0; } void* LargeLocal::GetBuf() const { assert(this->size); assert(Sys_IsMainThread() || CanUseServerLargeLocal()); return LargeLocalGetBuf(this->startPos, this->size); } void LargeLocalEnd(int startPos) { assert(Sys_IsMainThread()); assert(g_largeLocalBuf); *g_largeLocalPos = startPos; } void LargeLocalEndRight(int startPos) { assert(CanUseServerLargeLocal()); assert(g_largeLocalBuf); *g_largeLocalRightPos = startPos; } void* LargeLocalGetBuf(int startPos, int size) { assert(Sys_IsMainThread() || CanUseServerLargeLocal()); assert(g_largeLocalBuf); assert(!(size & 127)); if (Sys_IsMainThread()) { return &g_largeLocalBuf[startPos]; } const auto startIndex = startPos - size; assert(startIndex >= 0); return &g_largeLocalBuf[startIndex]; } int CanUseServerLargeLocal() { return SV_GetServerThreadOwnsGame() ? Sys_IsServerThread() : Sys_IsRenderThread(); } }
0
0.818536
1
0.818536
game-dev
MEDIA
0.433531
game-dev,testing-qa
0.633393
1
0.633393
Hoto-Mocha/New-Blue-Archive-Pixel-Dungeon
2,336
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Degrade.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2025 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.buffs; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator; public class Degrade extends FlavourBuff { public static final float DURATION = 30f; { type = buffType.NEGATIVE; announced = true; } @Override public boolean attachTo(Char target) { if (super.attachTo(target)){ Item.updateQuickslot(); if (target == Dungeon.hero) ((Hero) target).updateHT(false); return true; } return false; } @Override public void detach() { super.detach(); if (target == Dungeon.hero) ((Hero) target).updateHT(false); Item.updateQuickslot(); } //called in Item.buffedLevel() public static int reduceLevel( int level ){ if (level <= 0){ //zero or negative levels are unaffected return level; } else { //Otherwise returns the rounded result of sqrt(2*(lvl-1)) + 1 // This means that levels 1/2/3/4/5/6/7/8/9/10/11/12/... // Are now instead: 1/2/3/3/4/4/4/5/5/ 5/ 5/ 6/... // Basically every level starting with 3 sticks around for 1 level longer than the last return (int)Math.round(Math.sqrt(2*(level-1)) + 1); } } @Override public int icon() { return BuffIndicator.DEGRADE; } @Override public float iconFadePercent() { return (DURATION - visualcooldown())/DURATION; } }
0
0.889305
1
0.889305
game-dev
MEDIA
0.991978
game-dev
0.966189
1
0.966189
plankes-projects/BaseWar
2,396
client/Classes/Model/Units/Race.h
/* * Race.h * * Created on: May 21, 2013 * Author: planke */ #ifndef RACE_H_ #define RACE_H_ #include "Tier.h" #include "../ArmyType.h" #include <string> #include <list> #include <vector> class Player; class UnitFactory; class Race { public: std::vector<UnitFactory*> getUnitFactories(Tier tier); std::vector<UnitFactory*> getAllUnitFactories(); //after creation, you need to call setArmyTypeAndOwner! static Race* createRaceWithId(int id); static Race* createMindChamberRace(); static Race* createBotanicRace(); static Race* createThirdRace(); /* * This will look at all units possible. * Than chose 3 from each tier and build a race with them. */ static std::string createRandomizedRaceString(); static Race* buildRaceFromRandomizedRaceString(std::string randomizedRaceString); virtual void setArmyTypeAndOwner(ArmyType armyType, Player* owner); virtual ~Race(); float getTier2Cost(); float getTier3Cost(); void reduceTier2Cost(float reduce); void reduceTier3Cost(float reduce); void setRaceButton0(std::string name); void setRaceButton1(std::string name); std::string getRaceButton0(); std::string getRaceButton1(); int getRaceId(); void setRaceId(int id); std::string getRandomRaceString() { return _randomRaceString; } void setRandomRaceString(std::string randomRaceString) { _randomRaceString = randomRaceString; } virtual void applyRaceHandicap(float multiplicator); virtual void spawn(); bool isSkipUnitInfo(){ return _isSkipUnitInfo; } bool isAIOnly(){ return _AIOnly; } void setDeleteUnitFactoriesInDestructor(bool enable){ _deleteUnitFactoriesInDestructor = enable; } protected: bool _isSkipUnitInfo; /** * If we set AIOnly we have to implement the AI ourself in the subclass */ bool _AIOnly; Race(); bool _deleteUnitFactoriesInDestructor; private: std::string _randomRaceString; static char _randomRaceStringConnector; static int _randomRaceUnitsPerTier; std::string _name; std::string _raceButton0; std::string _raceButton1; std::vector<UnitFactory*> _tier1; std::vector<UnitFactory*> _tier2; std::vector<UnitFactory*> _tier3; float _tier2Cost; float _tier3Cost; int _raceId; void addUnitFactory(Tier tier, UnitFactory* unitFactory); void addUnitFactoryFromRandomizedCORRECTNumber(Tier tier, int correctRandomizedRaceNumber, std::vector<Race*> races); }; #endif /* RACE_H_ */
0
0.800146
1
0.800146
game-dev
MEDIA
0.741145
game-dev
0.818469
1
0.818469
glKarin/com.n0n3m4.diii4a
6,025
Q3E/src/main/jni/source/game/client/hud_numericdisplay.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "hud_numericdisplay.h" #include "iclientmode.h" #include <Color.h> #include <KeyValues.h> #include <vgui/ISurface.h> #include <vgui/ISystem.h> #include <vgui/IVGui.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" using namespace vgui; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CHudNumericDisplay::CHudNumericDisplay(vgui::Panel *parent, const char *name) : BaseClass(parent, name) { vgui::Panel *pParent = g_pClientMode->GetViewport(); SetParent( pParent ); m_iValue = 0; m_LabelText[0] = 0; m_iSecondaryValue = 0; m_bDisplayValue = true; m_bDisplaySecondaryValue = false; m_bIndent = false; m_bIsTime = false; } //----------------------------------------------------------------------------- // Purpose: Resets values on restore/new map //----------------------------------------------------------------------------- void CHudNumericDisplay::Reset() { m_flBlur = 0.0f; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetDisplayValue(int value) { m_iValue = value; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetSecondaryValue(int value) { m_iSecondaryValue = value; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetShouldDisplayValue(bool state) { m_bDisplayValue = state; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetShouldDisplaySecondaryValue(bool state) { m_bDisplaySecondaryValue = state; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetLabelText(const wchar_t *text) { wcsncpy(m_LabelText, text, sizeof(m_LabelText) / sizeof(wchar_t)); m_LabelText[(sizeof(m_LabelText) / sizeof(wchar_t)) - 1] = 0; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetIndent(bool state) { m_bIndent = state; } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CHudNumericDisplay::SetIsTime(bool state) { m_bIsTime = state; } //----------------------------------------------------------------------------- // Purpose: paints a number at the specified position //----------------------------------------------------------------------------- void CHudNumericDisplay::PaintNumbers(HFont font, int xpos, int ypos, int value) { surface()->DrawSetTextFont(font); wchar_t unicode[6]; if ( !m_bIsTime ) { V_snwprintf(unicode, ARRAYSIZE(unicode), L"%d", value); } else { int iMinutes = value / 60; int iSeconds = value - iMinutes * 60; #ifdef PORTAL // portal uses a normal font for numbers so we need the seperate to be a renderable ':' char if ( iSeconds < 10 ) V_snwprintf( unicode, ARRAYSIZE(unicode), L"%d:0%d", iMinutes, iSeconds ); else V_snwprintf( unicode, ARRAYSIZE(unicode), L"%d:%d", iMinutes, iSeconds ); #else if ( iSeconds < 10 ) V_snwprintf( unicode, ARRAYSIZE(unicode), L"%d`0%d", iMinutes, iSeconds ); else V_snwprintf( unicode, ARRAYSIZE(unicode), L"%d`%d", iMinutes, iSeconds ); #endif } // adjust the position to take into account 3 characters int charWidth = surface()->GetCharacterWidth(font, '0'); if (value < 100 && m_bIndent) { xpos += charWidth; } if (value < 10 && m_bIndent) { xpos += charWidth; } surface()->DrawSetTextPos(xpos, ypos); surface()->DrawUnicodeString( unicode ); } //----------------------------------------------------------------------------- // Purpose: draws the text //----------------------------------------------------------------------------- void CHudNumericDisplay::PaintLabel( void ) { surface()->DrawSetTextFont(m_hTextFont); surface()->DrawSetTextColor(GetFgColor()); surface()->DrawSetTextPos(text_xpos, text_ypos); surface()->DrawUnicodeString( m_LabelText ); } //----------------------------------------------------------------------------- // Purpose: renders the vgui panel //----------------------------------------------------------------------------- void CHudNumericDisplay::Paint() { if (m_bDisplayValue) { // draw our numbers surface()->DrawSetTextColor(GetFgColor()); PaintNumbers(m_hNumberFont, digit_xpos, digit_ypos, m_iValue); // draw the overbright blur for (float fl = m_flBlur; fl > 0.0f; fl -= 1.0f) { if (fl >= 1.0f) { PaintNumbers(m_hNumberGlowFont, digit_xpos, digit_ypos, m_iValue); } else { // draw a percentage of the last one Color col = GetFgColor(); col[3] *= fl; surface()->DrawSetTextColor(col); PaintNumbers(m_hNumberGlowFont, digit_xpos, digit_ypos, m_iValue); } } } // total ammo if (m_bDisplaySecondaryValue) { surface()->DrawSetTextColor(GetFgColor()); PaintNumbers(m_hSmallNumberFont, digit2_xpos, digit2_ypos, m_iSecondaryValue); } PaintLabel(); }
0
0.739556
1
0.739556
game-dev
MEDIA
0.598469
game-dev
0.683442
1
0.683442
GarageGames/Torque2D
7,978
engine/source/2d/controllers/PointForceController.cc
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef _ATTRACTOR_CONTROLLER_H_ #include "2d/controllers/PointForceController.h" #endif // Script bindings. #include "PointForceController_ScriptBinding.h" //------------------------------------------------------------------------------ IMPLEMENT_CONOBJECT(PointForceController); //------------------------------------------------------------------------------ PointForceController::PointForceController() { // Reset he controller. mPosition.SetZero(); mRadius = 1.0f; mForce = 0.0f; mNonLinear = true; mLinearDrag = 0.0f; mAngularDrag = 0.0f; } //------------------------------------------------------------------------------ PointForceController::~PointForceController() { } //------------------------------------------------------------------------------ void PointForceController::initPersistFields() { // Call parent. Parent::initPersistFields(); // Force. addField( "Position", TypeVector2, Offset( mPosition, PointForceController), "The position of the attractor controller."); addField( "Radius", TypeF32, Offset( mRadius, PointForceController), "The radius of the attractor circle centered on the attractors position."); addField( "Force", TypeF32, Offset( mForce, PointForceController), "The force to apply to attact to the controller position."); addField( "NonLinear", TypeBool, Offset( mNonLinear, PointForceController), "Whether to apply the force non-linearly (using the inverse square law) or linearly."); addField( "LinearDrag", TypeF32, Offset(mLinearDrag, PointForceController), "The linear drag co-efficient for the fluid." ); addField( "AngularDrag", TypeF32, Offset(mAngularDrag, PointForceController), "The angular drag co-efficient for the fluid." ); } //------------------------------------------------------------------------------ void PointForceController::copyTo(SimObject* object) { // Call to parent. Parent::copyTo(object); // Cast to controller. PointForceController* pController = static_cast<PointForceController*>(object); // Sanity! AssertFatal(pController != NULL, "PointForceController::copyTo() - Object is not the correct type."); // Copy state. pController->setForce( getForce() ); } //------------------------------------------------------------------------------ void PointForceController::setTrackedObject( SceneObject* pSceneObject ) { // Set tracked object. mTrackedObject = pSceneObject; } //------------------------------------------------------------------------------ void PointForceController::integrate( Scene* pScene, const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats ) { // Finish if the attractor would have no effect. if ( mIsZero( mForce ) || mIsZero( mRadius ) ) return; // Prepare query filter. WorldQuery* pWorldQuery = prepareQueryFilter( pScene ); // Fetch the current position. const Vector2 currentPosition = getCurrentPosition(); // Calculate the AABB of the attractor. b2AABB aabb; aabb.lowerBound.Set( currentPosition.x - mRadius, currentPosition.y - mRadius ); aabb.upperBound.Set( currentPosition.x + mRadius, currentPosition.y + mRadius ); // Query for candidate objects. pWorldQuery->anyQueryAABB( aabb ); // Fetch results. typeWorldQueryResultVector& queryResults = pWorldQuery->getQueryResults(); // Fetch result count. const U32 resultCount = (U32)queryResults.size(); // Finish if nothing to process. if ( resultCount == 0 ) return; // Calculate the radius squared. const F32 radiusSqr = mRadius * mRadius; // Calculate the force squared in-case we need it. const F32 forceSqr = mForce * mForce * (( mForce < 0.0f ) ? -1.0f : 1.0f); // Calculate drag coefficients (time-integrated). const F32 linearDrag = mClampF( mLinearDrag, 0.0f, 1.0f ) * elapsedTime; const F32 angularDrag = mClampF( mAngularDrag, 0.0f, 1.0f ) * elapsedTime; // Fetch the tracked object. const SceneObject* pTrackedObject = mTrackedObject; // Iterate the results. for ( U32 n = 0; n < resultCount; n++ ) { // Fetch the scene object. SceneObject* pSceneObject = queryResults[n].mpSceneObject; // Ignore if it's the tracked object. if ( pSceneObject == pTrackedObject ) continue; // Ignore if it's a static body. if ( pSceneObject->getBodyType() == b2_staticBody ) continue; // Calculate the force distance to the controllers current position. Vector2 distanceForce = currentPosition - pSceneObject->getPosition(); // Fetch distance squared. const F32 distanceSqr = distanceForce.LengthSquared(); // Skip if the position is outside the radius or is centered on the controller. if ( distanceSqr > radiusSqr || distanceSqr < FLT_EPSILON ) continue; // Non-Linear force? if ( mNonLinear ) { // Yes, so use an approximation of the inverse-square law. distanceForce *= (1.0f / distanceSqr) * forceSqr; } else { // No, so normalize to the specified force (linear). distanceForce.Normalize( mForce ); } // Apply the force. pSceneObject->applyForce( distanceForce, true ); // Linear drag? if ( linearDrag > 0.0f ) { // Yes, so fetch linear velocity. Vector2 linearVelocity = pSceneObject->getLinearVelocity(); // Calculate linear velocity change. const Vector2 linearVelocityDelta = linearVelocity * linearDrag; // Set linear velocity. pSceneObject->setLinearVelocity( linearVelocity - linearVelocityDelta ); } // Angular drag? if ( angularDrag > 0.0f ) { // Yes, so fetch angular velocity. F32 angularVelocity = pSceneObject->getAngularVelocity(); // Calculate angular velocity change. const F32 angularVelocityDelta = angularVelocity * angularDrag; // Set angular velocity. pSceneObject->setAngularVelocity( angularVelocity - angularVelocityDelta ); } } } //------------------------------------------------------------------------------ void PointForceController::renderOverlay( Scene* pScene, const SceneRenderState* pSceneRenderState, BatchRender* pBatchRenderer ) { // Call parent. Parent::renderOverlay( pScene, pSceneRenderState, pBatchRenderer ); // Draw force radius. pScene->mDebugDraw.DrawCircle( getCurrentPosition(), mRadius, ColorF(1.0f, 1.0f, 0.0f ) ); }
0
0.672665
1
0.672665
game-dev
MEDIA
0.893843
game-dev
0.912368
1
0.912368
Auviotre/Enigmatic-Addons
6,370
src/main/java/auviotre/enigmatic/addon/handlers/OmniconfigAddonHandler.java
package auviotre.enigmatic.addon.handlers; import auviotre.enigmatic.addon.EnigmaticAddons; import auviotre.enigmatic.addon.helpers.MixinOmniconfigHelper; import com.aizistral.enigmaticlegacy.api.items.IPerhaps; import com.aizistral.enigmaticlegacy.handlers.SuperpositionHandler; import com.aizistral.omniconfig.Configuration; import com.aizistral.omniconfig.wrappers.Omniconfig; import com.aizistral.omniconfig.wrappers.OmniconfigWrapper; import com.google.common.base.Objects; import com.google.common.collect.Multimap; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class OmniconfigAddonHandler { public static final Map<Field, Omniconfig.BooleanParameter> ITEMS_OPTIONS = new HashMap<>(); public static Omniconfig.BooleanParameter frostParticle; public static Omniconfig.BooleanParameter etheriumShieldIcon; public static Omniconfig.BooleanParameter EnableCurseBoost; public static Omniconfig.BooleanParameter ImmediatelyCurseBoost; public static Omniconfig.BooleanParameter NearDeathAnger; public static Omniconfig.BooleanParameter TabResorted; public static Omniconfig.BooleanParameter FutureItemDisplay; public static Omniconfig.BooleanParameter HiddenRecipeJEIDisplay; public static boolean isItemEnabled(Object item) { if (item == null) { return false; } else { for (Field optionalItemField : ITEMS_OPTIONS.keySet()) { try { if (optionalItemField.get(null) != null) { Object optionalItem = optionalItemField.get(null); if (Objects.equal(item, optionalItem) && ITEMS_OPTIONS.get(optionalItemField) != null) { return ITEMS_OPTIONS.get(optionalItemField).getValue(); } } } catch (Exception exception) { exception.printStackTrace(); } } return !(item instanceof IPerhaps) || ((IPerhaps) item).isForMortals(); } } public static void initialize() { OmniconfigWrapper configBuilder = OmniconfigWrapper.setupBuilder("enigmaticaddons-common", true, "1.2.5.2"); configBuilder.pushVersioningPolicy(Configuration.VersioningPolicy.AGGRESSIVE); configBuilder.pushTerminateNonInvokedKeys(true); loadCommon(configBuilder); configBuilder.setReloadable(); OmniconfigWrapper clientBuilder = OmniconfigWrapper.setupBuilder("enigmaticaddons-client", true, "1.2.5.2"); clientBuilder.pushSidedType(Configuration.SidedConfigType.CLIENT); clientBuilder.pushVersioningPolicy(Configuration.VersioningPolicy.AGGRESSIVE); clientBuilder.pushTerminateNonInvokedKeys(true); loadClient(clientBuilder); clientBuilder.setReloadable(); } private static void loadClient(OmniconfigWrapper client) { client.loadConfigFile(); client.pushCategory("Generic Config", "Some more different stuff"); frostParticle = client.comment("If false, disables the particle effect for fully frozen entities.").clientOnly().getBoolean("CustomFrostParticle", true); etheriumShieldIcon = client.comment("If false, disables the icon display of the Etherium Shield.").clientOnly().getBoolean("EtheriumShieldIconDisplay", true); client.popCategory(); client.build(); } private static void loadCommon(OmniconfigWrapper builder) { builder.loadConfigFile(); builder.forceSynchronized(true); builder.pushCategory("Accessibility Options", "You may disable certain items or features from being obtainable/usable here." + System.lineSeparator() + "Check more details in Enigmatic Legacy's Config Files."); Multimap<String, Field> accessibilityGeneratorMap = SuperpositionHandler.retainAccessibilityGeneratorMap(EnigmaticAddons.MODID); ITEMS_OPTIONS.clear(); for (String itemName : accessibilityGeneratorMap.keySet()) { String optionName = itemName.replaceAll("[^a-zA-Z0-9]", "") + "Enabled"; Omniconfig.BooleanParameter param = builder.comment("Whether or not " + itemName + " should be enabled.").getBoolean(optionName, true); for (Field associatedField : accessibilityGeneratorMap.get(itemName)) { ITEMS_OPTIONS.put(associatedField, param); } } builder.popCategory(); builder.forceSynchronized(true); builder.pushCategory("Balance Options", "Various options that mostly affect individual items"); SuperpositionHandler.dispatchWrapperToHolders(EnigmaticAddons.MODID, builder); builder.popCategory(); builder.forceSynchronized(true); builder.pushCategory("Legacy Balance Options", "Various options that mostly affect Enigmatic Legacy's items"); builder.pushPrefix(""); MixinOmniconfigHelper.MixConfig(builder); builder.popCategory(); builder.forceSynchronized(true); builder.pushCategory("The Worthy One Options", "Various options that about the Events related to The Worthy One."); EnableCurseBoost = builder.comment("If true, When the proportion of curse time is long enough, there will be some changes in creatures' AI.").getBoolean("EnableCurseBoost", true); ImmediatelyCurseBoost = builder.comment("If true, when a creature spawned, it will immediately gain Curse Boost.").getBoolean("ImmediatelyCurseBoost", false); NearDeathAnger = builder.comment("If true, when a creature dies, it will anger its surrounding peers.").getBoolean("PartnerAnger", true); builder.popCategory(); builder.forceSynchronized(false); builder.pushCategory("Else Options", "Various options that relates to secondary contents."); TabResorted = builder.comment("If true, the main creative tab of Enigmatic Legacy will be resorted.").getBoolean("TabResorted", true); FutureItemDisplay = builder.comment("If true, the main creative tab of Enigmatic Legacy will display some uncompleted item.").getBoolean("FutureItemDisplay", false); HiddenRecipeJEIDisplay = builder.comment("If true, the Hidden Recipe will display in JEI.").getBoolean("HiddenRecipeJEIDisplay", true); builder.popCategory(); builder.build(); } }
0
0.926575
1
0.926575
game-dev
MEDIA
0.660812
game-dev
0.977225
1
0.977225
Kromtec/LegendsViewer
66,225
LegendsViewer/Controls/Map/MapPanel.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Windows.Forms; using LegendsViewer.Legends; using LegendsViewer.Legends.EventCollections; using LegendsViewer.Legends.Interfaces; using LegendsViewer.Legends.WorldObjects; using SevenZip; namespace LegendsViewer.Controls.Map { public class MapPanel : Panel { public DwarfTabControl TabControl; Bitmap _map, _minimap; public Bitmap AlternateMap, Overlay; //Size MinimapSize; public object FocusObject; List<object> _focusObjects; World _world; List<object> _displayObjects; public Point MousePanStart, Center, MouseClickLocation, MouseLocation; public Rectangle Source; Rectangle _zoomBounds; public double ZoomCurrent = 1; public double PixelWidth, PixelHeight, ZoomChange = 0.15, ZoomMax = 10.0, ZoomMin = 0.2; MapMenu _hoverMenu, _controlMenu, _yearMenu; MapMenuHorizontal _optionsMenu; public bool ZoomToBoundsOnFirstPaint, CivsToggled, SitesToggled, WarsToggled, BattlesToggled, OverlayToggled, AlternateMapToggled; public int TileSize = 16, MinYear, MaxYear, CurrentYear, MiniMapAreaSideLength = 200; List<CivPaths> _allCivPaths = new List<CivPaths>(); List<Entity> _warEntities = new List<Entity>(); List<Battle> _battles = new List<Battle>(); List<Location> _battleLocations = new List<Location>(); TrackBar _altMapTransparency = new TrackBar(); float _altMapAlpha = 1.0f; public MapPanel(Bitmap map, World world, DwarfTabControl dwarfTabControl, object focusObject) { TabControl = dwarfTabControl; _map = map; _world = world; FocusObject = focusObject; if (FocusObject != null && FocusObject.GetType() == typeof(World)) { FocusObject = null; } _displayObjects = new List<object>(); DoubleBuffered = true; Dock = DockStyle.Fill; Source = new Rectangle(new Point(Center.X - Width / 2, Center.Y - Height / 2), new Size(Width, Height)); _hoverMenu = new MapMenu(this); _controlMenu = new MapMenu(this); _controlMenu.AddOptions(new List<object> { "Zoom In", "Zoom Out", "Toggle Civs", "Toggle Sites", "Toggle Wars", "Toggle Battles", "Toggle Overlay", "Toggle Alt Map" }); _controlMenu.Open = true; _yearMenu = new MapMenu(this); _yearMenu.AddOptions(new List<object> { "+1000", "+100", "+10", "+1", "-1", "-10", "-100", "-1000" }); _yearMenu.Open = true; _optionsMenu = new MapMenuHorizontal(this) { Open = true }; _optionsMenu.AddOptions(new List<object> { "Load Alternate Map...", "Export Map...", "Overlays" }); MapMenu overlayOptions = new MapMenu(this); overlayOptions.AddOptions(new List<object> { "Battles", "Battles (Notable)", "Battle Deaths", "Beast Attacks", "Site Population...", "Site Events", "Site Events (Filtered)" }); overlayOptions.Options.ForEach(option => option.OptionObject = "Overlay"); _optionsMenu.Options.Last().SubMenu = overlayOptions; _altMapTransparency.Minimum = 0; _altMapTransparency.Maximum = 100; _altMapTransparency.AutoSize = false; _altMapTransparency.Size = new Size(150, 25); _altMapTransparency.TickFrequency = 1; _altMapTransparency.TickStyle = TickStyle.None; _altMapTransparency.BackColor = _yearMenu.MenuColor; _altMapTransparency.Visible = false; _altMapTransparency.Scroll += ChangeAltMapTransparency; _altMapTransparency.Value = 100; Controls.Add(_altMapTransparency); _altMapTransparency.Location = new Point(MiniMapAreaSideLength + _yearMenu.MenuBox.Width, Height - _altMapTransparency.Height); MinYear = _world.Eras.First().StartYear; if (MinYear == -1) { MinYear = 0; } MaxYear = CurrentYear = _world.Eras.Last().EndYear; //Set Map Year if Entity has no active sites so they show on map if (FocusObject != null && FocusObject.GetType() == typeof(Entity) && ((Entity)FocusObject).SiteHistory.Count(sitePeriod => sitePeriod.EndYear == -1) == 0) { CurrentYear = (FocusObject as Entity).SiteHistory.Max(sitePeriod => sitePeriod.EndYear) - 1; } else if (FocusObject != null && FocusObject.GetType() == typeof(Battle)) { CurrentYear = MinYear = MaxYear = ((Battle)focusObject).StartYear; } else if (FocusObject != null && FocusObject.GetType() == typeof(SiteConquered)) { CurrentYear = MinYear = MaxYear = ((SiteConquered)FocusObject).StartYear; } if (focusObject != null && focusObject.GetType() == typeof(List<object>)) { _focusObjects = ((List<object>)focusObject).GroupBy(item => item).Select(item => item.Key).ToList(); if (_focusObjects.First().GetType() == typeof(Battle)) { _battles.AddRange(_focusObjects.Cast<Battle>()); } else { _displayObjects.AddRange(_focusObjects); } } else { _focusObjects = new List<object>(); } if (focusObject != null && focusObject.GetType() != typeof(Battle)) { _displayObjects.Add(focusObject); } if (focusObject != null && focusObject.GetType() == typeof(Battle)) { _battles.Add(focusObject as Battle); } if (FocusObject != null && FocusObject.GetType() == typeof(War)) { if (FocusObject is War war) { MinYear = CurrentYear = war.StartYear; if (war.EndYear != -1) { MaxYear = war.EndYear; } UpdateWarDisplay(); foreach (Battle battle in war.Collections.OfType<Battle>()) { _battles.Add(battle); } } } //Center and zoom map on focusObject of the map if (FocusObject == null || _focusObjects.Count > 0) { Center = new Point(_map.Width / 2, _map.Height / 2); } else if (FocusObject.GetType() == typeof(Site)) { Site site = focusObject as Site; Center = new Point(site.Coordinates.X * TileSize + TileSize / 2, site.Coordinates.Y * TileSize + TileSize / 2); ZoomCurrent = 0.85; } else if (FocusObject.GetType() == typeof(Artifact)) { Artifact artifact = focusObject as Artifact; Center = new Point(artifact.Coordinates.X * TileSize + TileSize / 2, artifact.Coordinates.Y * TileSize + TileSize / 2); ZoomCurrent = 0.85; } else if (FocusObject.GetType() == typeof(Entity) || FocusObject.GetType() == typeof(War) || FocusObject.GetType() == typeof(Battle) || FocusObject.GetType() == typeof(SiteConquered) || FocusObject.GetType() == typeof(WorldRegion) || FocusObject.GetType() == typeof(UndergroundRegion) || FocusObject.GetType() == typeof(WorldConstruction) || FocusObject.GetType() == typeof(Landmass) || FocusObject.GetType() == typeof(MountainPeak) || FocusObject.GetType() == typeof(River)) { List<Entity> entities = new List<Entity>(); if (FocusObject.GetType() == typeof(Entity)) { entities.Add(FocusObject as Entity); } else if (FocusObject.GetType() == typeof(War)) { entities.Add((FocusObject as War).Attacker); entities.Add((FocusObject as War).Defender); } _zoomBounds = new Rectangle(-1, -1, -1, -1); foreach (Entity displayEntity in entities) { foreach (OwnerPeriod sitePeriod in displayEntity.SiteHistory.Where(ownerPeriod => ownerPeriod.StartYear <= CurrentYear && ownerPeriod.EndYear >= CurrentYear || ownerPeriod.EndYear == -1)) { if (_zoomBounds.Top == -1) { _zoomBounds.Y = _zoomBounds.Height = sitePeriod.Site.Coordinates.Y; _zoomBounds.X = _zoomBounds.Width = sitePeriod.Site.Coordinates.X; } if (sitePeriod.Site.Coordinates.Y < _zoomBounds.Y) { _zoomBounds.Y = sitePeriod.Site.Coordinates.Y; } if (sitePeriod.Site.Coordinates.X < _zoomBounds.X) { _zoomBounds.X = sitePeriod.Site.Coordinates.X; } if (sitePeriod.Site.Coordinates.Y > _zoomBounds.Height) { _zoomBounds.Height = sitePeriod.Site.Coordinates.Y; } if (sitePeriod.Site.Coordinates.X > _zoomBounds.Width) { _zoomBounds.Width = sitePeriod.Site.Coordinates.X; } } } if (FocusObject.GetType() == typeof(War)) { War war = FocusObject as War; foreach (Battle battle in war.Collections.OfType<Battle>()) { if (_zoomBounds.Top == -1) { _zoomBounds.Y = _zoomBounds.Height = battle.Coordinates.Y; _zoomBounds.X = _zoomBounds.Width = battle.Coordinates.X; } if (battle.Coordinates.Y < _zoomBounds.Y) { _zoomBounds.Y = battle.Coordinates.Y; } if (battle.Coordinates.X < _zoomBounds.X) { _zoomBounds.X = battle.Coordinates.X; } if (battle.Coordinates.Y > _zoomBounds.Height) { _zoomBounds.Height = battle.Coordinates.Y; } if (battle.Coordinates.X > _zoomBounds.Width) { _zoomBounds.Width = battle.Coordinates.X; } } } if (FocusObject.GetType() == typeof(Battle) || FocusObject.GetType() == typeof(SiteConquered)) { Battle battle; if (FocusObject.GetType() == typeof(Battle)) { battle = FocusObject as Battle; } else { battle = (FocusObject as SiteConquered).Battle; } Center = new Point(battle.Coordinates.X * TileSize + TileSize / 2, battle.Coordinates.Y * TileSize + TileSize / 2); _zoomBounds.Y = _zoomBounds.Height = battle.Coordinates.Y; _zoomBounds.X = _zoomBounds.Width = battle.Coordinates.X; Site attackerSite = GetClosestSite(battle.Attacker, battle.Coordinates); if (attackerSite != null) { if (attackerSite.Coordinates.Y < _zoomBounds.Y) { _zoomBounds.Y = attackerSite.Coordinates.Y; } if (attackerSite.Coordinates.X < _zoomBounds.X) { _zoomBounds.X = attackerSite.Coordinates.X; } if (attackerSite.Coordinates.Y > _zoomBounds.Height) { _zoomBounds.Height = attackerSite.Coordinates.Y; } if (attackerSite.Coordinates.X > _zoomBounds.Width) { _zoomBounds.Width = attackerSite.Coordinates.X; } } Site defenderSite = GetClosestSite(battle.Defender, battle.Coordinates); if (defenderSite != null) { if (defenderSite.Coordinates.Y < _zoomBounds.Y) { _zoomBounds.Y = defenderSite.Coordinates.Y; } if (defenderSite.Coordinates.X < _zoomBounds.X) { _zoomBounds.X = defenderSite.Coordinates.X; } if (defenderSite.Coordinates.Y > _zoomBounds.Height) { _zoomBounds.Height = defenderSite.Coordinates.Y; } if (defenderSite.Coordinates.X > _zoomBounds.Width) { _zoomBounds.Width = defenderSite.Coordinates.X; } } } if (FocusObject is IHasCoordinates) { _zoomBounds.X = (FocusObject as IHasCoordinates).Coordinates.Min(coord => coord.X); _zoomBounds.Y = (FocusObject as IHasCoordinates).Coordinates.Min(coord => coord.Y); _zoomBounds.Width = (FocusObject as IHasCoordinates).Coordinates.Max(coord => coord.X); _zoomBounds.Height = (FocusObject as IHasCoordinates).Coordinates.Max(coord => coord.Y); } _zoomBounds.X = _zoomBounds.X * TileSize - TileSize / 2 - TileSize; _zoomBounds.Width = _zoomBounds.Width * TileSize + TileSize / 2 + TileSize; _zoomBounds.Y = _zoomBounds.Y * TileSize - TileSize / 2 - TileSize; _zoomBounds.Height = _zoomBounds.Height * TileSize + TileSize / 2 + TileSize; Center.X = (_zoomBounds.Left + _zoomBounds.Width) / 2; Center.Y = (_zoomBounds.Top + _zoomBounds.Height) / 2; ZoomToBoundsOnFirstPaint = true; } else { Center = new Point(0, 0); } _battleLocations = _battles.GroupBy(battle => battle.Coordinates).Select(battle => battle.Key).ToList(); GenerateCivPaths(); _minimap = world.MiniMap; UpdateWarDisplay(); Invalidate(); if (MapUtil.AlternateMap != null) { AlternateMap = MapUtil.AlternateMap; _altMapAlpha = MapUtil.AltMapAlpha; _altMapTransparency.Value = (int)(_altMapAlpha * 100); AlternateMapToggled = false; ToggleAlternateMap(); } } private class CivPaths { public Entity Civ; public List<List<Site>> SitePaths; } protected override void OnPaint(PaintEventArgs e) { if (ZoomToBoundsOnFirstPaint) { ZoomToBounds(); } e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor; e.Graphics.PixelOffsetMode = PixelOffsetMode.Half; DrawMap(e.Graphics); DrawDisplayObjects(e.Graphics); DrawOverlay(e.Graphics); _controlMenu.Draw(e.Graphics); _yearMenu.Draw(e.Graphics); _optionsMenu.Draw(e.Graphics); DrawInfo(e.Graphics); DrawMiniMap(e.Graphics); if (_hoverMenu.Options.Count > 0) { _hoverMenu.Draw(e.Graphics); } } private void DrawMap(Graphics g, bool originalSize = false) { if (!originalSize) { g.FillRectangle(new SolidBrush(Color.FromArgb(0, 0, 50)), new Rectangle(Location, Size)); } if (AlternateMapToggled && _altMapAlpha > 0) { if (_altMapAlpha < 1) { g.DrawImage(_map, originalSize ? getOriginalSize(_map) : ClientRectangle, originalSize ? getOriginalSize(_map) : Source, GraphicsUnit.Pixel); using (ImageAttributes adjustAlpha = new ImageAttributes()) { ColorMatrix adjustAlphaMatrix = new ColorMatrix(); adjustAlphaMatrix.Matrix00 = adjustAlphaMatrix.Matrix11 = adjustAlphaMatrix.Matrix22 = adjustAlphaMatrix.Matrix44 = 1.0f; adjustAlphaMatrix.Matrix33 = _altMapAlpha; adjustAlpha.SetColorMatrix(adjustAlphaMatrix); if (originalSize) { g.DrawImage(AlternateMap, getOriginalSize(AlternateMap), 0, 0, AlternateMap.Width, AlternateMap.Height, GraphicsUnit.Pixel, adjustAlpha); } else { g.DrawImage(AlternateMap, ClientRectangle, Source.X, Source.Y, Source.Width, Source.Height, GraphicsUnit.Pixel, adjustAlpha); } } } else { g.DrawImage(AlternateMap, originalSize ? getOriginalSize(AlternateMap) : ClientRectangle, originalSize ? getOriginalSize(AlternateMap) : Source, GraphicsUnit.Pixel); } } else { g.DrawImage(_map, originalSize ? getOriginalSize(_map) : ClientRectangle, originalSize ? getOriginalSize(_map) : Source, GraphicsUnit.Pixel); } } private Rectangle getOriginalSize(Bitmap map) { return new Rectangle(0, 0, map.Width, map.Height); } private void DrawMiniMap(Graphics g) { double minimapRatio; if (_map.Width > _map.Height) { minimapRatio = Convert.ToDouble(_minimap.Width) / Convert.ToDouble(_map.Width); } else { minimapRatio = Convert.ToDouble(_minimap.Height) / Convert.ToDouble(_map.Height); } Rectangle minimapArea = new Rectangle(0, Height - MiniMapAreaSideLength, MiniMapAreaSideLength, MiniMapAreaSideLength); Point miniMapDrawLocation = new Point(minimapArea.X + MiniMapAreaSideLength / 2 - _minimap.Width / 2, minimapArea.Y + MiniMapAreaSideLength / 2 - _minimap.Height / 2); g.FillRectangle(new SolidBrush(Color.FromArgb(0, 0, 50)), minimapArea); g.DrawImage(_minimap, new Rectangle(miniMapDrawLocation.X, miniMapDrawLocation.Y, _minimap.Width, _minimap.Height), new Rectangle(0, 0, _minimap.Width, _minimap.Height), GraphicsUnit.Pixel); Point miniSourceLocation = new Point(miniMapDrawLocation.X + Convert.ToInt32(Source.X * minimapRatio), miniMapDrawLocation.Y + Convert.ToInt32(Source.Y * minimapRatio)); Size miniSourceSize = new Size(Convert.ToInt32(Source.Width * minimapRatio), Convert.ToInt32(Source.Height * minimapRatio)); Rectangle miniSource = new Rectangle(miniSourceLocation, miniSourceSize); if (miniSource.Left < minimapArea.Left) { miniSource.Width -= minimapArea.Left - miniSource.Left; miniSource.X = minimapArea.Left; } if (miniSource.Top < minimapArea.Top) { miniSource.Height -= minimapArea.Top - miniSource.Top; miniSource.Y = minimapArea.Top; } if (miniSource.Right > minimapArea.Right) { miniSource.Width = minimapArea.X + _minimap.Width - miniSource.X; } if (miniSource.Bottom > minimapArea.Bottom) { miniSource.Height = minimapArea.Y + _minimap.Height - miniSource.Y; } g.SmoothingMode = SmoothingMode.None; g.PixelOffsetMode = PixelOffsetMode.Default; using (Pen minimapPen = new Pen(Color.White)) { g.DrawRectangle(minimapPen, miniSource); } } public void DrawDisplayObjects(Graphics g, bool originalSize = false) { g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.Half; DrawEntities(g, _displayObjects.OfType<Entity>().ToList(), originalSize); DrawCivPaths(g, originalSize); Rectangle rectangle = originalSize ? getOriginalSize(_map) : Source; SizeF scaleTileSize = new SizeF((float)(PixelWidth * TileSize), (float)(PixelHeight * TileSize)); foreach (Site site in _displayObjects.OfType<Site>()) { PointF siteLocation = new PointF { X = (float)((site.Coordinates.X * TileSize - rectangle.X) * PixelWidth), Y = (float)((site.Coordinates.Y * TileSize - rectangle.Y) * PixelHeight) }; using (Pen sitePen = new Pen(Color.White)) { g.DrawRectangle(sitePen, siteLocation.X, siteLocation.Y, scaleTileSize.Width, scaleTileSize.Height); } } foreach (var battle in _battleLocations) { PointF battleLocation = new PointF { X = (float)((battle.X * TileSize - rectangle.X) * PixelWidth), Y = (float)((battle.Y * TileSize - rectangle.Y) * PixelHeight) }; using (Pen battlePen = new Pen(Color.FromArgb(175, Color.White), 2)) { g.DrawEllipse(battlePen, battleLocation.X, battleLocation.Y, scaleTileSize.Width, scaleTileSize.Height); } } foreach (War war in _displayObjects.OfType<War>().Where(war => war.StartYear <= CurrentYear && (war.EndYear >= CurrentYear || war.EndYear == -1))) { foreach (Battle battle in war.Collections.OfType<Battle>().Where(battle => battle.StartYear == CurrentYear)) { DrawBattlePaths(g, battle, originalSize); } } if (FocusObject is IHasCoordinates coordinates) { float margin = (float)(4 * PixelWidth); if (coordinates.GetType() == typeof(Landmass)) { PointF startloc = new PointF { X = (float)((coordinates.Coordinates[0].X * TileSize - rectangle.X) * PixelWidth), Y = (float)((coordinates.Coordinates[0].Y * TileSize - rectangle.Y) * PixelHeight) }; PointF endloc = new PointF { X = (float)((coordinates.Coordinates[1].X * TileSize - rectangle.X) * PixelWidth), Y = (float)((coordinates.Coordinates[1].Y * TileSize - rectangle.Y) * PixelHeight) }; using (Pen pen = new Pen(Color.FromArgb(255, Color.White), 2)) { g.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.White)), startloc.X, startloc.Y, endloc.X - startloc.X + scaleTileSize.Width, endloc.Y - startloc.Y + scaleTileSize.Height); g.DrawRectangle(pen, startloc.X, startloc.Y, endloc.X - startloc.X + scaleTileSize.Width, endloc.Y - startloc.Y + scaleTileSize.Height); } } else { foreach (Location coord in coordinates.Coordinates) { PointF loc = new PointF { X = (float)((coord.X * TileSize - rectangle.X) * PixelWidth), Y = (float)((coord.Y * TileSize - rectangle.Y) * PixelHeight) }; using (Pen pen = new Pen(Color.FromArgb(255, Color.White), 2)) { if (coordinates.GetType() == typeof(WorldRegion)) { g.FillRectangle(new SolidBrush(Color.LightGreen), loc.X + margin, loc.Y + margin, scaleTileSize.Width - 2 * margin, scaleTileSize.Height - 2 * margin); } else if (coordinates.GetType() == typeof(UndergroundRegion)) { g.FillRectangle(new SolidBrush(Color.SandyBrown), loc.X + margin, loc.Y + margin, scaleTileSize.Width - 2 * margin, scaleTileSize.Height - 2 * margin); } else if (coordinates.GetType() == typeof(WorldConstruction)) { g.FillRectangle(new SolidBrush(Color.Gold), loc.X + margin, loc.Y + margin, scaleTileSize.Width - 2 * margin, scaleTileSize.Height - 2 * margin); } else if (coordinates.GetType() == typeof(MountainPeak)) { g.FillRectangle(new SolidBrush(Color.CornflowerBlue), loc.X + margin, loc.Y + margin, scaleTileSize.Width - 2 * margin, scaleTileSize.Height - 2 * margin); } g.DrawRectangle(pen, loc.X + margin, loc.Y + margin, scaleTileSize.Width - 2 * margin, scaleTileSize.Height - 2 * margin); } } } } if (FocusObject != null && FocusObject.GetType() == typeof(Battle)) { DrawBattlePaths(g, FocusObject as Battle); } if (FocusObject != null && FocusObject.GetType() == typeof(SiteConquered)) { DrawBattlePaths(g, ((SiteConquered)FocusObject).Battle); } } private void DrawOverlay(Graphics g, bool originalSize = false) { g.SmoothingMode = SmoothingMode.None; g.InterpolationMode = InterpolationMode.NearestNeighbor; if (OverlayToggled) { g.DrawImage(Overlay, originalSize ? getOriginalSize(_map) : ClientRectangle, originalSize ? getOriginalSize(_map) : Source, GraphicsUnit.Pixel); } } private void DrawEntities(Graphics g, List<Entity> entities, bool originalSize = false) { var rectangle = originalSize ? getOriginalSize(_map) : Source; SizeF scaleTileSize = new SizeF((float)PixelWidth * TileSize, (float)PixelHeight * TileSize); g.InterpolationMode = InterpolationMode.Default; g.PixelOffsetMode = PixelOffsetMode.Half; foreach (Site site in entities.SelectMany(entity => entity.Sites).Distinct()) { PointF siteLocation = new PointF { X = (float)((site.Coordinates.X * TileSize - rectangle.X) * PixelWidth), Y = (float)((site.Coordinates.Y * TileSize - rectangle.Y) * PixelHeight) }; OwnerPeriod ownerPeriod = site.OwnerHistory.LastOrDefault(op => op.StartYear <= CurrentYear && (op.EndYear >= CurrentYear || op.EndYear == -1)); Entity entity = ownerPeriod?.Owner as Entity; if (entity == null) { continue; } if (ownerPeriod.EndYear != -1 && ownerPeriod.EndYear <= CurrentYear) { ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix(new ColorMatrix { Matrix00 = 0.66f, Matrix11 = 0.66f, Matrix22 = 0.66f, Matrix33 = 1.00f, Matrix44 = 0.66f }); using (Bitmap lostSiteIdenticon = new Bitmap(entity.Identicon.Width, entity.Identicon.Height)) { using (Graphics drawLostSite = Graphics.FromImage(lostSiteIdenticon)) { drawLostSite.DrawImage(entity.Identicon, new Rectangle(0, 0, entity.Identicon.Width, entity.Identicon.Height), 0, 0, entity.Identicon.Width, entity.Identicon.Height, GraphicsUnit.Pixel, imageAttributes); } g.DrawImage(lostSiteIdenticon, new RectangleF(siteLocation.X, siteLocation.Y, scaleTileSize.Width + 1, scaleTileSize.Height + 1)); } } else { g.DrawImage(entity.Identicon, new RectangleF(siteLocation.X, siteLocation.Y, scaleTileSize.Width + 1, scaleTileSize.Height + 1)); } } } private void DrawBattlePaths(Graphics g, Battle battle, bool originalSize = false) { using (Pen attackerLine = new Pen(Color.Black, 3)) using (Pen defenderLine = new Pen(Color.Black, 3)) using (AdjustableArrowCap victorCap = new AdjustableArrowCap(4, 6)) using (AdjustableArrowCap loserCap = new AdjustableArrowCap(5, 6)) { attackerLine.DashStyle = DashStyle.Dot; defenderLine.DashStyle = DashStyle.Dot; loserCap.Filled = false; Site attackerSite = GetClosestSite(battle.Attacker, battle.Coordinates); Site defenderSite = GetClosestSite(battle.Defender, battle.Coordinates); attackerLine.Color = battle.Attacker.LineColor; defenderLine.Color = battle.Defender.LineColor; if (battle.Victor == battle.Attacker) { attackerLine.CustomEndCap = victorCap; defenderLine.CustomEndCap = loserCap; } else if (battle.Victor == battle.Defender) { attackerLine.CustomEndCap = loserCap; defenderLine.CustomEndCap = victorCap; } g.DrawLine(attackerLine, SiteToScreen(attackerSite.Coordinates, originalSize), SiteToScreen(battle.Coordinates, originalSize)); if (defenderSite != null && defenderSite.Coordinates != battle.Coordinates) { g.DrawLine(defenderLine, SiteToScreen(defenderSite.Coordinates, originalSize), SiteToScreen(battle.Coordinates, originalSize)); } } } private void DrawCivPaths(Graphics g, bool originalSize = false) { g.SmoothingMode = SmoothingMode.AntiAlias; foreach (CivPaths civPaths in _allCivPaths) { foreach (List<Site> path in civPaths.SitePaths) { Site site1 = path.First(); Site site2 = path.Last(); Size tileDistance = new Size(site1.Coordinates.X - site2.Coordinates.X, site1.Coordinates.Y - site2.Coordinates.Y); if (tileDistance.Width < 0) { tileDistance.Width *= -1; } if (tileDistance.Height < 0) { tileDistance.Height *= -1; } if (tileDistance.Width > 1 || tileDistance.Height > 1) { using (Pen pathPen = new Pen(civPaths.Civ.LineColor, 2)) { g.DrawLine(pathPen, SiteToScreen(site1.Coordinates, originalSize), SiteToScreen(site2.Coordinates, originalSize)); } } } } } private void DrawInfo(Graphics g) { Point tileLocation = WindowToTilePoint(MouseLocation); Font font = new Font("Arial", 10); Brush fontBrush = new SolidBrush(Color.Gray); Brush boxBrush = new SolidBrush(Color.FromArgb(200, Color.Black)); SizeF tileInfoSize = g.MeasureString(tileLocation.X + ", " + tileLocation.Y, font); Rectangle tileInfoBox = new Rectangle(_controlMenu.MenuBox.Width, Height - _minimap.Height - Convert.ToInt32(tileInfoSize.Height), 70, Convert.ToInt32(tileInfoSize.Height)); g.FillRectangle(boxBrush, tileInfoBox); g.DrawString(tileLocation.X + ", " + tileLocation.Y, font, fontBrush, new Point(tileInfoBox.X + 3, tileInfoBox.Y)); SizeF yearBoxSize = g.MeasureString(CurrentYear.ToString(), font); Rectangle yearBox = new Rectangle(_minimap.Width, Height - _yearMenu.MenuBox.Height - Convert.ToInt32(yearBoxSize.Height), _yearMenu.MenuBox.Width, Convert.ToInt32(yearBoxSize.Height)); g.FillRectangle(boxBrush, yearBox); g.DrawString(CurrentYear.ToString(), font, fontBrush, new Point(yearBox.X + 3, yearBox.Y)); font.Dispose(); fontBrush.Dispose(); boxBrush.Dispose(); } public void ToggleCivs() { bool reToggleWars = false; if (WarsToggled) { ToggleWars(); reToggleWars = true; } if (!CivsToggled) { _displayObjects.AddRange(_world.Entities.Where(entity => entity.IsCiv && entity != FocusObject && !_displayObjects.Contains(entity))); CivsToggled = true; } else { _displayObjects.RemoveAll(dwarfObject => dwarfObject.GetType() == typeof(Entity) && dwarfObject != FocusObject && !_warEntities.Contains(dwarfObject)); CivsToggled = false; } _controlMenu.Options.Single(option => option.Text == "Toggle Civs").Toggled = CivsToggled; GenerateCivPaths(); if (reToggleWars) { ToggleWars(); } Invalidate(); } public void ToggleSites() { if (!SitesToggled) { _displayObjects.AddRange(_world.Sites.Where(site => site != FocusObject)); SitesToggled = true; } else { _displayObjects.RemoveAll(dwarfObject => dwarfObject.GetType() == typeof(Site) && dwarfObject != FocusObject && !_focusObjects.Contains(dwarfObject)); SitesToggled = false; } _controlMenu.Options.Single(option => option.Text == "Toggle Sites").Toggled = SitesToggled; Invalidate(); } public void ToggleWars() { if (!WarsToggled) { List<War> displayWars = new List<War>(); foreach (Entity entity in _displayObjects.OfType<Entity>()) { foreach (War war in entity.Wars) { displayWars.Add(war); } } foreach (War war in displayWars) { if (!_displayObjects.Contains(war) && war != FocusObject) { _displayObjects.Add(war); } } WarsToggled = true; } else { _displayObjects.RemoveAll(displayObject => displayObject.GetType() == typeof(War) && displayObject != FocusObject); WarsToggled = false; } UpdateWarDisplay(); _controlMenu.Options.Single(option => option.Text == "Toggle Wars").Toggled = WarsToggled; Invalidate(); } public void ToggleBattles() { if (!BattlesToggled) { //DisplayObjects.AddRange(World.EventCollections.OfType<Battle>().Where(battle => !DisplayObjects.Contains(battle) && battle != FocusObject)); _battles.AddRange(_world.EventCollections.OfType<Battle>().Where(battle => !_displayObjects.Contains(battle) && battle != FocusObject && !_focusObjects.Contains(battle))); _battleLocations = _battles.GroupBy(battle => battle.Coordinates).Select(battle => battle.Key).ToList(); BattlesToggled = true; } else { //DisplayObjects.RemoveAll(displayObject => displayObject.GetType() == typeof(Battle) && displayObject != FocusObject); _battles.Clear(); if (_focusObjects.Count > 0 && _focusObjects.First().GetType() == typeof(Battle)) { _battles.AddRange(_focusObjects.Cast<Battle>()); } if (FocusObject != null && FocusObject.GetType() == typeof(Battle)) { _battles.Add(FocusObject as Battle); } if (FocusObject != null && FocusObject.GetType() == typeof(War)) { //DisplayObjects.AddRange((FocusObject as War).Collections.OfType<Battle>()); _battles.AddRange(((War)FocusObject).Collections.OfType<Battle>()); } //BattleLocations = DisplayObjects.OfType<Battle>().GroupBy(battle => battle.Coordinates).Select(battle => battle.Key).ToList(); _battleLocations = _battles.GroupBy(battle => battle.Coordinates).Select(battle => battle.Key).ToList(); BattlesToggled = false; } _controlMenu.Options.Single(option => option.Text == "Toggle Battles").Toggled = BattlesToggled; Invalidate(); } public void ToggleOverlay() { if (Overlay != null) { OverlayToggled = !OverlayToggled; Invalidate(); } _controlMenu.Options.Single(option => option.Text == "Toggle Overlay").Toggled = OverlayToggled; } public void ToggleAlternateMap() { if (AlternateMap != null) { AlternateMapToggled = !AlternateMapToggled; Invalidate(); } _controlMenu.Options.Single(option => option.Text == "Toggle Alt Map").Toggled = AlternateMapToggled; _altMapTransparency.Visible = AlternateMapToggled; } public void GenerateCivPaths() { _allCivPaths = new List<CivPaths>(); foreach (Entity civ in _displayObjects.OfType<Entity>()) { CivPaths civPaths = new CivPaths { Civ = civ, SitePaths = PathMaker.Create(civ, CurrentYear) }; _allCivPaths.Add(civPaths); } } public void ChangeYear(int amount) { CurrentYear += amount; if (CurrentYear > MaxYear) { CurrentYear = MaxYear; } if (CurrentYear < MinYear) { CurrentYear = MinYear; } UpdateWarDisplay(); GenerateCivPaths(); Invalidate(); } public void UpdateWarDisplay() { _displayObjects.RemoveAll(displayObject => _warEntities.Contains(displayObject)); _warEntities.Clear(); foreach (War war in _displayObjects.OfType<War>().Where(war => war.StartYear <= CurrentYear && (war.EndYear >= CurrentYear || war.EndYear == -1))) { if (war.Attacker.Parent != null) { if (!_displayObjects.Contains(war.Attacker.Parent)) { _warEntities.Add(war.Attacker.Parent); } } else if (!_displayObjects.Contains(war.Attacker)) { _warEntities.Add(war.Attacker); } if (war.Defender.Parent != null) { if (!_displayObjects.Contains(war.Defender.Parent)) { _warEntities.Add(war.Defender.Parent); } } else if (!_displayObjects.Contains(war.Defender)) { _warEntities.Add(war.Defender); } } if (FocusObject != null && (FocusObject.GetType() == typeof(Battle) || FocusObject.GetType() == typeof(SiteConquered))) { Battle battle; if (FocusObject.GetType() == typeof(Battle)) { battle = FocusObject as Battle; } else { battle = ((SiteConquered)FocusObject).Battle; } if (battle != null) { if (battle.Attacker.Parent != null) { if (!_displayObjects.Contains(battle.Attacker.Parent)) { _warEntities.Add(battle.Attacker.Parent); } } else if (!_displayObjects.Contains(battle.Attacker)) { _warEntities.Add(battle.Attacker); } if (battle.Defender.Parent != null) { if (!_displayObjects.Contains(battle.Defender.Parent)) { _warEntities.Add(battle.Defender.Parent); } } else if (!_displayObjects.Contains(battle.Defender)) { _warEntities.Add(battle.Defender); } } } _displayObjects.AddRange(_warEntities); GenerateCivPaths(); } public void MakeOverlay(string overlay) { List<Location> coordinatesList = new List<Location>(); List<int> occurences = new List<int>(); _optionsMenu.Options.Single(option => option.Text == "Overlays").SubMenu.Options.ForEach(option => option.Toggled = false); _optionsMenu.Options.Single(option => option.Text == "Overlays").SubMenu.Options.Single(option => option.Text == overlay).Toggled = true; switch (overlay) { case "Battles": _world.EventCollections.OfType<Battle>().Select(battle => battle.Coordinates).ToList().ForEach(coordinates => coordinatesList.Add(coordinates)); break; case "Battles (Notable)": _world.EventCollections.OfType<Battle>().Where(battle => battle.Notable).Select(battle => battle.Coordinates).ToList().ForEach(coordinates => coordinatesList.Add(coordinates)); break; case "Battle Deaths": foreach (Location coordinates in _world.EventCollections.OfType<Battle>().GroupBy(battle => battle.Coordinates).Select(battle => battle.Key).ToList()) { coordinatesList.Add(coordinates); occurences.Add(_world.EventCollections.OfType<Battle>().Where(battle => battle.Coordinates == coordinates).Sum(battle => battle.AttackerDeathCount + battle.DefenderDeathCount)); } break; case "Site Population...": DlgPopulation selectPopulations = new DlgPopulation(_world); selectPopulations.ShowDialog(); if (selectPopulations.SelectedPopulations.Count == 0) { return; } foreach (Location coordinates in _world.Sites.GroupBy(site => site.Coordinates).Select(site => site.Key).ToList()) { coordinatesList.Add(coordinates); occurences.Add(_world.Sites.Where(site => site.Coordinates == coordinates).Sum(site => site.Populations.Where(population => selectPopulations.SelectedPopulations.Contains(population.Race.NamePlural)).Sum(population => population.Count))); } break; case "Site Events": foreach (Location coordinates in _world.Sites.GroupBy(site => site.Coordinates).Select(site => site.Key).ToList()) { coordinatesList.Add(coordinates); occurences.Add(_world.Sites.Where(site => site.Coordinates == coordinates).Sum(site => site.Events.Count())); } break; case "Site Events (Filtered)": foreach (Location coordinates in _world.Sites.GroupBy(site => site.Coordinates).Select(site => site.Key).ToList()) { coordinatesList.Add(coordinates); occurences.Add(_world.Sites.Where(site => site.Coordinates == coordinates).Sum(site => site.Events.Count(dEvent => !Legends.WorldObjects.Site.Filters.Contains(dEvent.Type)))); } break; case "Beast Attacks": _world.EventCollections.OfType<BeastAttack>().Select(attack => attack.Coordinates).ToList().ForEach(coordinates => coordinatesList.Add(coordinates)); break; } for (int i = 0; i < coordinatesList.Count; i++) { coordinatesList[i] = new Location(coordinatesList[i].X * TileSize + TileSize / 2, coordinatesList[i].Y * TileSize + TileSize / 2); } if (Overlay != null) { Overlay.Dispose(); } if (occurences.Count > 0) { Overlay = HeatMapMaker.Create(_map.Width, _map.Height, coordinatesList, occurences); } else { Overlay = HeatMapMaker.Create(_map.Width, _map.Height, coordinatesList); } OverlayToggled = false; ToggleOverlay(); GC.Collect(); } public void ExportMap() { SaveFileDialog exportMapDialog = new SaveFileDialog { Filter = "Png Image (.png)|*.png|JPEG Image (.jpeg)|*.jpeg|Gif Image (.gif)|*.gif|Bitmap Image (.bmp)|*.bmp|Tiff Image (.tiff)|*.tiff|All files (*.*)|*.*", FilterIndex = 1, RestoreDirectory = true }; if (exportMapDialog.ShowDialog() == DialogResult.OK) { Bitmap map = new Bitmap(_world.Map.Height, _world.Map.Width); using (Graphics mapGraphics = Graphics.FromImage(map)) { mapGraphics.PixelOffsetMode = PixelOffsetMode.Half; DrawMap(mapGraphics, true); DrawDisplayObjects(mapGraphics, true); DrawOverlay(mapGraphics, true); using (Stream exportStream = exportMapDialog.OpenFile()) { switch (exportMapDialog.FilterIndex) { case 1: map.Save(exportStream, ImageFormat.Png); break; case 2: map.Save(exportStream, ImageFormat.Jpeg); break; case 3: map.Save(exportStream, ImageFormat.Gif); break; case 4: map.Save(exportStream, ImageFormat.Bmp); break; case 5: map.Save(exportStream, ImageFormat.Tiff); break; default: map.Save(exportStream, ImageFormat.Png); break; } exportStream.Close(); } } } } public void ChangeMap() { OpenFileDialog openMap = new OpenFileDialog(); openMap.ShowDialog(); string fileName; bool deleteFile = false; if (openMap.FileName != "" && !openMap.FileName.EndsWith(".bmp") && !openMap.FileName.EndsWith(".png") && !openMap.FileName.EndsWith(".jpeg") && !openMap.FileName.EndsWith(".jpg")) { deleteFile = true; using (SevenZipExtractor extractor = new SevenZipExtractor(openMap.FileName)) { if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 0) { MessageBox.Show("No Image Files Found"); return; } if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 1) { fileName = extractor.ArchiveFileNames.Single(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")); } else { DlgFileSelect fileSelect = new DlgFileSelect(extractor.ArchiveFileNames.Where(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")).ToList()); fileSelect.ShowDialog(); if (fileSelect.SelectedFile == "") { return; } if (File.Exists(fileSelect.SelectedFile)) { MessageBox.Show(fileSelect.SelectedFile + " already exists."); return; } fileName = fileSelect.SelectedFile; } extractor.ExtractFiles(Directory.GetCurrentDirectory(), fileName); } } else { fileName = openMap.FileName; } if (fileName != "") { using (FileStream mapStream = new FileStream(fileName, FileMode.Open)) { AlternateMap = new Bitmap(mapStream); } if (AlternateMap.Size != _map.Size) { Bitmap resized = new Bitmap(_map.Width, _map.Height); using (Graphics resize = Graphics.FromImage(resized)) { resize.SmoothingMode = SmoothingMode.AntiAlias; resize.InterpolationMode = InterpolationMode.HighQualityBicubic; resize.DrawImage(AlternateMap, new Rectangle(0, 0, _map.Width, _map.Height)); AlternateMap.Dispose(); AlternateMap = resized; } } MapUtil.AlternateMap = AlternateMap; if (MapUtil.AltMapAlpha == 0) { MapUtil.AltMapAlpha = 1; } AlternateMapToggled = false; ToggleAlternateMap(); } if (deleteFile) { File.Delete(fileName); } } private void ChangeAltMapTransparency(object sender, EventArgs e) { _altMapAlpha = _altMapTransparency.Value / 100.0f; MapUtil.AltMapAlpha = _altMapAlpha; Invalidate(); } private PointF SiteToScreen(Location siteCoordinates, bool originalSize = false) { var rectangle = originalSize ? getOriginalSize(_map) : Source; PointF screenCoordinates = new PointF { X = (float)((siteCoordinates.X * TileSize - rectangle.X + TileSize / 2) * PixelWidth), Y = (float)((siteCoordinates.Y * TileSize - rectangle.Y + TileSize / 2) * PixelHeight) }; return screenCoordinates; } private void Pan(int xChange, int yChange) { Source.Offset(xChange, yChange); Center.Offset(xChange, yChange); _hoverMenu.Open = false; if (xChange > 2 || xChange < -2 || yChange > 2 || yChange < -2) { _optionsMenu.SelectedOption = null; } Invalidate(); } public void ZoomIn() { if (ZoomCurrent > ZoomMin) { ZoomCurrent -= ZoomCurrent * ZoomChange; } UpdateScales(); Invalidate(); } public void ZoomOut() { if (ZoomCurrent < ZoomMax) { ZoomCurrent += ZoomCurrent * ZoomChange; } UpdateScales(); Invalidate(); } private void ZoomToBounds() { ZoomCurrent = 1.0; while (ZoomCurrent > 0.85) { ZoomCurrent -= ZoomCurrent * ZoomChange; //Zoom in to set zoom scale } ZoomCurrent += ZoomCurrent * ZoomChange; UpdateScales(); while (true) //Zoom out till bounds are within the map source { if (Source.X <= _zoomBounds.X && Source.Right >= _zoomBounds.Width && Source.Y <= _zoomBounds.Y && Source.Bottom >= _zoomBounds.Height) { break; } ZoomCurrent += ZoomCurrent * ZoomChange; if (ZoomCurrent > ZoomMax) { break; } UpdateScales(); } ZoomToBoundsOnFirstPaint = false; } private void UpdateScales() { Source.Location = new Point(Center.X - Convert.ToInt32(Width / 2 * ZoomCurrent), Center.Y - Convert.ToInt32(Height / 2 * ZoomCurrent)); Source.Size = new Size(Convert.ToInt32(Width * ZoomCurrent), Convert.ToInt32(Height * ZoomCurrent)); PixelWidth = Convert.ToDouble(Width) / Source.Width; PixelHeight = Convert.ToDouble(Height) / Source.Height; _hoverMenu.Open = false; _controlMenu.MenuBox.Location = new Point(0, Height - _minimap.Height - _controlMenu.MenuBox.Height); _yearMenu.MenuBox.Location = new Point(_minimap.Width, Height - _yearMenu.MenuBox.Height); _altMapTransparency.Location = new Point(MiniMapAreaSideLength + _yearMenu.MenuBox.Width, Height - _altMapTransparency.Height); } private Point WindowToWorldPoint(Point window) { int x = Source.X + Convert.ToInt32(window.X * ZoomCurrent); int y = Source.Y + Convert.ToInt32(window.Y * ZoomCurrent); return new Point(x, y); } public Point WindowToTilePoint(Point window) { Point tilePoint = WindowToWorldPoint(window); tilePoint.X = tilePoint.X / TileSize; tilePoint.Y = tilePoint.Y / TileSize; return tilePoint; } public Location WindowToWorldTile(Point window) { Point location = WindowToTilePoint(window); return new Location(location.X, location.Y); } protected override void OnSizeChanged(EventArgs e) { UpdateScales(); } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { MouseClickLocation = e.Location; } if (e.Button == MouseButtons.Left) { MousePanStart = e.Location; } } protected override void OnMouseUp(MouseEventArgs e) { if (e.Location.X > MouseClickLocation.X - 5 && e.Location.X < MouseClickLocation.X + 5 && e.Location.Y > MouseClickLocation.Y - 5 && e.Location.Y < MouseClickLocation.Y + 5)// e.Location == MouseClickLocation) { if (_controlMenu.SelectedOption != null) { _controlMenu.Click(e.X, e.Y); } else if (_yearMenu.SelectedOption != null) { _yearMenu.Click(e.X, e.Y); } else if (_optionsMenu.SelectedOption != null) { _optionsMenu.Click(e.X, e.Y); } else if (_hoverMenu.Options.Count == 1 && _hoverMenu.Options.Count(option => option.SubMenu.Options.Count(option2 => option2.SubMenu != null) > 0) == 0) { _hoverMenu.Options.First().Click(); } else if (!_hoverMenu.Open && _hoverMenu.Options.Count > 0) { _hoverMenu.Open = true; } else if (_hoverMenu.Open) { _hoverMenu.Click(e.X, e.Y); _hoverMenu.Open = false; } else { _hoverMenu.Open = false; } _optionsMenu.SelectedOption = null; } } protected override void OnMouseMove(MouseEventArgs e) { if (!_controlMenu.HighlightOption(e.X, e.Y) && !_yearMenu.HighlightOption(e.X, e.Y) && !_optionsMenu.HighlightOption(e.X, e.Y) && !_hoverMenu.Open) { List<object> addOptions = new List<object>(); Location tile = WindowToWorldTile(e.Location); foreach (Site site in _displayObjects.OfType<Entity>().SelectMany(entity => entity.Sites).Where(site => site.Coordinates == tile).Distinct()) { OwnerPeriod ownerPeriod = site.OwnerHistory.LastOrDefault(op => op.StartYear <= CurrentYear && op.EndYear >= CurrentYear || op.EndYear == -1); if(ownerPeriod != null && ownerPeriod.Owner is Entity entity) { addOptions.Add(entity); addOptions.Add(ownerPeriod.Site); } } foreach (Site site in _displayObjects.OfType<Site>().Where(site => site.Coordinates == tile && !addOptions.Contains(site))) { addOptions.Add(site); } if (FocusObject != null && FocusObject.GetType() == typeof(Battle) && ((Battle)FocusObject).Coordinates == tile) { addOptions.Add(FocusObject as Battle); } foreach (Battle battle in _displayObjects.OfType<War>().SelectMany(war => war.Collections).OfType<Battle>().Where(battle => battle != FocusObject && battle.StartYear == CurrentYear && battle.Coordinates == tile)) { addOptions.Add(battle); } if (BattlesToggled || _battles.Count > 0) { if (_battleLocations.Any(location => location == tile)) { List<Battle> battles = _battles.Where(battle => battle.Coordinates == tile).ToList(); if (battles.Count > 0) { addOptions.Add(battles); } } } _hoverMenu.AddOptions(addOptions); if (_hoverMenu.Options.Count > 0) { _hoverMenu.MenuBox.Location = WindowToTilePoint(e.Location); _hoverMenu.MenuBox.X = Convert.ToInt32(((_hoverMenu.MenuBox.X + 1) * TileSize - Source.X) * PixelWidth); _hoverMenu.MenuBox.Y = Convert.ToInt32(((_hoverMenu.MenuBox.Y + 1) * TileSize - Source.Y) * PixelHeight); Invalidate(); } } else { _hoverMenu.HighlightOption(e.X, e.Y); } if (_optionsMenu.SelectedOption != null || _controlMenu.SelectedOption != null || _yearMenu.SelectedOption != null) { _hoverMenu.Options.Clear(); } if (e.Button == MouseButtons.Left) { Point worldStart = WindowToWorldPoint(new Point(MousePanStart.X, MousePanStart.Y)); Point worldEnd = WindowToWorldPoint(new Point(e.X, e.Y)); int xChange = worldStart.X - worldEnd.X; int yChange = worldStart.Y - worldEnd.Y; Pan(xChange, yChange); MousePanStart = e.Location; } MouseLocation = e.Location; } protected override void OnMouseEnter(EventArgs e) { Focus(); } protected override void OnMouseWheel(MouseEventArgs e) { if (e.Delta > 0) { if (ModifierKeys == (Keys.Control | Keys.Shift)) { ChangeYear(100); } else if (ModifierKeys == Keys.Control) { ChangeYear(1); } else if (ModifierKeys == Keys.Shift) { ChangeYear(10); } else { ZoomIn(); } } else if (e.Delta < 0) { if (ModifierKeys == (Keys.Control | Keys.Shift)) { ChangeYear(-100); } else if (ModifierKeys == Keys.Control) { ChangeYear(-1); } else if (ModifierKeys == Keys.Shift) { ChangeYear(-10); } else { ZoomOut(); } } } public static List<Bitmap> CreateBitmaps(World world, DwarfObject dwarfObject) { int maxSize = world.PageMiniMap.Height > world.PageMiniMap.Width ? world.PageMiniMap.Height : world.PageMiniMap.Width; MapPanel createBitmaps = new MapPanel(world.Map, world, null, dwarfObject) { Height = maxSize, Width = maxSize }; if (createBitmaps.ZoomToBoundsOnFirstPaint) { createBitmaps.ZoomToBounds(); } createBitmaps.MiniMapAreaSideLength = maxSize; createBitmaps._minimap = world.PageMiniMap; Bitmap miniMap = new Bitmap(maxSize, maxSize); using (Graphics miniMapGraphics = Graphics.FromImage(miniMap)) { createBitmaps.DrawMiniMap(miniMapGraphics); } Bitmap map = new Bitmap(maxSize, maxSize); using (Graphics mapGraphics = Graphics.FromImage(map)) { mapGraphics.PixelOffsetMode = PixelOffsetMode.Half; createBitmaps.DrawMap(mapGraphics); createBitmaps.DrawDisplayObjects(mapGraphics); createBitmaps.Dispose(); return new List<Bitmap> { map, miniMap }; } } private Site GetClosestSite(Entity civ, Location coordinates) { double closestDistance = double.MaxValue; Site closestSite = null; foreach (OwnerPeriod period in civ.SiteHistory.Where(ownerPeriod => ownerPeriod.StartYear <= CurrentYear && ownerPeriod.EndYear >= CurrentYear || ownerPeriod.EndYear == -1)) { int rise = period.Site.Coordinates.Y - coordinates.Y; int run = period.Site.Coordinates.X - coordinates.X; double distance = Math.Sqrt(Math.Pow(rise, 2) + Math.Pow(run, 2)); if (distance < closestDistance) { closestSite = period.Site; closestDistance = distance; } } return closestSite; } } }
0
0.942312
1
0.942312
game-dev
MEDIA
0.659357
game-dev,desktop-app
0.980811
1
0.980811
mavlink/qgroundcontrol
35,716
src/AutoPilotPlugins/APM/APMSafetyComponent.qml
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ import QtQuick import QtQuick.Controls import QtQuick.Layouts import QGroundControl import QGroundControl.FactControls import QGroundControl.Controls SetupPage { id: safetyPage pageComponent: safetyPageComponent Component { id: safetyPageComponent Flow { id: flowLayout width: availableWidth spacing: _margins FactPanelController { id: controller; } QGCPalette { id: ggcPal; colorGroupEnabled: true } property Fact _batt1Monitor: controller.getParameterFact(-1, "BATT_MONITOR") property Fact _batt2Monitor: controller.getParameterFact(-1, "BATT2_MONITOR", false /* reportMissing */) property bool _batt2MonitorAvailable: controller.parameterExists(-1, "BATT2_MONITOR") property bool _batt1MonitorEnabled: _batt1Monitor.rawValue !== 0 property bool _batt2MonitorEnabled: _batt2MonitorAvailable ? _batt2Monitor.rawValue !== 0 : false property bool _batt1ParamsAvailable: controller.parameterExists(-1, "BATT_CAPACITY") property bool _batt2ParamsAvailable: controller.parameterExists(-1, "BATT2_CAPACITY") property Fact _failsafeBatt1LowAct: controller.getParameterFact(-1, "BATT_FS_LOW_ACT", false /* reportMissing */) property Fact _failsafeBatt2LowAct: controller.getParameterFact(-1, "BATT2_FS_LOW_ACT", false /* reportMissing */) property Fact _failsafeBatt1CritAct: controller.getParameterFact(-1, "BATT_FS_CRT_ACT", false /* reportMissing */) property Fact _failsafeBatt2CritAct: controller.getParameterFact(-1, "BATT2_FS_CRT_ACT", false /* reportMissing */) property Fact _failsafeBatt1LowMah: controller.getParameterFact(-1, "BATT_LOW_MAH", false /* reportMissing */) property Fact _failsafeBatt2LowMah: controller.getParameterFact(-1, "BATT2_LOW_MAH", false /* reportMissing */) property Fact _failsafeBatt1CritMah: controller.getParameterFact(-1, "BATT_CRT_MAH", false /* reportMissing */) property Fact _failsafeBatt2CritMah: controller.getParameterFact(-1, "BATT2_CRT_MAH", false /* reportMissing */) property Fact _failsafeBatt1LowVoltage: controller.getParameterFact(-1, "BATT_LOW_VOLT", false /* reportMissing */) property Fact _failsafeBatt2LowVoltage: controller.getParameterFact(-1, "BATT2_LOW_VOLT", false /* reportMissing */) property Fact _failsafeBatt1CritVoltage: controller.getParameterFact(-1, "BATT_CRT_VOLT", false /* reportMissing */) property Fact _failsafeBatt2CritVoltage: controller.getParameterFact(-1, "BATT2_CRT_VOLT", false /* reportMissing */) property Fact _armingCheck: controller.getParameterFact(-1, "ARMING_CHECK") property real _margins: ScreenTools.defaultFontPixelHeight property real _innerMargin: _margins / 2 property bool _showIcon: !ScreenTools.isTinyScreen property bool _roverFirmware: controller.parameterExists(-1, "MODE1") // This catches all usage of ArduRover firmware vehicle types: Rover, Boat... property string _restartRequired: qsTr("Requires vehicle reboot") Component { id: batteryFailsafeComponent Column { spacing: _margins GridLayout { id: gridLayout columnSpacing: _margins rowSpacing: _margins columns: 2 QGCLabel { text: qsTr("Low action:") } FactComboBox { fact: failsafeBattLowAct indexModel: false Layout.fillWidth: true } QGCLabel { text: qsTr("Critical action:") } FactComboBox { fact: failsafeBattCritAct indexModel: false Layout.fillWidth: true } QGCLabel { text: qsTr("Low voltage threshold:") } FactTextField { fact: failsafeBattLowVoltage showUnits: true Layout.fillWidth: true } QGCLabel { text: qsTr("Critical voltage threshold:") } FactTextField { fact: failsafeBattCritVoltage showUnits: true Layout.fillWidth: true } QGCLabel { text: qsTr("Low mAh threshold:") } FactTextField { fact: failsafeBattLowMah showUnits: true Layout.fillWidth: true } QGCLabel { text: qsTr("Critical mAh threshold:") } FactTextField { fact: failsafeBattCritMah showUnits: true Layout.fillWidth: true } } // GridLayout } // Column } Component { id: restartRequiredComponent ColumnLayout { spacing: ScreenTools.defaultFontPixelWidth QGCLabel { text: _restartRequired } QGCButton { text: qsTr("Reboot vehicle") onClicked: controller.vehicle.rebootVehicle() } } } Column { spacing: _margins / 2 visible: _batt1MonitorEnabled QGCLabel { text: qsTr("Battery1 Failsafe Triggers") font.bold: true } Rectangle { width: battery1FailsafeLoader.x + battery1FailsafeLoader.width + _margins height: battery1FailsafeLoader.y + battery1FailsafeLoader.height + _margins color: ggcPal.windowShade Loader { id: battery1FailsafeLoader anchors.margins: _margins anchors.top: parent.top anchors.left: parent.left sourceComponent: _batt1ParamsAvailable ? batteryFailsafeComponent : restartRequiredComponent property Fact battMonitor: _batt1Monitor property bool battParamsAvailable: _batt1ParamsAvailable property Fact failsafeBattLowAct: _failsafeBatt1LowAct property Fact failsafeBattCritAct: _failsafeBatt1CritAct property Fact failsafeBattLowMah: _failsafeBatt1LowMah property Fact failsafeBattCritMah: _failsafeBatt1CritMah property Fact failsafeBattLowVoltage: _failsafeBatt1LowVoltage property Fact failsafeBattCritVoltage: _failsafeBatt1CritVoltage } } // Rectangle } // Column - Battery Failsafe Settings Column { spacing: _margins / 2 visible: _batt2MonitorEnabled QGCLabel { text: qsTr("Battery2 Failsafe Triggers") font.bold: true } Rectangle { width: battery2FailsafeLoader.x + battery2FailsafeLoader.width + _margins height: battery2FailsafeLoader.y + battery2FailsafeLoader.height + _margins color: ggcPal.windowShade Loader { id: battery2FailsafeLoader anchors.margins: _margins anchors.top: parent.top anchors.left: parent.left sourceComponent: _batt2ParamsAvailable ? batteryFailsafeComponent : restartRequiredComponent property Fact battMonitor: _batt2Monitor property bool battParamsAvailable: _batt2ParamsAvailable property Fact failsafeBattLowAct: _failsafeBatt2LowAct property Fact failsafeBattCritAct: _failsafeBatt2CritAct property Fact failsafeBattLowMah: _failsafeBatt2LowMah property Fact failsafeBattCritMah: _failsafeBatt2CritMah property Fact failsafeBattLowVoltage: _failsafeBatt2LowVoltage property Fact failsafeBattCritVoltage: _failsafeBatt2CritVoltage } } // Rectangle } // Column - Battery Failsafe Settings Component { id: planeGeneralFS Column { spacing: _margins / 2 property Fact _failsafeThrEnable: controller.getParameterFact(-1, "THR_FAILSAFE") property Fact _failsafeThrValue: controller.getParameterFact(-1, "THR_FS_VALUE") property Fact _failsafeGCSEnable: controller.getParameterFact(-1, "FS_GCS_ENABL") QGCLabel { text: qsTr("Failsafe Triggers") font.bold: true } Rectangle { width: fsColumn.x + fsColumn.width + _margins height: fsColumn.y + fsColumn.height + _margins color: qgcPal.windowShade ColumnLayout { id: fsColumn anchors.margins: _margins anchors.left: parent.left anchors.top: parent.top RowLayout { QGCCheckBox { id: throttleEnableCheckBox text: qsTr("Throttle PWM threshold:") checked: _failsafeThrEnable.value === 1 onClicked: _failsafeThrEnable.value = (checked ? 1 : 0) } FactTextField { fact: _failsafeThrValue showUnits: true enabled: throttleEnableCheckBox.checked } } QGCCheckBox { text: qsTr("GCS failsafe") checked: _failsafeGCSEnable.value != 0 onClicked: _failsafeGCSEnable.value = checked ? 1 : 0 } } } // Rectangle - Failsafe trigger settings } // Column - Failsafe trigger settings } Loader { sourceComponent: controller.vehicle.fixedWing ? planeGeneralFS : undefined } Component { id: roverGeneralFS Column { spacing: _margins / 2 property Fact _failsafeGCSEnable: controller.getParameterFact(-1, "FS_GCS_ENABLE") property Fact _failsafeThrEnable: controller.getParameterFact(-1, "FS_THR_ENABLE") property Fact _failsafeThrValue: controller.getParameterFact(-1, "FS_THR_VALUE") property Fact _failsafeAction: controller.getParameterFact(-1, "FS_ACTION") property Fact _failsafeCrashCheck: controller.getParameterFact(-1, "FS_CRASH_CHECK") QGCLabel { id: failsafeLabel text: qsTr("Failsafe Triggers") font.bold: true } Rectangle { id: failsafeSettings width: fsGrid.x + fsGrid.width + _margins height: fsGrid.y + fsGrid.height + _margins color: ggcPal.windowShade GridLayout { id: fsGrid anchors.margins: _margins anchors.left: parent.left anchors.top: parent.top columns: 2 QGCLabel { text: qsTr("Ground Station failsafe:") } FactComboBox { Layout.fillWidth: true fact: _failsafeGCSEnable indexModel: false } QGCLabel { text: qsTr("Throttle failsafe:") } FactComboBox { Layout.fillWidth: true fact: _failsafeThrEnable indexModel: false } QGCLabel { text: qsTr("PWM threshold:") } FactTextField { Layout.fillWidth: true fact: _failsafeThrValue } QGCLabel { text: qsTr("Failsafe Crash Check:") } FactComboBox { Layout.fillWidth: true fact: _failsafeCrashCheck indexModel: false } } } // Rectangle - Failsafe Settings } // Column - Failsafe Settings } Loader { sourceComponent: _roverFirmware ? roverGeneralFS : undefined } Component { id: copterGeneralFS Column { spacing: _margins / 2 property Fact _failsafeGCSEnable: controller.getParameterFact(-1, "FS_GCS_ENABLE") property Fact _failsafeBattLowAct: controller.getParameterFact(-1, "r.BATT_FS_LOW_ACT", false /* reportMissing */) property Fact _failsafeBattMah: controller.getParameterFact(-1, "r.BATT_LOW_MAH", false /* reportMissing */) property Fact _failsafeBattVoltage: controller.getParameterFact(-1, "r.BATT_LOW_VOLT", false /* reportMissing */) property Fact _failsafeThrEnable: controller.getParameterFact(-1, "FS_THR_ENABLE") property Fact _failsafeThrValue: controller.getParameterFact(-1, "FS_THR_VALUE") QGCLabel { text: qsTr("General Failsafe Triggers") font.bold: true } Rectangle { width: generalFailsafeColumn.x + generalFailsafeColumn.width + _margins height: generalFailsafeColumn.y + generalFailsafeColumn.height + _margins color: ggcPal.windowShade Column { id: generalFailsafeColumn anchors.margins: _margins anchors.top: parent.top anchors.left: parent.left spacing: _margins GridLayout { columnSpacing: _margins rowSpacing: _margins columns: 2 QGCLabel { text: qsTr("Ground Station failsafe:") } FactComboBox { fact: _failsafeGCSEnable indexModel: false Layout.fillWidth: true } QGCLabel { text: qsTr("Throttle failsafe:") } QGCComboBox { model: [qsTr("Disabled"), qsTr("Always RTL"), qsTr("Continue with Mission in Auto Mode"), qsTr("Always Land")] currentIndex: _failsafeThrEnable.value Layout.fillWidth: true onActivated: (index) => { _failsafeThrEnable.value = index } } QGCLabel { text: qsTr("PWM threshold:") } FactTextField { fact: _failsafeThrValue showUnits: true Layout.fillWidth: true } } // GridLayout } // Column } // Rectangle - Failsafe Settings } // Column - General Failsafe Settings } Loader { sourceComponent: controller.vehicle.multiRotor ? copterGeneralFS : undefined } Component { id: copterGeoFence Column { spacing: _margins / 2 property Fact _fenceAction: controller.getParameterFact(-1, "FENCE_ACTION") property Fact _fenceAltMax: controller.getParameterFact(-1, "FENCE_ALT_MAX") property Fact _fenceEnable: controller.getParameterFact(-1, "FENCE_ENABLE") property Fact _fenceMargin: controller.getParameterFact(-1, "FENCE_MARGIN") property Fact _fenceRadius: controller.getParameterFact(-1, "FENCE_RADIUS") property Fact _fenceType: controller.getParameterFact(-1, "FENCE_TYPE") readonly property int _maxAltitudeFenceBitMask: 1 readonly property int _circleFenceBitMask: 2 readonly property int _polygonFenceBitMask: 4 QGCLabel { text: qsTr("GeoFence") font.bold: true } Rectangle { width: mainLayout.width + (_margins * 2) height: mainLayout.height + (_margins * 2) color: ggcPal.windowShade ColumnLayout { id: mainLayout x: _margins y: _margins spacing: ScreenTools.defaultFontPixellHeight / 2 FactCheckBox { id: enabledCheckBox text: qsTr("Enabled") fact: _fenceEnable } GridLayout { columns: 2 enabled: enabledCheckBox.checked QGCCheckBox { text: qsTr("Maximum Altitude") checked: _fenceType.rawValue & _maxAltitudeFenceBitMask onClicked: { if (checked) { _fenceType.rawValue |= _maxAltitudeFenceBitMask } else { _fenceType.value &= ~_maxAltitudeFenceBitMask } } } FactTextField { fact: _fenceAltMax } QGCCheckBox { text: qsTr("Circle centered on Home") checked: _fenceType.rawValue & _circleFenceBitMask onClicked: { if (checked) { _fenceType.rawValue |= _circleFenceBitMask } else { _fenceType.value &= ~_circleFenceBitMask } } } FactTextField { fact: _fenceRadius showUnits: true } QGCCheckBox { text: qsTr("Inclusion/Exclusion Circles+Polygons") checked: _fenceType.rawValue & _polygonFenceBitMask onClicked: { if (checked) { _fenceType.rawValue |= _polygonFenceBitMask } else { _fenceType.value &= ~_polygonFenceBitMask } } } Item { height: 1 width: 1 } } // GridLayout Item { height: 1 width: 1 } GridLayout { columns: 2 enabled: enabledCheckBox.checked QGCLabel { text: qsTr("Breach action") } FactComboBox { sizeToContents: true fact: _fenceAction } QGCLabel { text: qsTr("Fence margin") } FactTextField { fact: _fenceMargin } } } } // Rectangle - GeoFence Settings } // Column - GeoFence Settings } Loader { sourceComponent: controller.vehicle.multiRotor ? copterGeoFence : undefined } Component { id: copterRTL Column { spacing: _margins / 2 property Fact _landSpeedFact: controller.getParameterFact(-1, "LAND_SPEED") property Fact _rtlAltFact: controller.getParameterFact(-1, "RTL_ALT") property Fact _rtlLoitTimeFact: controller.getParameterFact(-1, "RTL_LOIT_TIME") property Fact _rtlAltFinalFact: controller.getParameterFact(-1, "RTL_ALT_FINAL") QGCLabel { id: rtlLabel text: qsTr("Return to Launch") font.bold: true } Rectangle { id: rtlSettings width: landSpeedField.x + landSpeedField.width + _margins height: landSpeedField.y + landSpeedField.height + _margins color: ggcPal.windowShade QGCColoredImage { id: icon visible: _showIcon anchors.margins: _margins anchors.left: parent.left anchors.top: parent.top height: ScreenTools.defaultFontPixelWidth * 20 width: ScreenTools.defaultFontPixelWidth * 20 color: ggcPal.text sourceSize.width: width mipmap: true fillMode: Image.PreserveAspectFit source: "/qmlimages/ReturnToHomeAltitude.svg" } QGCRadioButton { id: returnAtCurrentRadio anchors.margins: _innerMargin anchors.left: _showIcon ? icon.right : parent.left anchors.top: parent.top text: qsTr("Return at current altitude") checked: _rtlAltFact.value == 0 onClicked: _rtlAltFact.value = 0 } QGCRadioButton { id: returnAltRadio anchors.topMargin: _innerMargin anchors.top: returnAtCurrentRadio.bottom anchors.left: returnAtCurrentRadio.left text: qsTr("Return at specified altitude:") checked: _rtlAltFact.value != 0 onClicked: _rtlAltFact.value = 1500 } FactTextField { id: rltAltField anchors.leftMargin: _margins anchors.left: returnAltRadio.right anchors.baseline: returnAltRadio.baseline fact: _rtlAltFact showUnits: true enabled: returnAltRadio.checked } QGCCheckBox { id: homeLoiterCheckbox anchors.left: returnAtCurrentRadio.left anchors.baseline: landDelayField.baseline checked: _rtlLoitTimeFact.value > 0 text: qsTr("Loiter above Home for:") onClicked: _rtlLoitTimeFact.value = (checked ? 60 : 0) } FactTextField { id: landDelayField anchors.topMargin: _innerMargin anchors.left: rltAltField.left anchors.top: rltAltField.bottom fact: _rtlLoitTimeFact showUnits: true enabled: homeLoiterCheckbox.checked === true } QGCLabel { anchors.left: returnAtCurrentRadio.left anchors.baseline: rltAltFinalField.baseline text: qsTr("Final land stage altitude:") } FactTextField { id: rltAltFinalField anchors.topMargin: _innerMargin anchors.left: rltAltField.left anchors.top: landDelayField.bottom fact: _rtlAltFinalFact showUnits: true } QGCLabel { anchors.left: returnAtCurrentRadio.left anchors.baseline: landSpeedField.baseline text: qsTr("Final land stage descent speed:") } FactTextField { id: landSpeedField anchors.topMargin: _innerMargin anchors.left: rltAltField.left anchors.top: rltAltFinalField.bottom fact: _landSpeedFact showUnits: true } } // Rectangle - RTL Settings } // Column - RTL Settings } Loader { sourceComponent: controller.vehicle.multiRotor ? copterRTL : undefined } Component { id: planeRTL Column { spacing: _margins / 2 property Fact _rtlAltFact: { if (controller.firmwareMajorVersion < 4 || (controller.firmwareMajorVersion === 4 && controller.firmwareMinorVersion < 5)) { return controller.getParameterFact(-1, "ALT_HOLD_RTL") } else { return controller.getParameterFact(-1, "RTL_ALTITUDE") } } QGCLabel { text: qsTr("Return to Launch") font.bold: true } Rectangle { width: rltAltField.x + rltAltField.width + _margins height: rltAltField.y + rltAltField.height + _margins color: qgcPal.windowShade QGCRadioButton { id: returnAtCurrentRadio anchors.margins: _margins anchors.left: parent.left anchors.top: parent.top text: qsTr("Return at current altitude") checked: _rtlAltFact.value < 0 onClicked: _rtlAltFact.value = -1 } QGCRadioButton { id: returnAltRadio anchors.topMargin: _margins / 2 anchors.left: returnAtCurrentRadio.left anchors.top: returnAtCurrentRadio.bottom text: qsTr("Return at specified altitude:") checked: _rtlAltFact.value >= 0 onClicked: _rtlAltFact.value = 10000 } FactTextField { id: rltAltField anchors.leftMargin: _margins anchors.left: returnAltRadio.right anchors.baseline: returnAltRadio.baseline fact: _rtlAltFact showUnits: true enabled: returnAltRadio.checked } } // Rectangle - RTL Settings } // Column - RTL Settings } Loader { sourceComponent: controller.vehicle.fixedWing ? planeRTL : undefined } Column { spacing: _margins / 2 QGCLabel { text: qsTr("Arming Checks") font.bold: true } Rectangle { width: flowLayout.width height: armingCheckInnerColumn.height + (_margins * 2) color: ggcPal.windowShade Column { id: armingCheckInnerColumn anchors.margins: _margins anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right spacing: _margins FactBitmask { id: armingCheckBitmask anchors.left: parent.left anchors.right: parent.right firstEntryIsAll: true fact: _armingCheck } QGCLabel { id: armingCheckWarning anchors.left: parent.left anchors.right: parent.right wrapMode: Text.WordWrap color: qgcPal.warningText text: qsTr("Warning: Turning off arming checks can lead to loss of Vehicle control.") visible: _armingCheck.value != 1 } } } // Rectangle - Arming checks } // Column - Arming Checks } // Flow } // Component - safetyPageComponent } // SetupView
0
0.818198
1
0.818198
game-dev
MEDIA
0.57956
game-dev
0.693113
1
0.693113
strangergwenn/AstralShipwright
1,659
Source/AstralShipwright/Spacecraft/NovaSpacecraftHatchComponent.cpp
// Astral Shipwright - Gwennaël Arbona #include "NovaSpacecraftHatchComponent.h" #include "Spacecraft/NovaSpacecraftPawn.h" #include "Nova.h" #include "Neutron/Actor/NeutronMeshInterface.h" #include "Animation/AnimSingleNodeInstance.h" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UNovaSpacecraftHatchComponent::UNovaSpacecraftHatchComponent() : Super(), CurrentDockingState(false) { // Settings PrimaryComponentTick.bCanEverTick = true; } /*---------------------------------------------------- Inherited ----------------------------------------------------*/ void UNovaSpacecraftHatchComponent::SetAdditionalAsset(TSoftObjectPtr<UObject> AdditionalAsset) {} void UNovaSpacecraftHatchComponent::BeginPlay() { Super::BeginPlay(); HatchMesh = Cast<UNeutronSkeletalMeshComponent>(GetAttachParent()); NCHECK(HatchMesh); } void UNovaSpacecraftHatchComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); ANovaSpacecraftPawn* SpacecraftPawn = Cast<ANovaSpacecraftPawn>(GetOwner()); if (IsValid(SpacecraftPawn)) { bool DesiredDockingState = SpacecraftPawn->IsDocking() || SpacecraftPawn->IsDocked(); if (DesiredDockingState != CurrentDockingState) { NLOG("UNovaSpacecraftHatchComponent::TickComponent : new dock state is %d", DesiredDockingState); HatchMesh->GetSingleNodeInstance()->SetReverse(!DesiredDockingState); HatchMesh->GetSingleNodeInstance()->SetPlaying(true); CurrentDockingState = DesiredDockingState; } } }
0
0.744634
1
0.744634
game-dev
MEDIA
0.957518
game-dev
0.773002
1
0.773002
Gaby-Station/Gaby-Station
1,925
Content.Client/_EinsteinEngines/Forensics/ScentTrackerSystem.cs
// SPDX-FileCopyrightText: 2025 GabyChangelog <agentepanela2@gmail.com> // SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me> // SPDX-FileCopyrightText: 2025 MarkerWicker <markerWicker@proton.me> // SPDX-FileCopyrightText: 2025 Solstice <solsticeofthewinter@gmail.com> // SPDX-FileCopyrightText: 2025 SolsticeOfTheWinter <solsticeofthewinter@gmail.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Shared._EinsteinEngines.Forensics.Systems; using Content.Shared._EinsteinEngines.Forensics; using Content.Shared.Forensics.Components; using Robust.Shared.Random; using Robust.Shared.Timing; using Robust.Client.Player; namespace Content.Client._EinsteinEngines.Forensics; public sealed class ScentTrackerSystem : SharedScentTrackerSystem { [Dependency] private readonly IGameTiming _timing = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly SharedTransformSystem _transform = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; public override void Update(float frameTime) { base.Update(frameTime); // Goobstation - move trycomp, scent = empty outside of the while loop // If the player can't track scents, continuing beyond this point is a waste of processing power. if (!TryComp<ScentTrackerComponent>(_playerManager.LocalEntity, out var scentcomp) || scentcomp.Scent == string.Empty) return; var query = AllEntityQuery<ForensicsComponent>(); while (query.MoveNext(out var uid, out var comp)) if (scentcomp.Scent == comp.Scent && _timing.CurTime > comp.TargetTime) { comp.TargetTime = _timing.CurTime + TimeSpan.FromSeconds(1.0f); Spawn("ScentTrackEffect", _transform.GetMapCoordinates(uid).Offset(_random.NextVector2(0.25f))); } } }
0
0.989532
1
0.989532
game-dev
MEDIA
0.93582
game-dev
0.929261
1
0.929261
randovania/randovania
13,385
tools/factorio/create_resources.py
import argparse import csv import json import typing from pathlib import Path from randovania.games.factorio import importer_util from randovania.games.factorio.data_importer import data_parser from randovania.games.factorio.importer_util import and_req, or_req, tech_req, template_req from randovania.lib import json_lib _k_items_for_crafting_category = { "crafting": [], "advanced-crafting": ["assembling-machine-1"], # , "assembling-machine-2", "assembling-machine-3"], "smelting": [], # ["stone-furnace", "steel-furnace", "electric-furnace"], "chemistry": ["chemical-plant"], "crafting-with-fluid": ["assembling-machine-2"], # , "assembling-machine-3"], "oil-processing": ["oil-refinery"], "rocket-building": ["rocket-silo"], "centrifuging": ["centrifuge"], } _k_burner_entities = [ "stone-furnace", "steel-furnace", "boiler", "burner-mining-drill", ] _k_electric_entities = [ "assembling-machine-1", "assembling-machine-2", "assembling-machine-3", "electric-furnace", "chemical-plant", "oil-refinery", "rocket-silo", "centrifuge", "electric-mining-drill", "pumpjack", ] _k_fuel_production = template_req("craft-coal") # _k_basic_mining = or_req( # [ # template_req("use-burner-mining-drill"), # template_req("use-electric-mining-drill"), # ] # ) _k_basic_mining = and_req([]) _k_miner_for_resource = { "raw-fish": and_req([]), "wood": and_req([]), "coal": and_req([]), # coal is needed for power, so let's keep it simple to avoid loops # Rn, can always mine "iron-ore": _k_basic_mining, "copper-ore": _k_basic_mining, "stone": _k_basic_mining, "water": template_req("has-offshore-pump"), "steam": or_req( [ and_req( [ template_req("has-boiler"), _k_fuel_production, ], comment="Boiler powered Steam Engines", ), # Causes loops with coal liquefaction # and_req( # [ # item_req("nuclear-reactor"), # template_req("craft-uranium-fuel-cell"), # ], # comment="Nuclear Power", # ), ] ), "uranium-ore": and_req( [ template_req("use-electric-mining-drill"), template_req("craft-sulfuric-acid"), tech_req("uranium-mining"), ] ), "crude-oil": template_req("use-pumpjack"), } def requirement_for_recipe(recipes_raw: dict, recipe: str, unlocking_techs: list[str]) -> dict: entries = [] if len(unlocking_techs) > 1: entries.append(or_req([tech_req(tech) for tech in unlocking_techs])) elif unlocking_techs: entries.append(tech_req(unlocking_techs[0])) category = recipes_raw[recipe].get("category", "crafting") if category != "crafting": # hand-craft compatible, so assume always possible entries.append(template_req(f"perform-{category}")) for ingredient in recipes_raw[recipe]["ingredients"]: if isinstance(ingredient, dict): ing_name = ingredient["name"] else: ing_name = ingredient[0] if recipe == "kovarex-enrichment-process" and ing_name == "uranium-235": continue entries.append(template_req(f"craft-{ing_name}")) return and_req(entries) def create_resources(header: dict, techs_for_recipe: dict) -> None: header["resource_database"]["items"] = {} for tech_name, recipes_unlocked in techs_for_recipe.items(): header["resource_database"]["items"][tech_name] = { "long_name": importer_util.get_localized_name(tech_name), "max_capacity": 1, "extra": {"recipes_unlocked": recipes_unlocked}, } def update_templates(header: dict, recipes_raw: dict, techs_for_recipe: dict[str, list[str]]): header["resource_database"]["requirement_template"]["has-electricity"] = { "display_name": "Has Electricity", "requirement": or_req( [ and_req( [ tech_req("steam-power"), _k_fuel_production, ], comment="Boiler powered Steam Engines", ), and_req( [tech_req("solar-energy"), tech_req("electric-energy-accumulators")], comment="Solar with battery for night", ), # TODO: maybe craft? # TODO: figure out settings later # and_req([item_req("solar-energy"), setting("solar-without-accumulator")]), # Nuclear requires electricity to work # and_req( # [ # item_req("nuclear-power"), # template_req("craft-uranium-fuel-cell"), # ], # comment="Nuclear Power", # ), ] ), } for entity in _k_burner_entities: header["resource_database"]["requirement_template"][f"use-{entity}"] = { "display_name": f"Use {entity}", "requirement": and_req( [template_req(f"has-{entity}"), _k_fuel_production], comment="Fuel is considered always available.", ), } for entity in _k_electric_entities: header["resource_database"]["requirement_template"][f"use-{entity}"] = { "display_name": f"Use {entity}", "requirement": and_req( [ template_req(f"has-{entity}"), template_req("has-electricity"), ] ), } # Machines needed for the non-trivial crafting recipes for category, items in _k_items_for_crafting_category.items(): header["resource_database"]["requirement_template"][f"perform-{category}"] = { "display_name": f"Perform {category}", "requirement": or_req([template_req(f"use-{it}") for it in items]) if items else and_req([]), } # Add the templates for crafting all recipes for item_name, recipes in data_parser.get_recipes_for(recipes_raw).items(): localized_name = importer_util.get_localized_name(item_name) techs = set() for recipe in recipes: techs.update(techs_for_recipe.get(recipe, [])) header["resource_database"]["requirement_template"][f"has-{item_name}"] = { "display_name": f"Unlocked {localized_name}", "requirement": or_req([tech_req(tech) for tech in sorted(techs)]) if techs else and_req([]), } header["resource_database"]["requirement_template"][f"craft-{item_name}"] = { "display_name": f"Craft {localized_name}", "requirement": or_req( [ requirement_for_recipe(recipes_raw, recipe, techs_for_recipe.get(recipe, [])) for recipe in sorted(recipes) ] ), } # Mining all resources for resource_name, requirement in _k_miner_for_resource.items(): localized_name = importer_util.get_localized_name(resource_name) header["resource_database"]["requirement_template"][f"craft-{resource_name}"] = { "display_name": f"Mine {localized_name}", "requirement": requirement, } def read_tech_csv(csv_path: Path) -> dict: result = {} with csv_path.open() as f: f.readline() r = csv.reader(f) for line in r: if line[1] == "<>": continue tech_name, pickup_name, progressive_tier, category = line[:4] # print(tech_name, pickup_name, progressive_tier, category) result[tech_name] = { "pickup_name": pickup_name, "progressive_tier": progressive_tier, "category": category, } return result _custom_shuffled_count = { "Laser Weapons Damage": 0, "Follower Robot Count": 0, "Laser Shooting Speed": 0, "Mining Productivity": 4, "Physical Projectile Damage": 0, "Refined Flammables": 0, "Regular Inserter Capacity Bonus": 3, "Research Speed": 5, "Bulk Inserter Capacity Bonus": 4, "Stronger Explosives": 0, "Research Productivity": 5, "Toolbelt": 3, "Weapon Shooting Speed": 0, "Worker Robots Speed": 5, "Worker Robots Storage": 5, } def create_pickups(techs_raw: dict, existing_pickup_ids: dict[str, int], tech_csv: dict) -> dict: result = {} for tech_name, data in tech_csv.items(): pickup_name = data["pickup_name"] if pickup_name in result: result[pickup_name]["progression"].append(tech_name) if tech_name in existing_pickup_ids: if "original_locations" in result[pickup_name]: result[pickup_name]["original_locations"].append(existing_pickup_ids[tech_name]) else: tech = techs_raw[tech_name] if "icons" in tech: icon = tech["icons"][0]["icon"] else: icon = tech["icon"] result[pickup_name] = { "gui_category": data["category"], "hint_features": [data["category"]], "model_name": icon, "offworld_models": {}, "preferred_location_category": "major" if data["category"] != "enhancement" else "minor", "description": "", "progression": [tech_name], "expected_case_for_describer": "shuffled", } if pickup_name in _custom_shuffled_count: if _custom_shuffled_count[pickup_name] == 0: result[pickup_name]["expected_case_for_describer"] = "missing" else: result[pickup_name]["custom_count_for_shuffled_case"] = _custom_shuffled_count[pickup_name] if tech_name in existing_pickup_ids: result[pickup_name]["original_locations"] = [existing_pickup_ids[tech_name]] for pickup in result.values(): if len(pickup["progression"]) > 1: pickup["description"] = "Provides in order: " + " → ".join( importer_util.get_localized_name(tech_name) for tech_name in pickup["progression"] ) else: pickup.pop("description") result["Uranium Mining"]["expected_case_for_describer"] = "starting_item" result["Rocket Silo"]["expected_case_for_describer"] = "vanilla" result["Rocket Silo"]["hide_from_gui"] = True result["Rocket Silo"]["original_locations"] = result["Rocket Silo"].pop("original_locations") # move to the end return result def remove_unwanted_tech(tech_raw: dict[str, dict], tech_csv) -> dict: def filter_tech(name: str) -> bool: if name not in tech_csv: return False return not name.startswith("randovania-") return {key: value for key, value in tech_raw.items() if filter_tech(key)} def main(): parser = argparse.ArgumentParser() parser.add_argument("--factorio", type=Path, help="Path to the Factorio root folder.", required=True) parser.add_argument("--tech-csv", type=Path, help="Path to the CSV with tech definitions.", required=True) args = parser.parse_args() factorio_path: Path = args.factorio csv_path: Path = args.tech_csv rdv_factorio_path = Path(__file__).parents[2].joinpath("randovania/games/factorio") pickup_db_path = rdv_factorio_path.joinpath("pickup_database/pickup-database.json") header_path = rdv_factorio_path.joinpath("logic_database/header.json") raw_dump_path = factorio_path.joinpath("script-output/data-raw-dump.json") importer_util.read_locales(factorio_path) tech_csv = read_tech_csv(csv_path) existing_pickup_ids = importer_util.load_existing_pickup_ids(rdv_factorio_path.joinpath("logic_database/Tech.json")) with raw_dump_path.open() as f: raw_dump: dict[str, dict[str, typing.Any]] = json.load(f) recipes_raw = raw_dump["recipe"] data_parser.remove_expensive(recipes_raw) techs_raw = remove_unwanted_tech(raw_dump["technology"], tech_csv) json_lib.write_path(rdv_factorio_path.joinpath("assets", "recipes-raw.json"), recipes_raw) json_lib.write_path(rdv_factorio_path.joinpath("assets", "techs-raw.json"), techs_raw) with header_path.open() as f: header = json.load(f) header["resource_database"]["requirement_template"] = {} with pickup_db_path.open() as f: pickup_db = json.load(f) create_resources(header, data_parser.get_recipes_unlock_by_tech(techs_raw)) update_templates(header, recipes_raw, data_parser.get_techs_for_recipe(techs_raw)) pickup_db["standard_pickups"] = create_pickups(techs_raw, existing_pickup_ids, tech_csv) header["resource_database"]["requirement_template"] = dict( sorted(header["resource_database"]["requirement_template"].items(), key=lambda it: it[1]["display_name"]) ) with header_path.open("w") as f: json.dump(header, f, indent=4) with pickup_db_path.open("w") as f: json.dump(pickup_db, f, indent=4) if __name__ == "__main__": main()
0
0.866984
1
0.866984
game-dev
MEDIA
0.951187
game-dev
0.684784
1
0.684784
IAFEnvoy/IceAndFire-CE
1,991
common/src/main/java/com/iafenvoy/iceandfire/world/processor/DreadPortalProcessor.java
package com.iafenvoy.iceandfire.world.processor; import com.iafenvoy.iceandfire.registry.IafBlocks; import com.iafenvoy.iceandfire.registry.IafProcessors; import com.mojang.serialization.MapCodec; import net.minecraft.block.BlockState; import net.minecraft.structure.StructurePlacementData; import net.minecraft.structure.StructureTemplate; import net.minecraft.structure.processor.StructureProcessor; import net.minecraft.structure.processor.StructureProcessorType; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.random.Random; import net.minecraft.world.WorldView; public class DreadPortalProcessor extends StructureProcessor { public static final DreadPortalProcessor INSTANCE = new DreadPortalProcessor(); public static final MapCodec<DreadPortalProcessor> CODEC = MapCodec.unit(() -> INSTANCE); public static BlockState getRandomCrackedBlock(Random random) { float rand = random.nextFloat(); if (rand < 0.3) return IafBlocks.DREAD_STONE_BRICKS.get().getDefaultState(); else if (rand < 0.6) return IafBlocks.DREAD_STONE_BRICKS_CRACKED.get().getDefaultState(); else return IafBlocks.DREAD_STONE_BRICKS_MOSSY.get().getDefaultState(); } @Override public StructureTemplate.StructureBlockInfo process(WorldView world, BlockPos pos, BlockPos pivot, StructureTemplate.StructureBlockInfo originalBlockInfo, StructureTemplate.StructureBlockInfo currentBlockInfo, StructurePlacementData data) { Random random = data.getRandom(pos); float integrity = 1.0F; if (random.nextFloat() <= integrity && currentBlockInfo.state().isOf(IafBlocks.DREAD_STONE_BRICKS.get())) { BlockState state = getRandomCrackedBlock(random); return new StructureTemplate.StructureBlockInfo(pos, state, null); } return currentBlockInfo; } @Override protected StructureProcessorType<?> getType() { return IafProcessors.DREAD_PORTAL_PROCESSOR.get(); } }
0
0.899694
1
0.899694
game-dev
MEDIA
0.990999
game-dev
0.831391
1
0.831391
KoshakMineDEV/Lumi
1,286
src/main/java/cn/nukkit/block/BlockSlabTuffBrick.java
package cn.nukkit.block; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.block.data.BlockColor; public class BlockSlabTuffBrick extends BlockSlab { public BlockSlabTuffBrick() { this(0); } public BlockSlabTuffBrick(int meta) { super(meta, TUFF_BRICK_DOUBLE_SLAB); } @Override public int getId() { return TUFF_BRICK_SLAB; } @Override public String getName() { return "Tuff Brick Slab"; } @Override public double getHardness() { return 1.5; } @Override public double getResistance() { return 6; } @Override public int getToolType() { return ItemTool.TYPE_PICKAXE; } @Override public int getToolTier() { return ItemTool.TIER_WOODEN; } @Override public boolean canHarvestWithHand() { return false; } @Override public Item[] getDrops(Item item) { if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { return new Item[]{ toItem() }; } else { return Item.EMPTY_ARRAY; } } @Override public BlockColor getColor() { return BlockColor.GRAY_BLOCK_COLOR; } }
0
0.820263
1
0.820263
game-dev
MEDIA
0.978837
game-dev
0.514196
1
0.514196
CMU-SAFARI/PiDRAM
14,329
fpga-zynq/common/linux-xlnx/arch/x86/crypto/serpent-sse2-i586-asm_32.S
/* * Serpent Cipher 4-way parallel algorithm (i586/SSE2) * * Copyright (C) 2011 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * Based on crypto/serpent.c by * Copyright (C) 2002 Dag Arne Osvik <osvik@ii.uib.no> * 2003 Herbert Valerio Riedel <hvr@gnu.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * */ #include <linux/linkage.h> .file "serpent-sse2-i586-asm_32.S" .text #define arg_ctx 4 #define arg_dst 8 #define arg_src 12 #define arg_xor 16 /********************************************************************** 4-way SSE2 serpent **********************************************************************/ #define CTX %edx #define RA %xmm0 #define RB %xmm1 #define RC %xmm2 #define RD %xmm3 #define RE %xmm4 #define RT0 %xmm5 #define RT1 %xmm6 #define RNOT %xmm7 #define get_key(i, j, t) \ movd (4*(i)+(j))*4(CTX), t; \ pshufd $0, t, t; #define K(x0, x1, x2, x3, x4, i) \ get_key(i, 0, x4); \ get_key(i, 1, RT0); \ get_key(i, 2, RT1); \ pxor x4, x0; \ pxor RT0, x1; \ pxor RT1, x2; \ get_key(i, 3, x4); \ pxor x4, x3; #define LK(x0, x1, x2, x3, x4, i) \ movdqa x0, x4; \ pslld $13, x0; \ psrld $(32 - 13), x4; \ por x4, x0; \ pxor x0, x1; \ movdqa x2, x4; \ pslld $3, x2; \ psrld $(32 - 3), x4; \ por x4, x2; \ pxor x2, x1; \ movdqa x1, x4; \ pslld $1, x1; \ psrld $(32 - 1), x4; \ por x4, x1; \ movdqa x0, x4; \ pslld $3, x4; \ pxor x2, x3; \ pxor x4, x3; \ movdqa x3, x4; \ pslld $7, x3; \ psrld $(32 - 7), x4; \ por x4, x3; \ movdqa x1, x4; \ pslld $7, x4; \ pxor x1, x0; \ pxor x3, x0; \ pxor x3, x2; \ pxor x4, x2; \ movdqa x0, x4; \ get_key(i, 1, RT0); \ pxor RT0, x1; \ get_key(i, 3, RT0); \ pxor RT0, x3; \ pslld $5, x0; \ psrld $(32 - 5), x4; \ por x4, x0; \ movdqa x2, x4; \ pslld $22, x2; \ psrld $(32 - 22), x4; \ por x4, x2; \ get_key(i, 0, RT0); \ pxor RT0, x0; \ get_key(i, 2, RT0); \ pxor RT0, x2; #define KL(x0, x1, x2, x3, x4, i) \ K(x0, x1, x2, x3, x4, i); \ movdqa x0, x4; \ psrld $5, x0; \ pslld $(32 - 5), x4; \ por x4, x0; \ movdqa x2, x4; \ psrld $22, x2; \ pslld $(32 - 22), x4; \ por x4, x2; \ pxor x3, x2; \ pxor x3, x0; \ movdqa x1, x4; \ pslld $7, x4; \ pxor x1, x0; \ pxor x4, x2; \ movdqa x1, x4; \ psrld $1, x1; \ pslld $(32 - 1), x4; \ por x4, x1; \ movdqa x3, x4; \ psrld $7, x3; \ pslld $(32 - 7), x4; \ por x4, x3; \ pxor x0, x1; \ movdqa x0, x4; \ pslld $3, x4; \ pxor x4, x3; \ movdqa x0, x4; \ psrld $13, x0; \ pslld $(32 - 13), x4; \ por x4, x0; \ pxor x2, x1; \ pxor x2, x3; \ movdqa x2, x4; \ psrld $3, x2; \ pslld $(32 - 3), x4; \ por x4, x2; #define S0(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ por x0, x3; \ pxor x4, x0; \ pxor x2, x4; \ pxor RNOT, x4; \ pxor x1, x3; \ pand x0, x1; \ pxor x4, x1; \ pxor x0, x2; \ pxor x3, x0; \ por x0, x4; \ pxor x2, x0; \ pand x1, x2; \ pxor x2, x3; \ pxor RNOT, x1; \ pxor x4, x2; \ pxor x2, x1; #define S1(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x0, x1; \ pxor x3, x0; \ pxor RNOT, x3; \ pand x1, x4; \ por x1, x0; \ pxor x2, x3; \ pxor x3, x0; \ pxor x3, x1; \ pxor x4, x3; \ por x4, x1; \ pxor x2, x4; \ pand x0, x2; \ pxor x1, x2; \ por x0, x1; \ pxor RNOT, x0; \ pxor x2, x0; \ pxor x1, x4; #define S2(x0, x1, x2, x3, x4) \ pxor RNOT, x3; \ pxor x0, x1; \ movdqa x0, x4; \ pand x2, x0; \ pxor x3, x0; \ por x4, x3; \ pxor x1, x2; \ pxor x1, x3; \ pand x0, x1; \ pxor x2, x0; \ pand x3, x2; \ por x1, x3; \ pxor RNOT, x0; \ pxor x0, x3; \ pxor x0, x4; \ pxor x2, x0; \ por x2, x1; #define S3(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x3, x1; \ por x0, x3; \ pand x0, x4; \ pxor x2, x0; \ pxor x1, x2; \ pand x3, x1; \ pxor x3, x2; \ por x4, x0; \ pxor x3, x4; \ pxor x0, x1; \ pand x3, x0; \ pand x4, x3; \ pxor x2, x3; \ por x1, x4; \ pand x1, x2; \ pxor x3, x4; \ pxor x3, x0; \ pxor x2, x3; #define S4(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pand x0, x3; \ pxor x4, x0; \ pxor x2, x3; \ por x4, x2; \ pxor x1, x0; \ pxor x3, x4; \ por x0, x2; \ pxor x1, x2; \ pand x0, x1; \ pxor x4, x1; \ pand x2, x4; \ pxor x3, x2; \ pxor x0, x4; \ por x1, x3; \ pxor RNOT, x1; \ pxor x0, x3; #define S5(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ por x0, x1; \ pxor x1, x2; \ pxor RNOT, x3; \ pxor x0, x4; \ pxor x2, x0; \ pand x4, x1; \ por x3, x4; \ pxor x0, x4; \ pand x3, x0; \ pxor x3, x1; \ pxor x2, x3; \ pxor x1, x0; \ pand x4, x2; \ pxor x2, x1; \ pand x0, x2; \ pxor x2, x3; #define S6(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ pxor x0, x3; \ pxor x2, x1; \ pxor x0, x2; \ pand x3, x0; \ por x3, x1; \ pxor RNOT, x4; \ pxor x1, x0; \ pxor x2, x1; \ pxor x4, x3; \ pxor x0, x4; \ pand x0, x2; \ pxor x1, x4; \ pxor x3, x2; \ pand x1, x3; \ pxor x0, x3; \ pxor x2, x1; #define S7(x0, x1, x2, x3, x4) \ pxor RNOT, x1; \ movdqa x1, x4; \ pxor RNOT, x0; \ pand x2, x1; \ pxor x3, x1; \ por x4, x3; \ pxor x2, x4; \ pxor x3, x2; \ pxor x0, x3; \ por x1, x0; \ pand x0, x2; \ pxor x4, x0; \ pxor x3, x4; \ pand x0, x3; \ pxor x1, x4; \ pxor x4, x2; \ pxor x1, x3; \ por x0, x4; \ pxor x1, x4; #define SI0(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pxor x0, x1; \ por x1, x3; \ pxor x1, x4; \ pxor RNOT, x0; \ pxor x3, x2; \ pxor x0, x3; \ pand x1, x0; \ pxor x2, x0; \ pand x3, x2; \ pxor x4, x3; \ pxor x3, x2; \ pxor x3, x1; \ pand x0, x3; \ pxor x0, x1; \ pxor x2, x0; \ pxor x3, x4; #define SI1(x0, x1, x2, x3, x4) \ pxor x3, x1; \ movdqa x0, x4; \ pxor x2, x0; \ pxor RNOT, x2; \ por x1, x4; \ pxor x3, x4; \ pand x1, x3; \ pxor x2, x1; \ pand x4, x2; \ pxor x1, x4; \ por x3, x1; \ pxor x0, x3; \ pxor x0, x2; \ por x4, x0; \ pxor x4, x2; \ pxor x0, x1; \ pxor x1, x4; #define SI2(x0, x1, x2, x3, x4) \ pxor x1, x2; \ movdqa x3, x4; \ pxor RNOT, x3; \ por x2, x3; \ pxor x4, x2; \ pxor x0, x4; \ pxor x1, x3; \ por x2, x1; \ pxor x0, x2; \ pxor x4, x1; \ por x3, x4; \ pxor x3, x2; \ pxor x2, x4; \ pand x1, x2; \ pxor x3, x2; \ pxor x4, x3; \ pxor x0, x4; #define SI3(x0, x1, x2, x3, x4) \ pxor x1, x2; \ movdqa x1, x4; \ pand x2, x1; \ pxor x0, x1; \ por x4, x0; \ pxor x3, x4; \ pxor x3, x0; \ por x1, x3; \ pxor x2, x1; \ pxor x3, x1; \ pxor x2, x0; \ pxor x3, x2; \ pand x1, x3; \ pxor x0, x1; \ pand x2, x0; \ pxor x3, x4; \ pxor x0, x3; \ pxor x1, x0; #define SI4(x0, x1, x2, x3, x4) \ pxor x3, x2; \ movdqa x0, x4; \ pand x1, x0; \ pxor x2, x0; \ por x3, x2; \ pxor RNOT, x4; \ pxor x0, x1; \ pxor x2, x0; \ pand x4, x2; \ pxor x0, x2; \ por x4, x0; \ pxor x3, x0; \ pand x2, x3; \ pxor x3, x4; \ pxor x1, x3; \ pand x0, x1; \ pxor x1, x4; \ pxor x3, x0; #define SI5(x0, x1, x2, x3, x4) \ movdqa x1, x4; \ por x2, x1; \ pxor x4, x2; \ pxor x3, x1; \ pand x4, x3; \ pxor x3, x2; \ por x0, x3; \ pxor RNOT, x0; \ pxor x2, x3; \ por x0, x2; \ pxor x1, x4; \ pxor x4, x2; \ pand x0, x4; \ pxor x1, x0; \ pxor x3, x1; \ pand x2, x0; \ pxor x3, x2; \ pxor x2, x0; \ pxor x4, x2; \ pxor x3, x4; #define SI6(x0, x1, x2, x3, x4) \ pxor x2, x0; \ movdqa x0, x4; \ pand x3, x0; \ pxor x3, x2; \ pxor x2, x0; \ pxor x1, x3; \ por x4, x2; \ pxor x3, x2; \ pand x0, x3; \ pxor RNOT, x0; \ pxor x1, x3; \ pand x2, x1; \ pxor x0, x4; \ pxor x4, x3; \ pxor x2, x4; \ pxor x1, x0; \ pxor x0, x2; #define SI7(x0, x1, x2, x3, x4) \ movdqa x3, x4; \ pand x0, x3; \ pxor x2, x0; \ por x4, x2; \ pxor x1, x4; \ pxor RNOT, x0; \ por x3, x1; \ pxor x0, x4; \ pand x2, x0; \ pxor x1, x0; \ pand x2, x1; \ pxor x2, x3; \ pxor x3, x4; \ pand x3, x2; \ por x0, x3; \ pxor x4, x1; \ pxor x4, x3; \ pand x0, x4; \ pxor x2, x4; #define transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ movdqa x0, t2; \ punpckldq x1, x0; \ punpckhdq x1, t2; \ movdqa x2, t1; \ punpckhdq x3, x2; \ punpckldq x3, t1; \ movdqa x0, x1; \ punpcklqdq t1, x0; \ punpckhqdq t1, x1; \ movdqa t2, x3; \ punpcklqdq x2, t2; \ punpckhqdq x2, x3; \ movdqa t2, x2; #define read_blocks(in, x0, x1, x2, x3, t0, t1, t2) \ movdqu (0*4*4)(in), x0; \ movdqu (1*4*4)(in), x1; \ movdqu (2*4*4)(in), x2; \ movdqu (3*4*4)(in), x3; \ \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) #define write_blocks(out, x0, x1, x2, x3, t0, t1, t2) \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ \ movdqu x0, (0*4*4)(out); \ movdqu x1, (1*4*4)(out); \ movdqu x2, (2*4*4)(out); \ movdqu x3, (3*4*4)(out); #define xor_blocks(out, x0, x1, x2, x3, t0, t1, t2) \ transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \ \ movdqu (0*4*4)(out), t0; \ pxor t0, x0; \ movdqu x0, (0*4*4)(out); \ movdqu (1*4*4)(out), t0; \ pxor t0, x1; \ movdqu x1, (1*4*4)(out); \ movdqu (2*4*4)(out), t0; \ pxor t0, x2; \ movdqu x2, (2*4*4)(out); \ movdqu (3*4*4)(out), t0; \ pxor t0, x3; \ movdqu x3, (3*4*4)(out); ENTRY(__serpent_enc_blk_4way) /* input: * arg_ctx(%esp): ctx, CTX * arg_dst(%esp): dst * arg_src(%esp): src * arg_xor(%esp): bool, if true: xor output */ pcmpeqd RNOT, RNOT; movl arg_ctx(%esp), CTX; movl arg_src(%esp), %eax; read_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); K(RA, RB, RC, RD, RE, 0); S0(RA, RB, RC, RD, RE); LK(RC, RB, RD, RA, RE, 1); S1(RC, RB, RD, RA, RE); LK(RE, RD, RA, RC, RB, 2); S2(RE, RD, RA, RC, RB); LK(RB, RD, RE, RC, RA, 3); S3(RB, RD, RE, RC, RA); LK(RC, RA, RD, RB, RE, 4); S4(RC, RA, RD, RB, RE); LK(RA, RD, RB, RE, RC, 5); S5(RA, RD, RB, RE, RC); LK(RC, RA, RD, RE, RB, 6); S6(RC, RA, RD, RE, RB); LK(RD, RB, RA, RE, RC, 7); S7(RD, RB, RA, RE, RC); LK(RC, RA, RE, RD, RB, 8); S0(RC, RA, RE, RD, RB); LK(RE, RA, RD, RC, RB, 9); S1(RE, RA, RD, RC, RB); LK(RB, RD, RC, RE, RA, 10); S2(RB, RD, RC, RE, RA); LK(RA, RD, RB, RE, RC, 11); S3(RA, RD, RB, RE, RC); LK(RE, RC, RD, RA, RB, 12); S4(RE, RC, RD, RA, RB); LK(RC, RD, RA, RB, RE, 13); S5(RC, RD, RA, RB, RE); LK(RE, RC, RD, RB, RA, 14); S6(RE, RC, RD, RB, RA); LK(RD, RA, RC, RB, RE, 15); S7(RD, RA, RC, RB, RE); LK(RE, RC, RB, RD, RA, 16); S0(RE, RC, RB, RD, RA); LK(RB, RC, RD, RE, RA, 17); S1(RB, RC, RD, RE, RA); LK(RA, RD, RE, RB, RC, 18); S2(RA, RD, RE, RB, RC); LK(RC, RD, RA, RB, RE, 19); S3(RC, RD, RA, RB, RE); LK(RB, RE, RD, RC, RA, 20); S4(RB, RE, RD, RC, RA); LK(RE, RD, RC, RA, RB, 21); S5(RE, RD, RC, RA, RB); LK(RB, RE, RD, RA, RC, 22); S6(RB, RE, RD, RA, RC); LK(RD, RC, RE, RA, RB, 23); S7(RD, RC, RE, RA, RB); LK(RB, RE, RA, RD, RC, 24); S0(RB, RE, RA, RD, RC); LK(RA, RE, RD, RB, RC, 25); S1(RA, RE, RD, RB, RC); LK(RC, RD, RB, RA, RE, 26); S2(RC, RD, RB, RA, RE); LK(RE, RD, RC, RA, RB, 27); S3(RE, RD, RC, RA, RB); LK(RA, RB, RD, RE, RC, 28); S4(RA, RB, RD, RE, RC); LK(RB, RD, RE, RC, RA, 29); S5(RB, RD, RE, RC, RA); LK(RA, RB, RD, RC, RE, 30); S6(RA, RB, RD, RC, RE); LK(RD, RE, RB, RC, RA, 31); S7(RD, RE, RB, RC, RA); K(RA, RB, RC, RD, RE, 32); movl arg_dst(%esp), %eax; cmpb $0, arg_xor(%esp); jnz .L__enc_xor4; write_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); ret; .L__enc_xor4: xor_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); ret; ENDPROC(__serpent_enc_blk_4way) ENTRY(serpent_dec_blk_4way) /* input: * arg_ctx(%esp): ctx, CTX * arg_dst(%esp): dst * arg_src(%esp): src */ pcmpeqd RNOT, RNOT; movl arg_ctx(%esp), CTX; movl arg_src(%esp), %eax; read_blocks(%eax, RA, RB, RC, RD, RT0, RT1, RE); K(RA, RB, RC, RD, RE, 32); SI7(RA, RB, RC, RD, RE); KL(RB, RD, RA, RE, RC, 31); SI6(RB, RD, RA, RE, RC); KL(RA, RC, RE, RB, RD, 30); SI5(RA, RC, RE, RB, RD); KL(RC, RD, RA, RE, RB, 29); SI4(RC, RD, RA, RE, RB); KL(RC, RA, RB, RE, RD, 28); SI3(RC, RA, RB, RE, RD); KL(RB, RC, RD, RE, RA, 27); SI2(RB, RC, RD, RE, RA); KL(RC, RA, RE, RD, RB, 26); SI1(RC, RA, RE, RD, RB); KL(RB, RA, RE, RD, RC, 25); SI0(RB, RA, RE, RD, RC); KL(RE, RC, RA, RB, RD, 24); SI7(RE, RC, RA, RB, RD); KL(RC, RB, RE, RD, RA, 23); SI6(RC, RB, RE, RD, RA); KL(RE, RA, RD, RC, RB, 22); SI5(RE, RA, RD, RC, RB); KL(RA, RB, RE, RD, RC, 21); SI4(RA, RB, RE, RD, RC); KL(RA, RE, RC, RD, RB, 20); SI3(RA, RE, RC, RD, RB); KL(RC, RA, RB, RD, RE, 19); SI2(RC, RA, RB, RD, RE); KL(RA, RE, RD, RB, RC, 18); SI1(RA, RE, RD, RB, RC); KL(RC, RE, RD, RB, RA, 17); SI0(RC, RE, RD, RB, RA); KL(RD, RA, RE, RC, RB, 16); SI7(RD, RA, RE, RC, RB); KL(RA, RC, RD, RB, RE, 15); SI6(RA, RC, RD, RB, RE); KL(RD, RE, RB, RA, RC, 14); SI5(RD, RE, RB, RA, RC); KL(RE, RC, RD, RB, RA, 13); SI4(RE, RC, RD, RB, RA); KL(RE, RD, RA, RB, RC, 12); SI3(RE, RD, RA, RB, RC); KL(RA, RE, RC, RB, RD, 11); SI2(RA, RE, RC, RB, RD); KL(RE, RD, RB, RC, RA, 10); SI1(RE, RD, RB, RC, RA); KL(RA, RD, RB, RC, RE, 9); SI0(RA, RD, RB, RC, RE); KL(RB, RE, RD, RA, RC, 8); SI7(RB, RE, RD, RA, RC); KL(RE, RA, RB, RC, RD, 7); SI6(RE, RA, RB, RC, RD); KL(RB, RD, RC, RE, RA, 6); SI5(RB, RD, RC, RE, RA); KL(RD, RA, RB, RC, RE, 5); SI4(RD, RA, RB, RC, RE); KL(RD, RB, RE, RC, RA, 4); SI3(RD, RB, RE, RC, RA); KL(RE, RD, RA, RC, RB, 3); SI2(RE, RD, RA, RC, RB); KL(RD, RB, RC, RA, RE, 2); SI1(RD, RB, RC, RA, RE); KL(RE, RB, RC, RA, RD, 1); SI0(RE, RB, RC, RA, RD); K(RC, RD, RB, RE, RA, 0); movl arg_dst(%esp), %eax; write_blocks(%eax, RC, RD, RB, RE, RT0, RT1, RA); ret; ENDPROC(serpent_dec_blk_4way)
0
0.863547
1
0.863547
game-dev
MEDIA
0.53315
game-dev
0.759872
1
0.759872
BetonQuest/BetonQuest
1,106
src/main/java/org/betonquest/betonquest/compatibility/worldedit/WorldEditIntegrator.java
package org.betonquest.betonquest.compatibility.worldedit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import org.betonquest.betonquest.api.BetonQuestApi; import org.betonquest.betonquest.api.quest.PrimaryServerThreadData; import org.betonquest.betonquest.compatibility.Integrator; import org.bukkit.Bukkit; import java.io.File; /** * Integrator for WorldEdit. */ public class WorldEditIntegrator implements Integrator { /** * The default constructor. */ public WorldEditIntegrator() { } @Override public void hook(final BetonQuestApi api) { final WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"); final File folder = new File(worldEdit.getDataFolder(), "schematics"); final PrimaryServerThreadData data = api.getPrimaryServerThreadData(); api.getQuestRegistries().event().registerCombined("paste", new PasteSchematicEventFactory(folder, data)); } @Override public void reload() { // Empty } @Override public void close() { // Empty } }
0
0.592159
1
0.592159
game-dev
MEDIA
0.893007
game-dev
0.535796
1
0.535796
mgschwan/blensor
7,317
extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_DISCRETE_DYNAMICS_WORLD_H #define BT_DISCRETE_DYNAMICS_WORLD_H #include "btDynamicsWorld.h" class btDispatcher; class btOverlappingPairCache; class btConstraintSolver; class btSimulationIslandManager; class btTypedConstraint; class btActionInterface; class btPersistentManifold; class btIDebugDraw; struct InplaceSolverIslandCallback; #include "LinearMath/btAlignedObjectArray.h" ///btDiscreteDynamicsWorld provides discrete rigid body simulation ///those classes replace the obsolete CcdPhysicsEnvironment/CcdPhysicsController ATTRIBUTE_ALIGNED16(class) btDiscreteDynamicsWorld : public btDynamicsWorld { protected: btAlignedObjectArray<btTypedConstraint*> m_sortedConstraints; InplaceSolverIslandCallback* m_solverIslandCallback; btConstraintSolver* m_constraintSolver; btSimulationIslandManager* m_islandManager; btAlignedObjectArray<btTypedConstraint*> m_constraints; btAlignedObjectArray<btRigidBody*> m_nonStaticRigidBodies; btVector3 m_gravity; //for variable timesteps btScalar m_localTime; btScalar m_fixedTimeStep; //for variable timesteps bool m_ownsIslandManager; bool m_ownsConstraintSolver; bool m_synchronizeAllMotionStates; bool m_applySpeculativeContactRestitution; btAlignedObjectArray<btActionInterface*> m_actions; int m_profileTimings; bool m_latencyMotionStateInterpolation; btAlignedObjectArray<btPersistentManifold*> m_predictiveManifolds; virtual void predictUnconstraintMotion(btScalar timeStep); virtual void integrateTransforms(btScalar timeStep); virtual void calculateSimulationIslands(); virtual void solveConstraints(btContactSolverInfo& solverInfo); virtual void updateActivationState(btScalar timeStep); void updateActions(btScalar timeStep); void startProfiling(btScalar timeStep); virtual void internalSingleStepSimulation( btScalar timeStep); void createPredictiveContacts(btScalar timeStep); virtual void saveKinematicState(btScalar timeStep); void serializeRigidBodies(btSerializer* serializer); void serializeDynamicsWorldInfo(btSerializer* serializer); public: BT_DECLARE_ALIGNED_ALLOCATOR(); ///this btDiscreteDynamicsWorld constructor gets created objects from the user, and will not delete those btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); virtual ~btDiscreteDynamicsWorld(); ///if maxSubSteps > 0, it will interpolate motion between fixedTimeStep's virtual int stepSimulation( btScalar timeStep,int maxSubSteps=1, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.)); virtual void synchronizeMotionStates(); ///this can be useful to synchronize a single rigid body -> graphics object void synchronizeSingleMotionState(btRigidBody* body); virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies=false); virtual void removeConstraint(btTypedConstraint* constraint); virtual void addAction(btActionInterface*); virtual void removeAction(btActionInterface*); btSimulationIslandManager* getSimulationIslandManager() { return m_islandManager; } const btSimulationIslandManager* getSimulationIslandManager() const { return m_islandManager; } btCollisionWorld* getCollisionWorld() { return this; } virtual void setGravity(const btVector3& gravity); virtual btVector3 getGravity () const; virtual void addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::StaticFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter); virtual void addRigidBody(btRigidBody* body); virtual void addRigidBody(btRigidBody* body, short group, short mask); virtual void removeRigidBody(btRigidBody* body); ///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btCollisionWorld::removeCollisionObject virtual void removeCollisionObject(btCollisionObject* collisionObject); virtual void debugDrawConstraint(btTypedConstraint* constraint); virtual void debugDrawWorld(); virtual void setConstraintSolver(btConstraintSolver* solver); virtual btConstraintSolver* getConstraintSolver(); virtual int getNumConstraints() const; virtual btTypedConstraint* getConstraint(int index) ; virtual const btTypedConstraint* getConstraint(int index) const; virtual btDynamicsWorldType getWorldType() const { return BT_DISCRETE_DYNAMICS_WORLD; } ///the forces on each rigidbody is accumulating together with gravity. clear this after each timestep. virtual void clearForces(); ///apply gravity, call this once per timestep virtual void applyGravity(); virtual void setNumTasks(int numTasks) { (void) numTasks; } ///obsolete, use updateActions instead virtual void updateVehicles(btScalar timeStep) { updateActions(timeStep); } ///obsolete, use addAction instead virtual void addVehicle(btActionInterface* vehicle); ///obsolete, use removeAction instead virtual void removeVehicle(btActionInterface* vehicle); ///obsolete, use addAction instead virtual void addCharacter(btActionInterface* character); ///obsolete, use removeAction instead virtual void removeCharacter(btActionInterface* character); void setSynchronizeAllMotionStates(bool synchronizeAll) { m_synchronizeAllMotionStates = synchronizeAll; } bool getSynchronizeAllMotionStates() const { return m_synchronizeAllMotionStates; } void setApplySpeculativeContactRestitution(bool enable) { m_applySpeculativeContactRestitution = enable; } bool getApplySpeculativeContactRestitution() const { return m_applySpeculativeContactRestitution; } ///Preliminary serialization test for Bullet 2.76. Loading those files requires a separate parser (see Bullet/Demos/SerializeDemo) virtual void serialize(btSerializer* serializer); ///Interpolate motion state between previous and current transform, instead of current and next transform. ///This can relieve discontinuities in the rendering, due to penetrations void setLatencyMotionStateInterpolation(bool latencyInterpolation ) { m_latencyMotionStateInterpolation = latencyInterpolation; } bool getLatencyMotionStateInterpolation() const { return m_latencyMotionStateInterpolation; } }; #endif //BT_DISCRETE_DYNAMICS_WORLD_H
0
0.870586
1
0.870586
game-dev
MEDIA
0.986747
game-dev
0.815231
1
0.815231
brnkhy/MapzenGo
1,872
Assets/MapzenGo/Plugins/UniRx/Scripts/UnityEngineBridge/Triggers/ObservableRectTransformTrigger.cs
// after uGUI(from 4.6) #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5) using System; using UnityEngine; namespace UniRx.Triggers { [DisallowMultipleComponent] public class ObservableRectTransformTrigger : ObservableTriggerBase { Subject<Unit> onRectTransformDimensionsChange; // Callback that is sent if an associated RectTransform has it's dimensions changed public void OnRectTransformDimensionsChange() { if (onRectTransformDimensionsChange != null) onRectTransformDimensionsChange.OnNext(Unit.Default); } /// <summary>Callback that is sent if an associated RectTransform has it's dimensions changed.</summary> public IObservable<Unit> OnRectTransformDimensionsChangeAsObservable() { return onRectTransformDimensionsChange ?? (onRectTransformDimensionsChange = new Subject<Unit>()); } Subject<Unit> onRectTransformRemoved; // Callback that is sent if an associated RectTransform is removed public void OnRectTransformRemoved() { if (onRectTransformRemoved != null) onRectTransformRemoved.OnNext(Unit.Default); } /// <summary>Callback that is sent if an associated RectTransform is removed.</summary> public IObservable<Unit> OnRectTransformRemovedAsObservable() { return onRectTransformRemoved ?? (onRectTransformRemoved = new Subject<Unit>()); } protected override void RaiseOnCompletedOnDestroy() { if (onRectTransformDimensionsChange != null) { onRectTransformDimensionsChange.OnCompleted(); } if (onRectTransformRemoved != null) { onRectTransformRemoved.OnCompleted(); } } } } #endif
0
0.92962
1
0.92962
game-dev
MEDIA
0.351976
game-dev
0.896129
1
0.896129
gorustyt/go-pathfinding
4,256
jpf_move_diagonally_If_no_obstacles.go
package path_finding import "math" func (grid *Grid) JPFMoveDiagonallyIfNoObstaclesFind(node *GridNodeInfo) (neighbors []*GridNode) { var ( parent = node.Parent x = node.X y = node.Y px, py, dx, dy int ) // directed pruning: can ignore most neighbors, unless forced. if parent != nil { px = parent.X py = parent.Y // get the normalized direction of travel dx = (x - px) / int(math.Max(math.Abs(float64(x-px)), float64(1))) dy = (y - py) / int(math.Max(math.Abs(float64(y-py)), float64(1))) // search diagonally if dx != 0 && dy != 0 { if grid.isWalkableAt(x, y+dy) { neighbors = append(neighbors, grid.getNodeAt(x, y+dy)) } if grid.isWalkableAt(x+dx, y) { neighbors = append(neighbors, grid.getNodeAt(x+dx, y)) } if grid.isWalkableAt(x, y+dy) && grid.isWalkableAt(x+dx, y) { neighbors = append(neighbors, grid.getNodeAt(x+dx, y+dy)) } } else { // search horizontally/vertically var isNextWalkable bool if dx != 0 { isNextWalkable = grid.isWalkableAt(x+dx, y) var isTopWalkable = grid.isWalkableAt(x, y+1) var isBottomWalkable = grid.isWalkableAt(x, y-1) if isNextWalkable { neighbors = append(neighbors, grid.getNodeAt(x+dx, y)) if isTopWalkable { neighbors = append(neighbors, grid.getNodeAt(x+dx, y+1)) } if isBottomWalkable { neighbors = append(neighbors, grid.getNodeAt(x+dx, y-1)) } } if isTopWalkable { neighbors = append(neighbors, grid.getNodeAt(x, y+1)) } if isBottomWalkable { neighbors = append(neighbors, grid.getNodeAt(x, y-1)) } } else if dy != 0 { isNextWalkable = grid.isWalkableAt(x, y+dy) var isRightWalkable = grid.isWalkableAt(x+1, y) var isLeftWalkable = grid.isWalkableAt(x-1, y) if isNextWalkable { neighbors = append(neighbors, grid.getNodeAt(x, y+dy)) if isRightWalkable { neighbors = append(neighbors, grid.getNodeAt(x+1, y+dy)) } if isLeftWalkable { neighbors = append(neighbors, grid.getNodeAt(x-1, y+dy)) } } if isRightWalkable { neighbors = append(neighbors, grid.getNodeAt(x+1, y)) } if isLeftWalkable { neighbors = append(neighbors, grid.getNodeAt(x-1, y)) } } } } // return all neighbors else { neighborNodes := grid.getNeighbors(node.GridNode, DiagonalMovementOnlyWhenNoObstacles) for _, neighbor := range neighborNodes { neighbors = append(neighbors, grid.getNodeAt(neighbor.X, neighbor.Y)) } return neighbors } func (grid *Grid) JPFMoveDiagonallyIfNoObstaclesJump(x, y, px, py int, endNode *GridNode) (jumpPoint *GridNode) { dx := x - px dy := y - py if !grid.isWalkableAt(x, y) { return nil } if !grid.TracePath(grid.getNodeAt(x, y)) { return } if grid.getNodeAt(x, y) == endNode { return grid.getNodeAt(x, y) } // check for forced neighbors // along the diagonal if dx != 0 && dy != 0 { // if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || // (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { // return [x, y]; // } // when moving diagonally, must check for vertical/horizontal jump points if grid.JPFMoveDiagonallyIfNoObstaclesJump(x+dx, y, x, y, endNode) != nil || grid.JPFMoveDiagonallyIfNoObstaclesJump(x, y+dy, x, y, endNode) != nil { return grid.getNodeAt(x, y) } } else { // horizontally/vertically if dx != 0 { if (grid.isWalkableAt(x, y-1) && !grid.isWalkableAt(x-dx, y-1)) || (grid.isWalkableAt(x, y+1) && !grid.isWalkableAt(x-dx, y+1)) { return grid.getNodeAt(x, y) } } else if dy != 0 { if (grid.isWalkableAt(x-1, y) && !grid.isWalkableAt(x-1, y-dy)) || (grid.isWalkableAt(x+1, y) && !grid.isWalkableAt(x+1, y-dy)) { return grid.getNodeAt(x, y) } // When moving vertically, must check for horizontal jump points // if (this._jump(x + 1, y, x, y) || this._jump(x - 1, y, x, y)) { // return [x, y]; // } } } // moving diagonally, must make sure one of the vertical/horizontal // neighbors is open to allow the path if grid.isWalkableAt(x+dx, y) && grid.isWalkableAt(x, y+dy) { return grid.JPFMoveDiagonallyIfNoObstaclesJump(x+dx, y+dy, x, y, endNode) } else { return nil } }
0
0.863215
1
0.863215
game-dev
MEDIA
0.780011
game-dev
0.950674
1
0.950674
Xeeynamo/sotn-decomp
73,636
src/servant/tt_002/faerie.c
// SPDX-License-Identifier: AGPL-3.0-or-later #include "common.h" #include "faerie.h" #include "sfx.h" #include "items.h" #include "../servant_private.h" static u32 s_AnimationStatus; static s32 s_HintTargetX; static s32 s_HintTargetY; static s32 s_ServantId; static s32 s_zPriority; static FamiliarStats s_FaerieStats; static s32 s_ElementalDamageStatus; static s32 s_UseResistDelayTimer; static s32 s_UseResistClearTimer; static s32 s_HpDifferenceHistory[5]; static s32 s_CachedHp; static s16 s_HpDifferenceIndex; STATIC_PAD_BSS(2); static s16 s_HpCacheResetTimer; STATIC_PAD_BSS(2); static s32 s_RoomSpecialState; static s32 D_us_80179320; // Possibly when player is sitting static s32 s_TargetLocationX; static s32 s_TargetLocationY; static s32 s_TargetLocationX_calc; static s32 s_TargetLocationY_calc; static s32 s_AngleToTarget; static s32 s_AllowedAngle; static s32 s_DistToTargetLocation; static s16 s_TargetLocOffset_calc; extern u16 g_FaerieClut[64]; extern FaerieAbilityStats g_FaerieAbilityStats[]; extern FaerieSfx g_FaerieSfx; extern s16 g_ResistItemsParamMap[]; extern s16 g_PotionItemsParamMap[]; extern unkGraphicsStruct g_unkGraphicsStruct; extern ItemPrimitiveParams g_ItemPrimitiveParams[]; extern u16 g_FaerieFrameCount1; extern u16 g_FaerieFrameCount2; extern s32 g_SfxRandomizerGrunt[]; extern s32 g_SfxRandomizerHammerResist[]; extern HintTriggerMap g_FaerieHints[]; extern FaerieWingAnimationParams g_WingAnimationParams[]; extern AnimationFrame* g_FaerieAnimationFrames[]; void unused_39C8(Entity*); void CheckForValidAbility(Entity*); static void UpdateServantUseLifeApple(Entity* self); static void UpdateServantUseHammer(Entity* self); static void UpdateServantUseUncurse(Entity* self); static void UpdateServantUseAntivenom(Entity* self); static void UpdateServantUseElementalResist(Entity* self); static void UpdateServantUsePotion(Entity* self); static void UpdateServantAdditionalInit(Entity* self); static void UpdateSubEntityWings(Entity* self); static void UpdateServantSitOnShoulder(Entity* self); static void UpdateServantOfferHint(Entity* self); static void UpdateEntitySetRoomSpecialState(Entity* self); static void UpdateSubEntityUseLifeApple(Entity* self); static void UpdateServantSfxPassthrough(Entity* self); static void UpdateSubEntityUseItem(Entity* self); ServantDesc faerie_ServantDesc = { ServantInit, UpdateServantDefault, UpdateServantUseLifeApple, UpdateServantUseHammer, UpdateServantUseUncurse, UpdateServantUseAntivenom, UpdateServantUseElementalResist, UpdateServantUsePotion, UpdateServantAdditionalInit, UpdateSubEntityWings, UpdateServantSitOnShoulder, UpdateServantOfferHint, UpdateEntitySetRoomSpecialState, UpdateSubEntityUseLifeApple, UpdateServantSfxPassthrough, UpdateSubEntityUseItem}; static void SetAnimationFrame(Entity* self, s32 animationIndex) { if (self->anim != g_FaerieAnimationFrames[animationIndex]) { self->anim = g_FaerieAnimationFrames[animationIndex]; self->pose = 0; self->poseTimer = 0; } } void unused_39C8(Entity* arg0) {} void ExecuteAbilityInitialize(Entity* self) { if (!self->ext.faerie.isAbilityInitialized) { switch (self->entityId) { case FAERIE_MODE_DEFAULT_UPDATE: case FAERIE_MODE_ADDITIONAL_INIT: self->flags = FLAG_POS_CAMERA_LOCKED | FLAG_KEEP_ALIVE_OFFCAMERA | FLAG_UNK_20000; SetAnimationFrame(self, 0xE); self->ext.faerie.randomMovementAngle = rand() % 4096; self->ext.faerie.targetAngle = 0; self->ext.faerie.defaultDistToTargetLoc = 8; self->ext.faerie.maxAngle = 0x20; self->step++; break; case FAERIE_SUBENTITY_WINGS: self->flags = FLAG_POS_CAMERA_LOCKED | FLAG_KEEP_ALIVE_OFFCAMERA | FLAG_UNK_20000; self->step++; break; } } else { switch (self->entityId) { case FAERIE_MODE_DEFAULT_UPDATE: self->ext.faerie.timer = 120; // fallthrough case FAERIE_MODE_USE_LIFE_APPLE: case FAERIE_MODE_USE_HAMMER: case FAERIE_MODE_USE_UNCURSE: case FAERIE_MODE_USE_ANTIVENOM: case FAERIE_MODE_USE_ELEMENTAL_RESIST: case FAERIE_MODE_USE_POTION: case FAERIE_MODE_SIT_ON_SHOULDER: case FAERIE_MODE_OFFER_HINT: self->flags = FLAG_POS_CAMERA_LOCKED | FLAG_KEEP_ALIVE_OFFCAMERA | FLAG_UNK_20000; SetAnimationFrame(self, 0xE); self->step++; break; case FAERIE_SUBENTITY_WINGS: self->flags = FLAG_POS_CAMERA_LOCKED | FLAG_KEEP_ALIVE_OFFCAMERA | FLAG_UNK_20000; self->step++; } } self->ext.faerie.isAbilityInitialized = self->entityId; s_RoomSpecialState = 0; } // This is a duplicate CreateEventEntity which is lower in the file, but we need // both to match the binary for PSX. They are identical, but faerie uses this // one. void CreateEventEntity_Local(Entity* entityParent, s32 entityId, s32 params) { Entity* entity; s32 i; for (i = 0; i < 3; i++) { entity = &g_Entities[5 + i]; if (!entity->entityId) { break; } } if (!entity->entityId) { DestroyEntity(entity); entity->entityId = entityId; entity->zPriority = entityParent->zPriority; entity->facingLeft = entityParent->facingLeft; entity->flags = FLAG_KEEP_ALIVE_OFFCAMERA; entity->posX.val = entityParent->posX.val; entity->posY.val = entityParent->posY.val; // Not necessarily making batFamBlueTrail here, but // that's an Ext that works. Just needs parent at 0x8C. entity->ext.batFamBlueTrail.parent = entityParent; entity->params = params; } } void SelectAnimationFrame(Entity* self) { if (abs(self->velocityY) > abs(self->velocityX)) { if (abs(self->velocityY) < FIX(0.5)) { if (self->ext.faerie.animationFlag == 1) { self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0x29); } else if (self->ext.faerie.animationFlag == 2) { self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0xE); } } else if (abs(self->velocityY) > FIX(1)) { if (self->velocityY >= 0) { self->ext.faerie.animationFlag = 2; SetAnimationFrame(self, 0xB); } else { self->ext.faerie.animationFlag = 2; SetAnimationFrame(self, 0xC); } } } else { if (abs(self->velocityX) > FIX(0.5625)) { if (self->ext.faerie.animationFlag == 0) { self->ext.faerie.animationFlag = 1; SetAnimationFrame(self, 0xF); } else if (self->ext.faerie.animationFlag == 2) { self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0xE); } } else if (abs(self->velocityX) < FIX(0.375)) { if (self->ext.faerie.animationFlag == 1) { self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0x29); } else if (self->ext.faerie.animationFlag == 2) { self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0xE); } } if (abs(self->velocityX) > FIX(0.5)) { if (self->velocityX >= 0) { self->facingLeft = 1; } else { self->facingLeft = 0; } } } } void CheckForValidAbility(Entity* self) { s32 i; s32 params; s32 rnd; s32 unkHpSum; s32 playerUnk18Flag; g_api.GetServantStats(self, 0, 0, &s_FaerieStats); playerUnk18Flag = g_Player.unk18 & 0xFA00; if (playerUnk18Flag) { if ((s_ElementalDamageStatus & playerUnk18Flag) == playerUnk18Flag) { s_UseResistClearTimer = 0; s_UseResistDelayTimer++; s_ElementalDamageStatus = playerUnk18Flag & s_ElementalDamageStatus; } else { s_UseResistDelayTimer = 0; s_ElementalDamageStatus |= playerUnk18Flag; } } else { s_UseResistClearTimer++; if (s_UseResistClearTimer > 3600) { s_ElementalDamageStatus = s_UseResistDelayTimer = s_UseResistClearTimer = 0; } } if (s_CachedHp > g_Status.hp) { s_HpDifferenceHistory[s_HpDifferenceIndex++] = s_CachedHp - g_Status.hp; if (s_HpDifferenceIndex > 4) { s_HpDifferenceIndex = 0; } s_CachedHp = g_Status.hp; s_HpCacheResetTimer = 0; } else { s_HpCacheResetTimer++; if (s_HpCacheResetTimer > 120) { s_HpDifferenceIndex = 0; s_HpCacheResetTimer = 0; s_CachedHp = g_Status.hp; for (i = 0; i < 5; i++) { s_HpDifferenceHistory[i] = 0; } } } if (g_Player.status & PLAYER_STATUS_DEAD) { rnd = rand() % 100; // for faerie, always true. stats table.lifeAppleChance is 0x00FF if (rnd <= g_FaerieAbilityStats[s_FaerieStats.level / 10].lifeAppleChance) { self->entityId = FAERIE_MODE_USE_LIFE_APPLE; self->step = 0; return; } } if (self->ext.faerie.timer < 0) { return; } if (self->ext.faerie.timer) { self->ext.faerie.timer--; return; } self->ext.faerie.timer = g_FaerieAbilityStats[s_FaerieStats.level / 10].timer; if (self->entityId == FAERIE_MODE_USE_HAMMER) { return; } if (PLAYER.step == 0xB && (!IsMovementAllowed(0)) && g_Status.equipHandCount[ITEM_HAMMER]) { rnd = rand() % 100; if (rnd <= g_FaerieAbilityStats[(s_FaerieStats.level / 10)].hammerChance) { self->ext.faerie.unk8E = 0; self->entityId = FAERIE_MODE_USE_HAMMER; self->step = 0; return; } } if (self->entityId == FAERIE_MODE_USE_UNCURSE) { return; } if (g_Player.status & PLAYER_STATUS_CURSE) { if (g_Status.equipHandCount[ITEM_UNCURSE]) { rnd = rand() % 100; if (rnd <= g_FaerieAbilityStats[(s_FaerieStats.level / 10)] .uncurseChance) { self->ext.faerie.requireUncurseLuckCheck = false; self->entityId = FAERIE_MODE_USE_UNCURSE; self->step = 0; return; } } if (!self->ext.faerie.requireUncurseLuckCheck) { self->ext.faerie.requireUncurseLuckCheck = true; self->entityId = FAERIE_MODE_USE_UNCURSE; self->step = 0; return; } } if (self->entityId == FAERIE_MODE_USE_ANTIVENOM) { return; } if (g_Player.status & PLAYER_STATUS_POISON) { if (g_Status.equipHandCount[ITEM_ANTIVENOM]) { rnd = rand() % 100; if (rnd <= g_FaerieAbilityStats[s_FaerieStats.level / 10] .antivenomChance) { self->ext.faerie.requireAntivenomLuckCheck = false; self->entityId = FAERIE_MODE_USE_ANTIVENOM; self->step = 0; return; } } if (!self->ext.faerie.requireAntivenomLuckCheck) { self->ext.faerie.requireAntivenomLuckCheck = true; self->entityId = FAERIE_MODE_USE_ANTIVENOM; self->step = 0; return; } } if (s_UseResistDelayTimer >= 10) { if (s_ElementalDamageStatus & ELEMENT_FIRE) { params = 0; } else if (s_ElementalDamageStatus & ELEMENT_THUNDER) { params = 1; } else if (s_ElementalDamageStatus & ELEMENT_ICE) { params = 2; } else if (s_ElementalDamageStatus & ELEMENT_HOLY) { params = 3; } else if (s_ElementalDamageStatus & ELEMENT_DARK) { params = 4; } else if (s_ElementalDamageStatus & ELEMENT_STONE) { params = 5; } if (!g_api.GetStatBuffTimer(g_ResistItemsParamMap[params * 4]) && g_Status.equipHandCount[g_ResistItemsParamMap[(params * 4) + 1]]) { rnd = rand() % 100; if (rnd <= g_FaerieAbilityStats[s_FaerieStats.level / 10].resistChance) { self->entityId = FAERIE_MODE_USE_ELEMENTAL_RESIST; self->step = 0; self->params = params; s_UseResistClearTimer = 0; s_UseResistDelayTimer = 0; return; } } } if (self->entityId == FAERIE_MODE_USE_POTION) { return; } for (unkHpSum = 0, params = 0, i = 0; i < 5; i++) { unkHpSum += s_HpDifferenceHistory[i]; } if (unkHpSum >= (g_Status.hpMax / 2)) { if (g_Status.hpMax < 100) { params = 1; } else { params = 2; } } if (g_Status.hp <= (g_Status.hpMax / 10)) { if (g_Status.hpMax < 100) { params = 1; } else { params = 2; } } // if health greater than ¼ max if (!(g_Status.hp > (g_Status.hpMax >> 2))) { if (unkHpSum >= (g_Status.hpMax / 8)) { params = 2; } else if (unkHpSum >= (g_Status.hpMax / 16)) { params = 1; } } if (!params) { return; } if (g_Status.equipHandCount[ITEM_POTION] | g_Status.equipHandCount[ITEM_HIGH_POTION]) { rnd = rand() % 100; if (rnd <= g_FaerieAbilityStats[s_FaerieStats.level / 10].healChance) { // This is likely a bug as it breaks the pattern. // variable also only ever gets set and never cleared self->ext.faerie.requirePotionLuckCheck = true; self->entityId = FAERIE_MODE_USE_POTION; self->step = 0; self->params = params - 1; s_HpDifferenceIndex = 0; s_HpCacheResetTimer = 0; s_CachedHp = g_Status.hp; for (i = 0; i < 5; i++) { s_HpDifferenceHistory[i] = 0; } } } else { if (!self->ext.faerie.requirePotionLuckCheck) { self->ext.faerie.requirePotionLuckCheck = true; self->entityId = FAERIE_MODE_USE_POTION; self->step = 0; self->params = params - 1; s_HpDifferenceIndex = 0; s_HpCacheResetTimer = 0; s_CachedHp = g_Status.hp; for (i = 0; i < 5; i++) { s_HpDifferenceHistory[i] = 0; } } } } void ServantInit(InitializeMode mode) { u16* src; u16* dst; RECT rect; s32 i; SpriteParts** spriteBanks; Entity* entity; #ifdef VERSION_PC const int len = LEN(g_FaerieClut); #else const int len = 256; #endif s_ServantId = g_Servant; if ((mode == MENU_SWITCH_SERVANT) || (mode == MENU_SAME_SERVANT)) { ProcessEvent(NULL, true); if (mode == MENU_SAME_SERVANT) { return; } } dst = &g_Clut[1][CLUT_INDEX_SERVANT]; src = g_FaerieClut; for (i = 0; i < len; i++) { *dst++ = *src++; } rect.x = 0; rect.w = 0x100; rect.h = 1; rect.y = 0xF4; dst = &g_Clut[1][CLUT_INDEX_SERVANT]; LoadImage(&rect, (u_long*)dst); spriteBanks = g_api.o.spriteBanks; spriteBanks += 20; *spriteBanks = (SpriteParts*)g_FaerieSpriteParts; entity = &g_Entities[SERVANT_ENTITY_INDEX]; DestroyEntity(entity); entity->unk5A = 0x6C; entity->palette = 0x140; entity->animSet = ANIMSET_OVL(20); entity->zPriority = PLAYER.zPriority - 2; entity->facingLeft = PLAYER.facingLeft; entity->params = 0; if (mode == MENU_SWITCH_SERVANT) { // PSP version does this in 2 chunks, the PSX version uses an lw instruction #ifdef VERSION_PSP if (D_8003C708.flags & LAYOUT_RECT_PARAMS_UNKNOWN_20 || D_8003C708.flags & LAYOUT_RECT_PARAMS_UNKNOWN_40) { #else if (LOW(D_8003C708.flags) & (LAYOUT_RECT_PARAMS_UNKNOWN_20 | LAYOUT_RECT_PARAMS_UNKNOWN_40)) { #endif entity->entityId = FAERIE_MODE_DEFAULT_UPDATE; } else { entity->entityId = FAERIE_MODE_ADDITIONAL_INIT; } entity->posX.val = FIX(128); entity->posY.val = FIX(-32); } else { entity->entityId = FAERIE_MODE_DEFAULT_UPDATE; if (D_8003C708.flags & LAYOUT_RECT_PARAMS_UNKNOWN_20) { if (ServantUnk0()) { entity->posX.val = FIX(192); } else { entity->posX.val = FIX(64); } entity->posY.val = FIX(160); } else { entity->posX.val = PLAYER.posX.val + (PLAYER.facingLeft ? FIX(24) : FIX(-24)); entity->posY.val = PLAYER.posY.val + FIX(-32); } } s_zPriority = (s32)entity->zPriority; g_api.GetServantStats(entity, 0, 0, &s_FaerieStats); entity++; DestroyEntity(entity); entity->entityId = FAERIE_SUBENTITY_WINGS; entity->unk5A = 0x6C; entity->palette = 0x140; entity->animSet = ANIMSET_OVL(20); entity->zPriority = PLAYER.zPriority - 3; entity->facingLeft = PLAYER.facingLeft; entity->params = 0; s_RoomSpecialState = 0; D_us_80179320 = 0; g_api.GetServantStats(entity, 0, 0, &s_FaerieStats); } void UpdateServantDefault(Entity* self) { g_api.GetServantStats(self, 0, 0, &s_FaerieStats); if (D_us_80179320) { self->zPriority = PLAYER.zPriority - 2; s_zPriority = self->zPriority; } if (D_8003C708.flags & FLAG_UNK_20) { switch (ServantUnk0()) { case 0: s_TargetLocationX = 0x40; break; case 1: s_TargetLocationX = 0xC0; break; case 2: s_TargetLocationX = self->posX.i.hi > 0x80 ? 0xC0 : 0x40; break; } s_TargetLocationY = 0xA0; } else { s_TargetLocOffset_calc = -0x18; if (PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX_calc = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY_calc = PLAYER.posY.i.hi - 0x20; s_AngleToTarget = self->ext.faerie.randomMovementAngle; self->ext.faerie.randomMovementAngle += 0x10; self->ext.faerie.randomMovementAngle &= 0xfff; s_DistToTargetLocation = self->ext.faerie.defaultDistToTargetLoc; s_TargetLocationX = s_TargetLocationX_calc + ((rcos(s_AngleToTarget / 2) * s_DistToTargetLocation) >> 0xC); s_TargetLocationY = s_TargetLocationY_calc - ((rsin(s_AngleToTarget) * (s_DistToTargetLocation / 2)) >> 0xC); } switch (self->step) { case 0: ExecuteAbilityInitialize(self); self->ext.faerie.animationFlag = 0; SetAnimationFrame(self, 0xE); s_CachedHp = g_Status.hp; s_HpDifferenceIndex = 0; s_HpCacheResetTimer = 0; self->ext.faerie.idleFrameCounter = 0; break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, self->ext.faerie.maxAngle); self->ext.faerie.targetAngle = s_AllowedAngle; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 0x28) { self->velocityY = -(rsin(s_AllowedAngle) << 3); self->velocityX = rcos(s_AllowedAngle) << 3; self->ext.faerie.maxAngle = 0x20; } else if (s_DistToTargetLocation < 0x3C) { self->velocityY = -(rsin(s_AllowedAngle) << 4); self->velocityX = rcos(s_AllowedAngle) << 4; self->ext.faerie.maxAngle = 0x40; } else if (s_DistToTargetLocation < 0x64) { self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; self->ext.faerie.maxAngle = 0x60; } else if (s_DistToTargetLocation < 0x100) { self->velocityY = -(rsin(s_AllowedAngle) << 6); self->velocityX = rcos(s_AllowedAngle) << 6; self->ext.faerie.maxAngle = 0x80; } else { self->velocityX = (s_TargetLocationX - self->posX.i.hi) << 0xE; self->velocityY = (s_TargetLocationY - self->posY.i.hi) << 0xE; self->ext.faerie.maxAngle = 0x80; } SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; if (!g_CutsceneHasControl && !IsMovementAllowed(1) && !CheckAllEntitiesValid() && !(D_8003C708.flags & FLAG_UNK_20)) { self->ext.faerie.idleFrameCounter += 1; } else { self->ext.faerie.idleFrameCounter = 0; } if (self->ext.faerie.idleFrameCounter > 0x708) { self->entityId = FAERIE_MODE_SIT_ON_SHOULDER; self->step = 0; return; } if (s_RoomSpecialState >= 2) { self->entityId = FAERIE_MODE_OFFER_HINT; self->step = 0; self->params = s_RoomSpecialState - ROOM_STATE_TO_HINT_OFFSET; } break; } ProcessEvent(self, false); if (!g_CutsceneHasControl) { CheckForValidAbility(self); } unused_39C8(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUseLifeApple(Entity* self) { s32 i; switch (self->step) { case 0: ExecuteAbilityInitialize(self); self->ext.faerie.frameCounter = 0; break; case 1: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter <= 24) { break; } self->step++; // fallthrough case 2: if (!g_Status.equipHandCount[ITEM_LIFE_APPLE]) { self->step = 0x5A; break; } self->step++; // fallthrough case 3: if (!g_unkGraphicsStruct.unk20) { g_Status.equipHandCount[ITEM_LIFE_APPLE]--; g_unkGraphicsStruct.unk20 = 0xfff; self->step++; } break; case 4: s_TargetLocationX_calc = PLAYER.posX.i.hi; s_TargetLocationY_calc = PLAYER.posY.i.hi - 0x20; s_AngleToTarget = self->ext.faerie.randomMovementAngle; self->ext.faerie.randomMovementAngle += 0x10; self->ext.faerie.randomMovementAngle &= 0xFFF; s_DistToTargetLocation = self->ext.faerie.defaultDistToTargetLoc; s_TargetLocationX = s_TargetLocationX_calc + ((rcos(s_AngleToTarget / 2) * s_DistToTargetLocation) >> 0xC); s_TargetLocationY = s_TargetLocationY_calc - ((rsin(s_AngleToTarget) * (s_DistToTargetLocation / 2)) >> 0xC); s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 0x5: self->facingLeft = PLAYER.facingLeft; SetAnimationFrame(self, 0x13); if (s_ServantId == FAM_ACTIVE_YOUSEI) { g_api.PlaySfx(g_FaerieSfx.regeneration); } self->step++; break; case 0x6: if (self->pose == 0xA) { if (s_ServantId == FAM_ACTIVE_FAERIE) { g_api.PlaySfx(g_FaerieSfx.regeneration); } self->step++; } break; case 0x7: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { CreateEventEntity_Local(self, FAERIE_SUBENTITY_ITEM, 0); self->ext.faerie.frameCounter = 0; self->step++; } break; case 0x8: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { CreateEventEntity_Local(self, FAERIE_SUBENTITY_LIFE_APPLE, 0); self->ext.faerie.frameCounter = 0; self->step++; } break; case 0x9: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 90) { if (SearchForEntityInRange(1, 0x29)) { g_unkGraphicsStruct.D_800973FC = 0; } for (i = 8; i < 0x40; i++) { DestroyEntity(&g_Entities[i]); } g_Status.hp = g_Status.hpMax; g_Status.mp = g_Status.mpMax; self->ext.faerie.frameCounter = 0; self->step++; } break; case 0xA: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 90) { g_unkGraphicsStruct.unk20 = 0; self->step++; } break; case 0xB: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; case 0x5A: // Only get here when you are dead and have no life apple SetAnimationFrame(self, 0x20); g_api.PlaySfx(g_FaerieSfx.ohNo); self->step++; break; case 0x5B: break; } ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUseHammer(Entity* self) { const int paramOffset = 3; s32 rnd; s32 i; s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 0x18; switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 2: self->facingLeft = PLAYER.facingLeft; if (g_Status.equipHandCount[ITEM_HAMMER]) { SetAnimationFrame(self, 0x17); for (rnd = rand() % 0x100, i = 0; true; i++) { if (rnd <= g_SfxRandomizerHammerResist[i * 2]) { g_api.PlaySfx(g_SfxRandomizerHammerResist[i * 2 + 1]); break; } } self->step++; } else { SetAnimationFrame(self, 0x10); g_api.PlaySfx(g_FaerieSfx.noMedicine); self->ext.faerie.frameCounter = 0; self->step += 2; } break; case 3: if (self->pose == 5) { g_Status.equipHandCount[ITEM_HAMMER]--; g_api.CreateEntFactoryFromEntity( self, FACTORY(0x37, paramOffset), 0); CreateEventEntity_Local(self, FAERIE_SUBENTITY_ITEM, 1); g_api.PlaySfx(SFX_LEVER_METAL_BANG); g_api.func_80102CD8(4); self->ext.faerie.frameCounter = 0; self->step++; } break; case 4: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; } CheckForValidAbility(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUseUncurse(Entity* self) { const int paramOffset = 1; s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 0x18; switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 2: if (!g_Status.equipHandCount[ITEM_UNCURSE]) { SetAnimationFrame(self, 0x14); self->step = 5; break; } if (SearchForEntityInRange(1, 0x27)) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } SetAnimationFrame(self, 0x12); if (s_ServantId == FAM_ACTIVE_YOUSEI) { g_api.PlaySfx(g_FaerieSfx.healing); } self->step++; break; case 3: self->facingLeft = PLAYER.facingLeft ? 0 : 1; if (self->pose == 0xB) { if (s_ServantId == FAM_ACTIVE_FAERIE) { g_api.PlaySfx(g_FaerieSfx.healing); } g_Status.equipHandCount[ITEM_UNCURSE]--; g_api.CreateEntFactoryFromEntity( self, FACTORY(0x37, paramOffset), 0); CreateEventEntity_Local( self, FAERIE_SUBENTITY_ITEM, paramOffset + 3); self->ext.faerie.frameCounter = 0; self->step++; break; } break; case 4: case 6: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; case 5: self->facingLeft = PLAYER.facingLeft; if (self->pose == 0x20) { g_api.PlaySfx(g_FaerieSfx.noMedicine); self->ext.faerie.frameCounter = 0; self->step++; } break; } CheckForValidAbility(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUseAntivenom(Entity* self) { const int paramOffset = 0; s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 0x18; switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 2: if (!g_Status.equipHandCount[ITEM_ANTIVENOM]) { SetAnimationFrame(self, 0x14); self->step = 5; break; } if (SearchForEntityInRange(1, 0x27)) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } SetAnimationFrame(self, 0x12); if (s_ServantId == FAM_ACTIVE_YOUSEI) { g_api.PlaySfx(g_FaerieSfx.healing); } self->step++; break; case 3: self->facingLeft = PLAYER.facingLeft ? 0 : 1; if (self->pose == 0xB) { if (s_ServantId == FAM_ACTIVE_FAERIE) { g_api.PlaySfx(g_FaerieSfx.healing); } g_Status.equipHandCount[ITEM_ANTIVENOM]--; g_api.CreateEntFactoryFromEntity( self, FACTORY(0x37, paramOffset), 0); CreateEventEntity_Local( self, FAERIE_SUBENTITY_ITEM, paramOffset + 3); self->ext.faerie.frameCounter = 0; self->step++; break; } break; case 4: case 6: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; case 5: self->facingLeft = PLAYER.facingLeft; if (self->pose == 0x20) { g_api.PlaySfx(g_FaerieSfx.noMedicine); self->ext.faerie.frameCounter = 0; self->step++; } break; } CheckForValidAbility(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUseElementalResist(Entity* self) { s32 i; s32 rnd; s32 temp; s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 0x18; switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 2: self->facingLeft = PLAYER.facingLeft; if (!g_Status .equipHandCount[g_ResistItemsParamMap[self->params * 4 + 1]]) { SetAnimationFrame(self, 0x10); self->step = 5; break; } if (SearchForEntityInRange(1, 0x27)) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } SetAnimationFrame(self, 0x12); self->step++; break; case 3: if (PLAYER.facingLeft) temp = 0; else temp = 1; self->facingLeft = temp; if (self->pose == 0xB) { for (rnd = rand() % 0x100, i = 0; true; i++) { if (rnd <= g_SfxRandomizerHammerResist[i * 2]) { g_api.PlaySfx(g_SfxRandomizerHammerResist[i * 2 + 1]); break; } } g_Status .equipHandCount[g_ResistItemsParamMap[self->params * 4 + 1]]--; g_api.CreateEntFactoryFromEntity( self, FACTORY(0x37, g_ResistItemsParamMap[self->params * 4 + 2]), 0); CreateEventEntity_Local( self, FAERIE_SUBENTITY_ITEM, g_ResistItemsParamMap[self->params * 4 + 3]); self->ext.faerie.frameCounter = 0; self->step++; } break; case 4: case 6: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; case 5: self->facingLeft = PLAYER.facingLeft; if (self->pose == 0x20) { g_api.PlaySfx(g_FaerieSfx.noMedicine); self->ext.faerie.frameCounter = 0; self->step++; } break; } CheckForValidAbility(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantUsePotion(Entity* self) { s32 temp; s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 0x18; switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 5); self->velocityX = rcos(s_AllowedAngle) << 5; SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { self->step++; } break; case 2: if (!g_Status.equipHandCount[g_PotionItemsParamMap[self->params * 2]]) { if (self->params) { temp = 0; } else { temp = 1; } self->params = temp; if (!g_Status .equipHandCount[g_PotionItemsParamMap[self->params * 2]]) { SetAnimationFrame(self, 0x14); self->step = 5; break; } } if (SearchForEntityInRange(1, 0x27)) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } SetAnimationFrame(self, 0x12); self->step++; break; case 3: self->facingLeft = PLAYER.facingLeft ? 0 : 1; if (self->pose == 0xB) { g_api.PlaySfx(g_FaerieSfx.potion); g_Status.equipHandCount[g_PotionItemsParamMap[self->params * 2]]--; g_api.CreateEntFactoryFromEntity( self, FACTORY(0x37, g_PotionItemsParamMap[self->params * 2 + 1]), 0); CreateEventEntity_Local(self, FAERIE_SUBENTITY_ITEM, 2); self->ext.faerie.frameCounter = 0; self->step++; } break; case 4: case 6: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 60) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; case 5: self->facingLeft = PLAYER.facingLeft; if (self->pose == 0x20) { g_api.PlaySfx(g_FaerieSfx.noMedicine); self->ext.faerie.frameCounter = 0; self->step++; } break; } CheckForValidAbility(self); ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } void UpdateServantAdditionalInit(Entity* arg0) { s16 rnd; s32 i; g_api.GetServantStats(arg0, 0, 0, &s_FaerieStats); if (D_us_80179320) { arg0->zPriority = PLAYER.zPriority - 2; s_zPriority = arg0->zPriority; } s_TargetLocOffset_calc = -0x18; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX_calc = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY_calc = PLAYER.posY.i.hi - 0x20; s_AngleToTarget = arg0->ext.faerie.randomMovementAngle; arg0->ext.faerie.randomMovementAngle += 0x10; arg0->ext.faerie.randomMovementAngle &= 0xfff; s_DistToTargetLocation = arg0->ext.faerie.defaultDistToTargetLoc; s_TargetLocationX = s_TargetLocationX_calc + ((rcos(s_AngleToTarget / 2) * s_DistToTargetLocation) >> 0xC); s_TargetLocationY = s_TargetLocationY_calc - ((rsin(s_AngleToTarget) * (s_DistToTargetLocation / 2)) >> 0xC); s_AngleToTarget = CalculateAngleToEntity(arg0, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, arg0->ext.faerie.targetAngle, arg0->ext.faerie.maxAngle); arg0->ext.faerie.targetAngle = s_AllowedAngle; s_DistToTargetLocation = CalculateDistance(arg0, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 0x3C) { arg0->velocityY = -(rsin(s_AllowedAngle) << 3); arg0->velocityX = rcos(s_AllowedAngle) << 3; arg0->ext.faerie.maxAngle = 0x40; } else if (s_DistToTargetLocation < 0x64) { arg0->velocityY = -(rsin(s_AllowedAngle) << 4); arg0->velocityX = rcos(s_AllowedAngle) << 4; arg0->ext.faerie.maxAngle = 0x60; } else { arg0->velocityY = -(rsin(s_AllowedAngle) << 5); arg0->velocityX = rcos(s_AllowedAngle) << 5; arg0->ext.faerie.maxAngle = 0x80; } arg0->posX.val += arg0->velocityX; arg0->posY.val += arg0->velocityY; switch (arg0->step) { case 0: ExecuteAbilityInitialize(arg0); arg0->ext.faerie.timer = -1; break; case 1: SelectAnimationFrame(arg0); if (IsMovementAllowed(1) || CheckAllEntitiesValid() || s_RoomSpecialState == 1 || g_CutsceneHasControl || g_unkGraphicsStruct.D_800973FC) { SetAnimationFrame(arg0, 0xE); arg0->entityId = FAERIE_MODE_DEFAULT_UPDATE; arg0->step = 0; return; } s_DistToTargetLocation = CalculateDistance(arg0, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 0x20) { arg0->facingLeft = PLAYER.facingLeft; arg0->step++; } break; case 2: rnd = rand() % 0x100; if (s_FaerieStats.unk8 == 1) { for (i = 0; true; i++) { if (rnd <= (s32)g_FaerieIntroRandomizer[i * 2]) { arg0->ext.faerie.currentSfxEvent = (ServantSfxEventDesc*) g_FaerieIntroRandomizer[i * 2 + 1]; break; } } } else { for (i = 0; true; i++) { if (rnd <= (s32)g_SfxEventRandomizer[i * 2]) { arg0->ext.faerie.currentSfxEvent = (ServantSfxEventDesc*)g_SfxEventRandomizer[i * 2 + 1]; break; } } } arg0->ext.faerie.sfxEventFlag = ((s16*)arg0->ext.faerie.currentSfxEvent)[0]; g_PauseAllowed = false; arg0->step++; break; case 3: if (PLAYER.posX.i.hi >= arg0->posX.i.hi) { arg0->facingLeft = 1; } else { arg0->facingLeft = 0; } if (arg0->ext.faerie.sfxEventFlag < 0) { if (g_PlaySfxStep > 4) { SetAnimationFrame( arg0, arg0->ext.faerie.currentSfxEvent->animIndex); arg0->step++; } } else { if ((g_PlaySfxStep == 4) || (g_PlaySfxStep >= 0x63)) { arg0->ext.faerie.sfxEventFlag--; } if (arg0->ext.faerie.sfxEventFlag < 0) { SetAnimationFrame( arg0, arg0->ext.faerie.currentSfxEvent->animIndex); if (arg0->ext.faerie.currentSfxEvent->sfxId && (SearchForEntityInRange(0, FAERIE_EVENT_SFX_PASSTHROUGH) == NULL)) { CreateEventEntity_Local( arg0, FAERIE_EVENT_SFX_PASSTHROUGH, arg0->ext.faerie.currentSfxEvent->sfxId); } arg0->ext.faerie.currentSfxEvent++; arg0->ext.faerie.sfxEventFlag = arg0->ext.faerie.currentSfxEvent->flag; } } break; case 4: if (g_PlaySfxStep == 0x63) { arg0->step++; } break; case 5: SetAnimationFrame(arg0, 0xE); g_PauseAllowed = true; arg0->entityId = FAERIE_MODE_DEFAULT_UPDATE; arg0->step = 0; break; } ProcessEvent(arg0, false); CheckForValidAbility(arg0); ServantUpdateAnim(arg0, NULL, g_FaerieAnimationFrames); FntPrint("sts = %d\n", g_PlaySfxStep); } void UpdateSubEntityWings(Entity* self) { s32 animIndex; s32 wingsInBackZ; s32 i; #ifdef VERSION_PSP s32 temp_zPriority; #else s16 temp_zPriority; #endif if (!self->step) { ExecuteAbilityInitialize(self); self->ext.faerieWings.parent = &g_Entities[SERVANT_ENTITY_INDEX]; self->step += 1; } self->posX.val = self->ext.faerieWings.parent->posX.val; self->posY.val = self->ext.faerieWings.parent->posY.val; self->facingLeft = self->ext.faerieWings.parent->facingLeft; for (i = 6; i <= 0x2D; i++) { if (self->ext.faerieWings.parent->anim == g_FaerieAnimationFrames[i]) break; } animIndex = abs(g_WingAnimationParams[i - 6].animIndex); wingsInBackZ = g_WingAnimationParams[i - 6].wingsInBackZ; SetAnimationFrame(self, animIndex); if (wingsInBackZ) { temp_zPriority = s_zPriority - 1; } else { temp_zPriority = s_zPriority + 1; } self->zPriority = temp_zPriority; ServantUpdateAnim(self, 0, g_FaerieAnimationFrames); } void UpdateServantSitOnShoulder(Entity* self) { s32 rnd; s32 i; g_api.GetServantStats(self, 0, 0, &s_FaerieStats); if (D_us_80179320 != 0) { self->zPriority = PLAYER.zPriority - 2; s_zPriority = self->zPriority; } if (IsMovementAllowed(1)) { if (self->step < 2) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } if (self->step < 9) { self->step = 9; } } if (PLAYER.step_s == 0) { s_TargetLocOffset_calc = -6; if (PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 12; } else { s_TargetLocOffset_calc = 16; if (PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY = PLAYER.posY.i.hi - 8; } switch (self->step) { case 0: ExecuteAbilityInitialize(self); SetAnimationFrame(self, 0xE); break; case 1: s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, 0x180); self->ext.faerie.targetAngle = s_AllowedAngle; self->velocityY = -(rsin(s_AllowedAngle) << 3); self->velocityX = (rcos(s_AllowedAngle) << 3); SelectAnimationFrame(self); self->posX.val += self->velocityX; self->posY.val += self->velocityY; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 2) { if (PLAYER.step_s == 0) { self->facingLeft = PLAYER.facingLeft; } else { self->facingLeft = PLAYER.facingLeft ? 0 : 1; } SetAnimationFrame(self, 0x18); self->ext.faerie.frameCounter = 0; self->flags |= FLAG_POS_PLAYER_LOCKED; self->flags &= ~FLAG_POS_CAMERA_LOCKED; #ifdef VERSION_PSP if (D_8003C708.flags & LAYOUT_RECT_PARAMS_UNKNOWN_20 || D_8003C708.flags & LAYOUT_RECT_PARAMS_UNKNOWN_40 || (s_RoomSpecialState == 1) || s_FaerieStats.level < 5) { self->step = 5; } else if (s_ServantId != FAM_ACTIVE_YOUSEI || PLAYER.step_s != 4) { self->step = 5; } else if (s_FaerieStats.level > 9 || g_Timer & 1 || s_FaerieStats.level > 4 || (g_Timer & 7)) { self->step = 5; } else { self->ext.faerie.unkB4 = 0; if (s_FaerieStats.level < 16) { self->ext.faerie.frameCounter = 0x708; } else { self->ext.faerie.frameCounter = 0x7a8 - (s_FaerieStats.level << 0x4); } self->step++; } #else if ((*((FgLayer32*)&D_8003C708)).flags & (LAYOUT_RECT_PARAMS_UNKNOWN_20 | LAYOUT_RECT_PARAMS_UNKNOWN_40) || (s_RoomSpecialState == 1) || s_FaerieStats.level < 5) { self->step = 5; } else if (s_ServantId != FAM_ACTIVE_YOUSEI || s_FaerieStats.level < 0x32 || PLAYER.step_s != 4) { self->step = 5; } else if (s_FaerieStats.level < 0x5A && rand() % 8) { self->step = 5; } else { self->ext.faerie.unkB4 = 0; if (PLAYER.step_s == 4) { self->ext.faerie.frameCounter = g_FaerieFrameCount2; } else { self->ext.faerie.frameCounter = g_FaerieFrameCount1; } self->step++; } #endif } break; case 2: self->ext.faerie.frameCounter--; if (self->ext.faerie.frameCounter < 0) { self->ext.faerie.frameCounter = 0; if (g_api.func_800F27F4(0)) { SetAnimationFrame(self, 0x19); self->ext.faerie.unkB4 = 1; self->step++; } } break; case 3: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 0x420) { SetAnimationFrame(self, 0x1A); self->ext.faerie.frameCounter = 0; self->step++; } break; case 4: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 0x15E0) { SetAnimationFrame(self, 0x19); self->ext.faerie.frameCounter = 0; self->step++; } break; case 5: self->ext.faerie.frameCounter++; if (self->ext.faerie.frameCounter > 0x500) { SetAnimationFrame(self, 0x18); self->ext.faerie.frameCounter = 0; self->ext.faerie.unkB4 = 0; self->step++; } break; case 6: self->ext.faerie.frameCounter = (rand() % 0x800) + 0x400; self->step++; /* fallthrough */ case 7: self->ext.faerie.frameCounter--; if (self->ext.faerie.frameCounter < 0) { self->ext.faerie.frameCounter = (rand() % 0x80) + 0x80; SetAnimationFrame(self, 0x19); self->step++; } break; case 8: self->ext.faerie.frameCounter--; if (self->ext.faerie.frameCounter < 0) { SetAnimationFrame(self, 0x18); self->step = 6; } break; case 9: // Happens when the faerie falls off your shoulder if (self->ext.faerie.unkB4) { g_api.func_800F27F4(1); } self->flags &= ~FLAG_POS_PLAYER_LOCKED; self->flags |= FLAG_POS_CAMERA_LOCKED; SetAnimationFrame(self, 0x1B); self->velocityX = self->facingLeft ? FIX(-0.25) : FIX(0.25); self->velocityY = FIX(1); for (rnd = rand() % 0x100, i = 0; true; i++) { if (rnd <= g_SfxRandomizerGrunt[i * 2]) { g_api.PlaySfx(g_SfxRandomizerGrunt[i * 2 + 1]); break; } } self->step++; break; case 10: // performs the fall animation self->posX.val += self->velocityX; self->posY.val += self->velocityY; self->velocityY -= FIX(0.03125); // fall animation is finished if (s_AnimationStatus == -1) { self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; return; } break; } ProcessEvent(self, false); CheckForValidAbility(self); #ifdef VERSION_PSP if ((self->step == 3 || self->step == 4) && *((s32*)0x9234CB8) < 0x200) { *((s32*)0x9234CB8) = 0x200; } #endif unused_39C8(self); s_AnimationStatus = ServantUpdateAnim(self, NULL, g_FaerieAnimationFrames); } // self->param is index for g_FaerieHints for the type of hint void UpdateServantOfferHint(Entity* self) { char pad[2]; self->ext.faerie.tileMapX = (g_Tilemap.left << 8) + g_Tilemap.scrollX.i.hi; self->ext.faerie.tileMapY = (g_Tilemap.top << 8) + g_Tilemap.scrollY.i.hi; if (D_us_80179320) { self->zPriority = PLAYER.zPriority - 2; s_zPriority = self->zPriority; } if ((g_FaerieHints[self->params].left == -1) || (self->step == 0)) { s_TargetLocOffset_calc = -24; if (!PLAYER.facingLeft) { s_TargetLocOffset_calc = -s_TargetLocOffset_calc; } s_TargetLocationX_calc = PLAYER.posX.i.hi + s_TargetLocOffset_calc; s_TargetLocationY_calc = PLAYER.posY.i.hi - 32; } else { s_TargetLocationX_calc = s_HintTargetX - self->ext.faerie.tileMapX; s_TargetLocationY_calc = s_HintTargetY - self->ext.faerie.tileMapY; } s_AngleToTarget = self->ext.faerie.randomMovementAngle; self->ext.faerie.randomMovementAngle = (self->ext.faerie.randomMovementAngle + 0x10) & 0xFFF; s_DistToTargetLocation = self->ext.faerie.defaultDistToTargetLoc; s_TargetLocationX = ((rcos(s_AngleToTarget / 2) * s_DistToTargetLocation) >> 12) + s_TargetLocationX_calc; s_TargetLocationY = s_TargetLocationY_calc - ((rsin(s_AngleToTarget) * (s_DistToTargetLocation / 2)) >> 12); s_AngleToTarget = CalculateAngleToEntity(self, s_TargetLocationX, s_TargetLocationY); s_AllowedAngle = GetTargetPositionWithDistanceBuffer( s_AngleToTarget, self->ext.faerie.targetAngle, self->ext.faerie.maxAngle); self->ext.faerie.targetAngle = s_AllowedAngle; s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 60) { self->velocityY = -(rsin(s_AllowedAngle) * 8); self->velocityX = rcos(s_AllowedAngle) * 8; self->ext.faerie.maxAngle = 64; } else if (s_DistToTargetLocation < 100) { self->velocityY = -(rsin(s_AllowedAngle) * 16); self->velocityX = rcos(s_AllowedAngle) * 16; self->ext.faerie.maxAngle = 96; } else { self->velocityY = -(rsin(s_AllowedAngle) * 32); self->velocityX = rcos(s_AllowedAngle) * 32; self->ext.faerie.maxAngle = 128; } self->posX.val += self->velocityX; self->posY.val += self->velocityY; switch (self->step) { case 0: ExecuteAbilityInitialize(self); s_HintTargetX = g_FaerieHints[self->params].left + self->ext.faerie.tileMapX; s_HintTargetY = g_FaerieHints[self->params].top + self->ext.faerie.tileMapY; self->ext.faerie.timer = -1; break; case 1: SelectAnimationFrame(self); s_DistToTargetLocation = CalculateDistance(self, s_TargetLocationX, s_TargetLocationY); if (s_DistToTargetLocation < 32) { self->facingLeft = PLAYER.facingLeft; self->step++; } break; case 2: self->ext.faerie.currentSfxEvent = g_FaerieHints[self->params].hint; // This is self->ext.faerie.currentSfxEvent->flag, but the weird cast is // needed for match self->ext.faerie.sfxEventFlag = *((s16*)self->ext.faerie.currentSfxEvent); g_PauseAllowed = 0; self->step++; break; case 3: if (PLAYER.posX.i.hi >= self->posX.i.hi) { self->facingLeft = true; } else { self->facingLeft = false; } if (self->ext.faerie.sfxEventFlag < 0) { if (g_PlaySfxStep > 4) { SetAnimationFrame( self, self->ext.faerie.currentSfxEvent->animIndex); self->step++; } } else { if ((g_PlaySfxStep == 4) || (g_PlaySfxStep >= 99)) { self->ext.faerie.sfxEventFlag--; } if (self->ext.faerie.sfxEventFlag < 0) { SetAnimationFrame( self, self->ext.faerie.currentSfxEvent->animIndex); if ((self->ext.faerie.currentSfxEvent->sfxId != 0) && (SearchForEntityInRange(0, FAERIE_EVENT_SFX_PASSTHROUGH) == NULL)) { CreateEventEntity_Local( self, FAERIE_EVENT_SFX_PASSTHROUGH, self->ext.faerie.currentSfxEvent->sfxId); } self->ext.faerie.currentSfxEvent++; self->ext.faerie.sfxEventFlag = self->ext.faerie.currentSfxEvent->flag; } } break; case 4: SetAnimationFrame(self, 14); g_PauseAllowed = 1; self->entityId = FAERIE_MODE_DEFAULT_UPDATE; self->step = 0; break; } unused_39C8(self); ServantUpdateAnim(self, NULL, &g_FaerieAnimationFrames); } // Unsure where this code is exectued from, but it would be where // an entity is created with Entity ID DC // It has to be from the engine somewhere as they are triggered // from room states (for the most part) void UpdateEntitySetRoomSpecialState(Entity* self) { Entity* entity; switch (self->params) { case 0: s_RoomSpecialState = ROOM_SPECIAL_STATE_UNK1; entity = SearchForEntityInRange(0, 222); if (entity && entity->step < 5) { entity->step = 8; } break; case 1: s_RoomSpecialState = ROOM_SPECIAL_STATE_DARKNESS; break; case 2: s_RoomSpecialState = ROOM_SPECIAL_STATE_MIST; break; case 3: s_RoomSpecialState = ROOM_SPECIAL_STATE_WALL_HINT1; break; case 4: s_RoomSpecialState = ROOM_SPECIAL_STATE_SUS_HINT1; break; case 5: s_RoomSpecialState = ROOM_SPECIAL_STATE_WALL_HINT2; break; case 6: s_RoomSpecialState = ROOM_SPECIAL_STATE_WALL_HINT3; break; case 7: s_RoomSpecialState = ROOM_SPECIAL_STATE_WALL_HINT4; break; case 8: s_RoomSpecialState = ROOM_SPECIAL_STATE_SUS_HINT2; break; case 9: s_RoomSpecialState = ROOM_SPECIAL_STATE_WALL_HINT5; break; case 10: s_RoomSpecialState = ROOM_SPECIAL_STATE_SUS_HINT3; break; case 15: D_us_80179320 = 1; break; } DestroyEntity(self); } void UpdateSubEntityUseLifeApple(Entity* arg0) { Primitive* currentPrim; s32 i; s32 temp_x; switch (arg0->step) { case 0: arg0->primIndex = g_api.AllocPrimitives(PRIM_G4, 10); if (arg0->primIndex == -1) { DestroyEntity(arg0); return; } arg0->flags = FLAG_POS_CAMERA_LOCKED | FLAG_KEEP_ALIVE_OFFCAMERA | FLAG_HAS_PRIMS; arg0->posX.i.hi += arg0->facingLeft ? -4 : 4; currentPrim = &g_PrimBuf[arg0->primIndex]; currentPrim->r1 = currentPrim->r3 = currentPrim->g1 = currentPrim->g3 = currentPrim->b1 = currentPrim->b3 = 0xFF; currentPrim->priority = 0x1C0; currentPrim->drawMode = FLAG_DRAW_UNK400 | FLAG_DRAW_UNK20 | FLAG_DRAW_UNK10 | FLAG_DRAW_ROTATE | FLAG_DRAW_SCALEX; currentPrim = currentPrim->next; currentPrim->r1 = currentPrim->r3 = currentPrim->g1 = currentPrim->g3 = currentPrim->b1 = currentPrim->b3 = 0xFF; currentPrim->priority = 0x1C0; currentPrim->drawMode = FLAG_DRAW_UNK400 | FLAG_DRAW_UNK20 | FLAG_DRAW_UNK10 | FLAG_DRAW_ROTATE | FLAG_DRAW_SCALEX; for (i = 0; i < 8; i++) { currentPrim = currentPrim->next; currentPrim->x0 = currentPrim->x1 = arg0->posX.i.hi; currentPrim->y0 = currentPrim->y1 = 0; currentPrim->x2 = arg0->posX.i.hi + ((rcos(i << 8) * 0x60) >> 0xC); currentPrim->x3 = arg0->posX.i.hi + ((rcos((i + 1) << 8) * 0x60) >> 0xC); currentPrim->y2 = (rsin(i << 8) * 3) << 5 >> 0xC; currentPrim->y3 = (rsin((i + 1) << 8) * 3) << 5 >> 0xC; currentPrim->priority = 0x1C0; currentPrim->drawMode = FLAG_DRAW_UNK400 | FLAG_DRAW_UNK20 | FLAG_DRAW_UNK10 | FLAG_DRAW_ROTATE | FLAG_DRAW_SCALEX; } arg0->ext.faerieLifeApple.primX = 0x10; arg0->ext.faerieLifeApple.primY = 0; arg0->ext.faerieLifeApple.opacity = 0x40; arg0->ext.faerieLifeApple.effectOpacity = 0; arg0->step++; break; case 1: arg0->ext.faerieLifeApple.effectOpacity += 4; arg0->ext.faerieLifeApple.primY += 0x10; if (arg0->ext.faerieLifeApple.primY >= 0x100) { arg0->step++; } break; case 2: arg0->ext.faerieLifeApple.lifeAppleTimer++; if (arg0->ext.faerieLifeApple.lifeAppleTimer > 0xF) { arg0->step++; } break; case 3: arg0->ext.faerieLifeApple.opacity += 4; if (arg0->ext.faerieLifeApple.opacity >= 0x100) { arg0->ext.faerieLifeApple.opacity = 0xFF; } arg0->ext.faerieLifeApple.primX += 4; if (arg0->ext.faerieLifeApple.primX >= 0x100) { arg0->ext.faerieLifeApple.lifeAppleTimer = 0; arg0->step++; } break; case 4: arg0->ext.faerieLifeApple.lifeAppleTimer++; if (arg0->ext.faerieLifeApple.lifeAppleTimer > 60) { arg0->step++; } break; case 5: arg0->ext.faerieLifeApple.effectOpacity--; if (arg0->ext.faerieLifeApple.effectOpacity < 0) { arg0->ext.faerieLifeApple.effectOpacity = 0; } arg0->ext.faerieLifeApple.opacity -= 4; if (arg0->ext.faerieLifeApple.opacity <= 0x40) { arg0->ext.faerieLifeApple.opacity = 0x40; } arg0->ext.faerieLifeApple.primX -= 8; if (arg0->ext.faerieLifeApple.primX <= 0) { DestroyEntity(arg0); return; } break; } currentPrim = &g_PrimBuf[arg0->primIndex]; temp_x = arg0->posX.i.hi - arg0->ext.faerieLifeApple.primX; if (temp_x < 0) { temp_x = 0; } currentPrim->x0 = currentPrim->x2 = temp_x; currentPrim->x1 = currentPrim->x3 = arg0->posX.i.hi; currentPrim->y0 = currentPrim->y1 = 0; currentPrim->y2 = currentPrim->y3 = arg0->ext.faerieLifeApple.primY; currentPrim->r0 = currentPrim->r2 = currentPrim->g0 = currentPrim->g2 = currentPrim->b0 = currentPrim->b2 = arg0->ext.faerieLifeApple.opacity; currentPrim = currentPrim->next; temp_x = arg0->posX.i.hi + arg0->ext.faerieLifeApple.primX; if (temp_x > 0x100) { temp_x = 0x100; } currentPrim->x0 = currentPrim->x2 = temp_x; currentPrim->x1 = currentPrim->x3 = arg0->posX.i.hi; currentPrim->y0 = currentPrim->y1 = 0; currentPrim->y2 = currentPrim->y3 = arg0->ext.faerieLifeApple.primY; currentPrim->r0 = currentPrim->r2 = currentPrim->g0 = currentPrim->g2 = currentPrim->b0 = currentPrim->b2 = arg0->ext.faerieLifeApple.opacity; for (i = 0; i < 8; i++) { currentPrim = currentPrim->next; currentPrim->r0 = currentPrim->r1 = currentPrim->g0 = currentPrim->g1 = currentPrim->b0 = currentPrim->b1 = arg0->ext.faerieLifeApple.effectOpacity; currentPrim->r2 = currentPrim->r3 = currentPrim->g2 = currentPrim->g3 = currentPrim->b2 = currentPrim->b3 = 0; } } void UpdateServantSfxPassthrough(Entity* self) { ProcessSfxState(self); } // self->params is the item being used void UpdateSubEntityUseItem(Entity* self) { FakePrim* fakePrim; s32 i; u16 posY2; s16 posX3; s32 posX; s16 posY; s16 posX2; u16 posX4; ItemPrimitiveParams* primitiveParams; posX2 = self->posX.i.hi; posY = self->posY.i.hi; primitiveParams = &g_ItemPrimitiveParams[(s16)self->params]; switch (self->step) { case 0: self->primIndex = g_api.func_800EDB58(PRIM_TILE_ALT, primitiveParams->count + 1); if (self->primIndex == -1) { DestroyEntity(self); return; } posX = posX2; self->flags = primitiveParams->flags; fakePrim = (FakePrim*)&g_PrimBuf[self->primIndex]; while (true) { fakePrim->drawMode = primitiveParams->drawMode + DRAW_HIDE; fakePrim->priority = primitiveParams->priority + PLAYER.zPriority; if (fakePrim->next == NULL) { fakePrim->w = 0; fakePrim->y0 = fakePrim->x0 = 0; fakePrim->drawMode &= ~DRAW_HIDE; break; } fakePrim->posX.i.hi = posX2; fakePrim->posY.i.hi = posY; fakePrim->posY.i.lo = 0; fakePrim->posX.i.lo = 0; switch (primitiveParams->unk6) { case 0: if (!self->facingLeft) { fakePrim->posX.i.hi = posX + 4; } else { fakePrim->posX.i.hi = posX - 4; } fakePrim->posY.i.hi = posY - 0x1A; fakePrim->velocityX.val = ((rand() % 0x2000) - 0x1000) << 4; fakePrim->velocityY.val = 0; break; case 1: if (!self->facingLeft) { posX3 = posX - 0x18; } else { posX3 = posX + 0x18; } posY2 = posY + 0x10; fakePrim->posX.i.hi = (u16)(posX3 - 8 + (rand() % 16)); fakePrim->posY.i.hi = posY2; fakePrim->velocityX.val = ((rand() % 0x2000) - 0x1000) << 4; fakePrim->velocityY.val = -((rand() % 0x1000) + 0x1800) << 4; fakePrim->delay = 0x2D; break; case 2: if (!self->facingLeft) { posX4 = posX + 0xE; } else { posX4 = posX - 0xE; } posY2 = posY - 8; fakePrim->posX.i.hi = posX4; fakePrim->posY.i.hi = posY2; fakePrim->velocityX.val = (rand() % 0x800) << 4; if (self->facingLeft) { fakePrim->velocityX.val = -fakePrim->velocityX.val; } fakePrim->velocityY.val = -((rand() % 0x1000) + 0x800) << 4; fakePrim->delay = 0x28; break; } fakePrim->x0 = fakePrim->posX.i.hi; fakePrim->y0 = fakePrim->posY.i.hi; fakePrim->r0 = primitiveParams->r; fakePrim->g0 = primitiveParams->g; fakePrim->b0 = primitiveParams->b; fakePrim->w = primitiveParams->w; fakePrim->h = primitiveParams->h; fakePrim = fakePrim->next; } self->step++; // fallthrough case 1: // The hammer runs this code more than once, the other items only // once if (--self->ext.faerieItem.unkFlag <= 0) { fakePrim = (FakePrim*)&g_PrimBuf[self->primIndex]; for (i = 0; i < self->ext.faerieItem.unkAccumulator; i++) { fakePrim = fakePrim->next; } for (i = 0; i < primitiveParams->unk2; i++) { fakePrim->drawMode &= ~DRAW_HIDE; fakePrim = fakePrim->next; } self->ext.faerieItem.unkAccumulator += primitiveParams->unk2; if (self->ext.faerieItem.unkAccumulator >= primitiveParams->count) { self->step++; } self->ext.faerieItem.unkFlag = primitiveParams->unk4; } // fallthrough case 2: self->ext.faerieItem.drawMode = DRAW_DEFAULT; fakePrim = (FakePrim*)&g_PrimBuf[self->primIndex]; while (true) { if (fakePrim->next == NULL) { fakePrim->w = 0; fakePrim->y0 = fakePrim->x0 = 0; fakePrim->drawMode &= ~DRAW_HIDE; break; } fakePrim->posX.i.hi = fakePrim->x0; fakePrim->posY.i.hi = fakePrim->y0; switch (primitiveParams->unk6) { case 0: if (!(fakePrim->drawMode & DRAW_HIDE)) { fakePrim->posX.val += fakePrim->velocityX.val; fakePrim->posY.val += fakePrim->velocityY.val; fakePrim->velocityX.val = AccumulateTowardZero(fakePrim->velocityX.val, 0x1000); fakePrim->velocityY.val -= FIX(2.0 / 16); if (fakePrim->posY.i.hi < 0) { fakePrim->drawMode |= DRAW_HIDE; } } break; case 1: if (!(fakePrim->drawMode & DRAW_HIDE)) { fakePrim->posX.val += fakePrim->velocityX.val; fakePrim->posY.val += fakePrim->velocityY.val; fakePrim->velocityY.val += FIX(2.0 / 16); if (--fakePrim->delay < 0) { fakePrim->drawMode |= DRAW_HIDE; } } break; case 2: if (!(fakePrim->drawMode & DRAW_HIDE)) { fakePrim->posX.val += fakePrim->velocityX.val; fakePrim->posY.val += fakePrim->velocityY.val; if (fakePrim->r0 != 0) { fakePrim->r0--; } if (fakePrim->g0 != 0) { fakePrim->g0--; } if (fakePrim->b0 != 0) { fakePrim->b0--; } fakePrim->velocityY.val += FIX(1.5 / 16); if (--fakePrim->delay < 0) { fakePrim->drawMode |= DRAW_HIDE; } } break; } fakePrim->x0 = fakePrim->posX.i.hi; fakePrim->y0 = fakePrim->posY.i.hi; self->ext.faerieItem.drawMode |= !(fakePrim->drawMode & DRAW_HIDE); fakePrim = fakePrim->next; } if (self->ext.faerieItem.drawMode == DRAW_DEFAULT) { DestroyEntity(self); } } } #ifndef VERSION_PSP #include "../servant_update_anim.h" #endif #include "../../destroy_entity.h" #ifndef VERSION_PSP #include "../accumulate_toward_zero.h" #include "../search_for_entity_in_range.h" #endif #include "../calculate_angle_to_entity.h" #include "../get_target_position_with_distance_buffer.h" #ifndef VERSION_PSP #include "../calculate_distance.h" #include "../play_sfx.h" #endif #include "../process_event.h" #include "../create_event_entity.h" #include "../is_movement_allowed.h" #ifndef VERSION_PSP #include "../check_all_entities_valid.h" #endif #include "../servant_unk0.h"
0
0.908147
1
0.908147
game-dev
MEDIA
0.933759
game-dev
0.831335
1
0.831335
Oluwatosin-Ogunyebi/OpenAIConnector-Spectacles
6,131
Assets/SpectaclesInteractionKit/Utils/SeededRandomNumberGenerator.ts
const TAG = "SeededRandomNumberGenerator" /** * Optimal constant, per: * Steele, GL, Vigna, S. Computationally easy, spectrally good multipliers for congruential pseudorandom number generators. Softw Pract Exper. 2022; 52( 2): 443– 458. doi:10.1002/spe.3030 * https://onlinelibrary.wiley.com/doi/10.1002/spe.3030 */ const a = 0x915f77f5 // The c constant has no effect on the potency of the generator, and can be set to anything const c = 12345 // Choosing a low modulus keeps javascript from losing precision const m = Math.pow(2, 32) /** * This is a random number generator that allows you to set the seed used, for generating * consistent random values between runs. * It is implemented as a linear congruential generator, which is fast but not very random. * * NOTE: The seed you pass needs to be an Integer * * See: https://en.wikipedia.org/wiki/Linear_congruential_generator */ export class SeededRandomNumberGenerator { // The current seed used by the random number generator for the next call seed: number constructor(seed?: number) { this.seed = seed ?? 0 if (!Number.isInteger(this.seed)) { throw new Error( `Illegal value: Non-Integer seed passed to SeededRandomNumberGenerator: ${this.seed}` ) } } /** * Returns a random integer between 0 and 2^32 * @returns A random integer between 0 and 2^32 */ public randomInteger(): number { const x = (a * this.seed + c) % m this.seed = x return x } /** * Generate a floating-point number in the given range * @param {number} start The lowest value in the range. * @param {number} end The highest value in the range. * @returns A function that, when called, returns a number within the given range. */ public randomRange(start: number, end: number): () => number { const range = end - start return () => { const x = this.randomInteger() return (x / m) * range + start } } /** * Generate an integer in the given range. * @param {number} start The lowest value in the range. If this is a decimal, the start of the range will be the floor of the value. * @param {number} end The highest value in the range. If this is a decimal, the end of the range will be the floor of the value. * @returns A function that, when called, returns an integer within the given range. */ public randomIntegerRange(start: number, end: number): () => number { const startFloor = Math.floor(start) const endFloor = Math.floor(end) const range = endFloor - startFloor + 1 return () => { const x = this.randomInteger() return (x % range) + startFloor } } /** * Returns an Array of random numbers within a specified range (no duplicates). * @param rangeMin - The minimum value of the range (inclusive). * @param rangeMax - The maximum value of the range (exclusive). * @param numRandomNumbers - The number of random numbers to generate. * @returns An Array of random numbers within the specified range. * @throws Will throw an error if rangeMin >= rangeMax. * @throws Will throw an error if numRandomNumbers > rangeMax - rangeMin. */ public getRandomNumberArrayInRangeNoDuplicates( rangeMin: number, rangeMax: number, numRandomNumbers: number ): number[] { if (rangeMin >= rangeMax) { throw new Error( `Illegal arguments, rangeMin (${rangeMin}) cannot be >= rangeMax (${rangeMax})` ) } if (numRandomNumbers > rangeMax - rangeMin) { throw new Error( `Illegal arguments, numRandomNumbers (${numRandomNumbers}) cannot be > rangeMax - rangeMin (${ rangeMax - rangeMin })` ) } // To avoid choosing duplicate indexes, populate a list with all possible numbers so we can remove them as they are chosen const possibleNumbers: number[] = [] for (let i = rangeMin; i < rangeMax; i++) { possibleNumbers.push(i) } const chosenNumbers: number[] = [] for (let i = 0; i < numRandomNumbers; i++) { const index = this.randomIntegerRange(0, possibleNumbers.length - 1)() chosenNumbers.push(possibleNumbers[index]) possibleNumbers.splice(index, 1) } return chosenNumbers } /** * Generates a random quaternion. * The resulting quaternion is of unit length and its components range between -1 and 1. * * @returns A randomly generated quaternion of unit length. */ randomQuaternion(): quat { const w = MathUtils.remap(this.randomRange(0, 1)(), 1, 0, 1, -1) const x = MathUtils.remap(this.randomRange(0, 1)(), 1, 0, 1, -1) const y = MathUtils.remap(this.randomRange(0, 1)(), 1, 0, 1, -1) const z = MathUtils.remap(this.randomRange(0, 1)(), 1, 0, 1, -1) const returnQuat = new quat(w, x, y, z) returnQuat.normalize() return returnQuat } /** * Generates a random point within an Axis-Aligned Bounding Box (AABB). An AABB is a rectangular box * specified by providing the minimum and maximum x, y, and z coordinates. * * @param {vec3} minPoint - The minimum point of the AABB. * @param {vec3} maxPoint - The maximum point of the AABB. * @throws Will throw an error if any component of minPoint is greater than the corresponding component of maxPoint. * @returns A randomly generated point within the specified AABB, where minPoint.x <= x <= maxPont.x etc. */ randomPointInAABB(minPoint: vec3, maxPoint: vec3): vec3 { if ( minPoint.x > maxPoint.x || minPoint.y > maxPoint.y || minPoint.z > maxPoint.z ) { throw new Error( "Illegal arguments, each component of minPoint cannot be greater than the corresponding component of maxPoint" ) } const x = MathUtils.remap( this.randomRange(0, 1)(), 1, 0, maxPoint.x, minPoint.x ) const y = MathUtils.remap( this.randomRange(0, 1)(), 1, 0, maxPoint.y, minPoint.y ) const z = MathUtils.remap( this.randomRange(0, 1)(), 1, 0, maxPoint.z, minPoint.z ) return new vec3(x, y, z) } }
0
0.806928
1
0.806928
game-dev
MEDIA
0.501792
game-dev
0.875572
1
0.875572
hojat72elect/libgdx_games
1,279
Beat_The_High_Score/core/src/com/github/dwursteisen/beat/intro/TextRenderSystem.kt
package com.github.dwursteisen.beat.intro import com.badlogic.ashley.core.ComponentMapper import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.github.dwursteisen.beat.game.Position import com.github.dwursteisen.beat.game.Size import com.github.dwursteisen.libgdx.ashley.get class TextRenderSystem(private val batch: SpriteBatch, private val font: BitmapFont) : IteratingSystem(Family.all(TextRender::class.java).get()) { private val text: ComponentMapper<TextRender> = get() private val position: ComponentMapper<Position> = get() private val size: ComponentMapper<Size> = get() override fun processEntity(entity: Entity, deltaTime: Float) { val text = entity[text] val position = entity[position] val size = entity[size] font.data.setScale(text.scale) font.color = text.color font.draw(batch, text.text, position.position.x, position.position.y + size.size.y, size.size.x, text.halign, true) } override fun update(deltaTime: Float) { batch.begin() super.update(deltaTime) batch.end() } }
0
0.792497
1
0.792497
game-dev
MEDIA
0.721147
game-dev
0.971763
1
0.971763
mega12345mega/NBT-Editor
2,762
src/main/java/com/luneruniverse/minecraft/mod/nbteditor/commands/get/GetBlockCommand.java
package com.luneruniverse.minecraft.mod.nbteditor.commands.get; import static com.luneruniverse.minecraft.mod.nbteditor.multiversion.commands.ClientCommandManager.argument; import com.luneruniverse.minecraft.mod.nbteditor.NBTEditorClient; import com.luneruniverse.minecraft.mod.nbteditor.commands.ClientCommand; import com.luneruniverse.minecraft.mod.nbteditor.localnbt.LocalBlock; import com.luneruniverse.minecraft.mod.nbteditor.multiversion.MVMisc; import com.luneruniverse.minecraft.mod.nbteditor.multiversion.TextInst; import com.luneruniverse.minecraft.mod.nbteditor.multiversion.commands.FabricClientCommandSource; import com.luneruniverse.minecraft.mod.nbteditor.util.BlockStateProperties; import com.luneruniverse.minecraft.mod.nbteditor.util.MainUtil; import com.mojang.brigadier.Command; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.minecraft.command.argument.BlockPosArgumentType; import net.minecraft.command.argument.BlockStateArgument; import net.minecraft.command.argument.PosArgument; import net.minecraft.nbt.NbtCompound; import net.minecraft.util.math.BlockPos; public class GetBlockCommand extends ClientCommand { @Override public String getName() { return "block"; } @Override public String getExtremeAlias() { return "b"; } @Override public void register(LiteralArgumentBuilder<FabricClientCommandSource> builder, String path) { Command<FabricClientCommandSource> getBlock = context -> { PosArgument posArg = getDefaultArg(context, "pos", null, PosArgument.class); BlockPos pos = (posArg == null ? null : posArg.toAbsoluteBlockPos(MVMisc.getCommandSource(context.getSource().getPlayer()))); if (pos != null && !MainUtil.client.world.isInBuildLimit(pos)) throw BlockPosArgumentType.OUT_OF_WORLD_EXCEPTION.create(); BlockStateArgument blockArg = context.getArgument("block", BlockStateArgument.class); NbtCompound nbt = blockArg.data; if (nbt == null) nbt = new NbtCompound(); LocalBlock block = new LocalBlock(blockArg.getBlockState().getBlock(), new BlockStateProperties(blockArg.getBlockState()), nbt); if (pos == null) { block.toItem().ifPresentOrElse(MainUtil::getWithMessage, () -> MainUtil.client.player.sendMessage(TextInst.translatable("nbteditor.nbt.export.item.error"), false)); } else if (NBTEditorClient.SERVER_CONN.isEditingExpanded()) block.place(pos); else MainUtil.client.player.sendMessage(TextInst.translatable("nbteditor.requires_server"), false); return Command.SINGLE_SUCCESS; }; builder.then(argument("block", MVMisc.getBlockStateArg()).executes(getBlock)) .then(argument("pos", BlockPosArgumentType.blockPos()).then(argument("block", MVMisc.getBlockStateArg()).executes(getBlock))); } }
0
0.737769
1
0.737769
game-dev
MEDIA
0.986863
game-dev
0.863905
1
0.863905
dilmerv/VRDraw
14,196
Assets/Oculus/VR/Scripts/Util/OVRDebugInfo.cs
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use the Utilities SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/utilities-1.31 Unless required by applicable law or agreed to in writing, the Utilities SDK 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. ************************************************************************************/ using UnityEngine; using System.Collections; using UnityEngine.UI; //------------------------------------------------------------------------------------- /// <summary> /// Shows debug information on a heads-up display. /// </summary> public class OVRDebugInfo : MonoBehaviour { #region GameObjects for Debug Information UIs GameObject debugUIManager; GameObject debugUIObject; GameObject riftPresent; GameObject fps; GameObject ipd; GameObject fov; GameObject height; GameObject depth; GameObject resolutionEyeTexture; GameObject latencies; GameObject texts; #endregion #region Debug strings string strRiftPresent = null; // "VR DISABLED" string strFPS = null; // "FPS: 0"; string strIPD = null; // "IPD: 0.000"; string strFOV = null; // "FOV: 0.0f"; string strHeight = null; // "Height: 0.0f"; string strDepth = null; // "Depth: 0.0f"; string strResolutionEyeTexture = null; // "Resolution : {0} x {1}" string strLatencies = null; // "R: {0:F3} TW: {1:F3} PP: {2:F3} RE: {3:F3} TWE: {4:F3}" #endregion /// <summary> /// Variables for FPS /// </summary> float updateInterval = 0.5f; float accum = 0.0f; int frames = 0; float timeLeft = 0.0f; /// <summary> /// Managing for UI initialization /// </summary> bool initUIComponent = false; bool isInited = false; /// <summary> /// UIs Y offset /// </summary> float offsetY = 55.0f; /// <summary> /// Managing for rift detection UI /// </summary> float riftPresentTimeout = 0.0f; /// <summary> /// Turn on / off VR variables /// </summary> bool showVRVars = false; #region MonoBehaviour handler /// <summary> /// Initialization /// </summary> void Awake() { // Create canvas for using new GUI debugUIManager = new GameObject(); debugUIManager.name = "DebugUIManager"; debugUIManager.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform rectTransform = debugUIManager.AddComponent<RectTransform>(); rectTransform.sizeDelta = new Vector2(100f, 100f); rectTransform.localScale = new Vector3(0.001f, 0.001f, 0.001f); rectTransform.localPosition = new Vector3(0.01f, 0.17f, 0.53f); rectTransform.localEulerAngles = Vector3.zero; Canvas canvas = debugUIManager.AddComponent<Canvas>(); canvas.renderMode = RenderMode.WorldSpace; canvas.pixelPerfect = false; } /// <summary> /// Updating VR variables and managing UI present /// </summary> void Update() { if (initUIComponent && !isInited) { InitUIComponents(); } if (Input.GetKeyDown(KeyCode.Space) && riftPresentTimeout < 0.0f) { initUIComponent = true; showVRVars ^= true; } UpdateDeviceDetection(); // Presenting VR variables if (showVRVars) { debugUIManager.SetActive(true); UpdateVariable(); UpdateStrings(); } else { debugUIManager.SetActive(false); } } /// <summary> /// Initialize isInited value on OnDestroy /// </summary> void OnDestroy() { isInited = false; } #endregion #region Private Functions /// <summary> /// Initialize UI GameObjects /// </summary> void InitUIComponents() { float posY = 0.0f; int fontSize = 20; debugUIObject = new GameObject(); debugUIObject.name = "DebugInfo"; debugUIObject.transform.parent = GameObject.Find("DebugUIManager").transform; debugUIObject.transform.localPosition = new Vector3(0.0f, 100.0f, 0.0f); debugUIObject.transform.localEulerAngles = Vector3.zero; debugUIObject.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); // Print out for FPS if (!string.IsNullOrEmpty(strFPS)) { fps = VariableObjectManager(fps, "FPS", posY -= offsetY, strFPS, fontSize); } // Print out for IPD if (!string.IsNullOrEmpty(strIPD)) { ipd = VariableObjectManager(ipd, "IPD", posY -= offsetY, strIPD, fontSize); } // Print out for FOV if (!string.IsNullOrEmpty(strFOV)) { fov = VariableObjectManager(fov, "FOV", posY -= offsetY, strFOV, fontSize); } // Print out for Height if (!string.IsNullOrEmpty(strHeight)) { height = VariableObjectManager(height, "Height", posY -= offsetY, strHeight, fontSize); } // Print out for Depth if (!string.IsNullOrEmpty(strDepth)) { depth = VariableObjectManager(depth, "Depth", posY -= offsetY, strDepth, fontSize); } // Print out for Resoulution of Eye Texture if (!string.IsNullOrEmpty(strResolutionEyeTexture)) { resolutionEyeTexture = VariableObjectManager(resolutionEyeTexture, "Resolution", posY -= offsetY, strResolutionEyeTexture, fontSize); } // Print out for Latency if (!string.IsNullOrEmpty(strLatencies)) { latencies = VariableObjectManager(latencies, "Latency", posY -= offsetY, strLatencies, 17); posY = 0.0f; } initUIComponent = false; isInited = true; } /// <summary> /// Update VR Variables /// </summary> void UpdateVariable() { UpdateIPD(); UpdateEyeHeightOffset(); UpdateEyeDepthOffset(); UpdateFOV(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); UpdateFPS(); } /// <summary> /// Update Strings /// </summary> void UpdateStrings() { if (debugUIObject == null) return; if (!string.IsNullOrEmpty(strFPS)) fps.GetComponentInChildren<Text>().text = strFPS; if (!string.IsNullOrEmpty(strIPD)) ipd.GetComponentInChildren<Text>().text = strIPD; if (!string.IsNullOrEmpty(strFOV)) fov.GetComponentInChildren<Text>().text = strFOV; if (!string.IsNullOrEmpty(strResolutionEyeTexture)) resolutionEyeTexture.GetComponentInChildren<Text>().text = strResolutionEyeTexture; if (!string.IsNullOrEmpty(strLatencies)) { latencies.GetComponentInChildren<Text>().text = strLatencies; latencies.GetComponentInChildren<Text>().fontSize = 14; } if (!string.IsNullOrEmpty(strHeight)) height.GetComponentInChildren<Text>().text = strHeight; if (!string.IsNullOrEmpty(strDepth)) depth.GetComponentInChildren<Text>().text = strDepth; } /// <summary> /// It's for rift present GUI /// </summary> void RiftPresentGUI(GameObject guiMainOBj) { riftPresent = ComponentComposition(riftPresent); riftPresent.transform.SetParent(guiMainOBj.transform); riftPresent.name = "RiftPresent"; RectTransform rectTransform = riftPresent.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0.0f, 0.0f, 0.0f); rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f); rectTransform.localEulerAngles = Vector3.zero; Text text = riftPresent.GetComponentInChildren<Text>(); text.text = strRiftPresent; text.fontSize = 20; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if (riftPresentTimeout >= 0.0f) { riftPresentTimeout -= Time.deltaTime; } } /// <summary> /// Object Manager for Variables /// </summary> /// <returns> gameobject for each Variable </returns> GameObject VariableObjectManager(GameObject gameObject, string name, float posY, string str, int fontSize) { gameObject = ComponentComposition(gameObject); gameObject.name = name; gameObject.transform.SetParent(debugUIObject.transform); RectTransform rectTransform = gameObject.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0.0f, posY -= offsetY, 0.0f); Text text = gameObject.GetComponentInChildren<Text>(); text.text = str; text.fontSize = fontSize; gameObject.transform.localEulerAngles = Vector3.zero; rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f); return gameObject; } /// <summary> /// Component composition /// </summary> /// <returns> Composed gameobject. </returns> GameObject ComponentComposition(GameObject GO) { GO = new GameObject(); GO.AddComponent<RectTransform>(); GO.AddComponent<CanvasRenderer>(); GO.AddComponent<Image>(); GO.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f); GO.GetComponent<Image>().color = new Color(7f / 255f, 45f / 255f, 71f / 255f, 200f / 255f); texts = new GameObject(); texts.AddComponent<RectTransform>(); texts.AddComponent<CanvasRenderer>(); texts.AddComponent<Text>(); texts.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f); texts.GetComponent<Text>().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font; texts.GetComponent<Text>().alignment = TextAnchor.MiddleCenter; texts.transform.SetParent(GO.transform); texts.name = "TextBox"; return GO; } #endregion #region Debugging variables handler /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format("Eye Height (m): {0:F3}", eyeHeight); } /// <summary> /// Updates the eye depth offset. /// </summary> void UpdateEyeDepthOffset() { float eyeDepth = OVRManager.profile.eyeDepth; strDepth = System.String.Format("Eye Depth (m): {0:F3}", eyeDepth); } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { #if UNITY_2017_2_OR_NEWER OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.LeftEye); #else OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.LeftEye); #endif strFOV = System.String.Format("FOV (deg): {0:F3}", eyeDesc.fov.y); } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { #if UNITY_2017_2_OR_NEWER OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.LeftEye); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.XR.XRNode.RightEye); float scale = UnityEngine.XR.XRSettings.renderViewportScale; #else OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.LeftEye); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(UnityEngine.VR.VRNode.RightEye); float scale = UnityEngine.VR.VRSettings.renderViewportScale; #endif float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Latency values are not available."); else strLatencies = System.String.Format("Render: {0:F3} TimeWarp: {1:F3} Post-Present: {2:F3}\nRender Error: {3:F3} TimeWarp Error: {4:F3}", latency.render, latency.timeWarp, latency.postPresent, latency.renderError, latency.timeWarpError); #endif } /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { timeLeft -= Time.unscaledDeltaTime; accum += Time.unscaledDeltaTime; ++frames; // Interval ended - update GUI text and start new interval if (timeLeft <= 0.0) { // display two fractional digits (f2 format) float fps = frames / accum; strFPS = System.String.Format("FPS: {0:F2}", fps); timeLeft += updateInterval; accum = 0.0f; frames = 0; } } #endregion }
0
0.942571
1
0.942571
game-dev
MEDIA
0.918181
game-dev,graphics-rendering
0.96879
1
0.96879
RCInet/LastEpoch_Mods
4,153
AssetBundleExport/Library/PackageCache/com.unity.visualscripting@1b53f46e931b/Editor/VisualScripting.Core/Variables/VariableDeclarationInspector.cs
using UnityEditor; using UnityEngine; namespace Unity.VisualScripting { [Inspector(typeof(VariableDeclaration))] public sealed class VariableDeclarationInspector : Inspector { private Metadata nameMetadata => metadata[nameof(VariableDeclaration.name)]; private Metadata valueMetadata => metadata[nameof(VariableDeclaration.value)]; private Metadata typeMetadata => metadata[nameof(VariableDeclaration.typeHandle)]; public VariableDeclarationInspector(Metadata metadata) : base(metadata) { VSUsageUtility.isVisualScriptingUsed = true; } protected override float GetHeight(float width, GUIContent label) { var height = 0f; using (LudiqGUIUtility.labelWidth.Override(Styles.labelWidth)) { height += Styles.padding; height += GetNameHeight(width); height += Styles.spacing; height += GetTypeHeight(width); height += Styles.spacing; height += GetValueHeight(width); height += Styles.padding; } return height; } private float GetNameHeight(float width) { return EditorGUIUtility.singleLineHeight; } private float GetValueHeight(float width) { return LudiqGUI.GetInspectorHeight(this, valueMetadata, width); } float GetTypeHeight(float width) { return LudiqGUI.GetInspectorHeight(this, typeMetadata, width); } protected override void OnGUI(Rect position, GUIContent label) { position = BeginLabeledBlock(metadata, position, label); using (LudiqGUIUtility.labelWidth.Override(Styles.labelWidth)) { y += Styles.padding; var namePosition = position.VerticalSection(ref y, GetNameHeight(position.width)); y += Styles.spacing; var typePosition = position.VerticalSection(ref y, GetTypeHeight(position.width)); y += Styles.spacing; var valuePosition = position.VerticalSection(ref y, GetValueHeight(position.width)); y += Styles.padding; OnNameGUI(namePosition); OnTypeGUI(typePosition); OnValueGUI(valuePosition); } EndBlock(metadata); } public void OnNameGUI(Rect namePosition) { namePosition = BeginLabeledBlock(nameMetadata, namePosition); var newName = EditorGUI.DelayedTextField(namePosition, (string)nameMetadata.value); if (EndBlock(nameMetadata)) { var variableDeclarations = (VariableDeclarationCollection)metadata.parent.value; if (StringUtility.IsNullOrWhiteSpace(newName)) { EditorUtility.DisplayDialog("Edit Variable Name", "Please enter a variable name.", "OK"); return; } else if (variableDeclarations.Contains(newName)) { EditorUtility.DisplayDialog("Edit Variable Name", "A variable with the same name already exists.", "OK"); return; } nameMetadata.RecordUndo(); variableDeclarations.EditorRename((VariableDeclaration)metadata.value, newName); nameMetadata.value = newName; } } public void OnValueGUI(Rect valuePosition) { LudiqGUI.Inspector(valueMetadata, valuePosition, GUIContent.none); } public void OnTypeGUI(Rect position) { LudiqGUI.Inspector(typeMetadata, position, GUIContent.none); } public static class Styles { public static readonly float labelWidth = SystemObjectInspector.Styles.labelWidth; public static readonly float padding = 2; public static readonly float spacing = EditorGUIUtility.standardVerticalSpacing; } } }
0
0.882677
1
0.882677
game-dev
MEDIA
0.482313
game-dev
0.981463
1
0.981463
McJtyMods/XNet
1,648
src/main/java/mcjty/xnet/datagen/ItemTags.java
package mcjty.xnet.datagen; import mcjty.xnet.modules.cables.CableModule; import net.minecraft.data.DataGenerator; import net.minecraft.data.ItemTagsProvider; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.common.data.ForgeBlockTagsProvider; import javax.annotation.Nonnull; public class ItemTags extends ItemTagsProvider { public ItemTags(DataGenerator generator, ExistingFileHelper helper) { super(generator, new ForgeBlockTagsProvider(generator, helper)); } @Override protected void addTags() { tag(CableModule.TAG_CABLES) .add(CableModule.NETCABLE_BLUE.get(), CableModule.NETCABLE_YELLOW.get(), CableModule.NETCABLE_GREEN.get(), CableModule.NETCABLE_RED.get(), CableModule.NETCABLE_ROUTING.get()); tag(CableModule.TAG_CABLES) .add(CableModule.NETCABLE_BLUE.get(), CableModule.NETCABLE_YELLOW.get(), CableModule.NETCABLE_GREEN.get(), CableModule.NETCABLE_RED.get(), CableModule.NETCABLE_ROUTING.get()); tag(CableModule.TAG_CONNECTORS) .add(CableModule.CONNECTOR_BLUE.get(), CableModule.CONNECTOR_YELLOW.get(), CableModule.CONNECTOR_GREEN.get(), CableModule.CONNECTOR_RED.get(), CableModule.CONNECTOR_ROUTING.get()); tag(CableModule.TAG_ADVANCED_CONNECTORS) .add(CableModule.ADVANCED_CONNECTOR_BLUE.get(), CableModule.ADVANCED_CONNECTOR_YELLOW.get(), CableModule.ADVANCED_CONNECTOR_GREEN.get(), CableModule.ADVANCED_CONNECTOR_RED.get(), CableModule.ADVANCED_CONNECTOR_ROUTING.get()); } @Nonnull @Override public String getName() { return "XNet Tags"; } }
0
0.615183
1
0.615183
game-dev
MEDIA
0.920829
game-dev
0.658417
1
0.658417
gamebooster/dota2-lua-engine
2,582
dota2-lua-engine/dota/dota_hud.h
// Copyright 2013 Karl Skomski - GPL v3 #pragma once #include "dota/dota_item.h" #include "utils/global_address_retriever.h" namespace dota { class CHudElement {}; class Hud { public: static Hud* GetInstance() { if (instance_ == nullptr) { instance_ = reinterpret_cast<Hud*>( GlobalAddressRetriever::GetInstance().GetDynamicAddress("Hud")); } return instance_; } CHudElement* FindSFElement(const char* name) { int list = *reinterpret_cast<int*>(this + 0x44); for (int i = 0; i < 64; i++) { const char* current_name = *(const char**)(list + 0x10 + (0x18 * i)); if (current_name == nullptr) break; if (strcmp(name, current_name) == 0) { return *reinterpret_cast<CHudElement**>( list + 0x10 + (0x18 * i) + 0x4); } } return nullptr; } CHudElement* FindElement(const char* name) { uint32_t address = GlobalAddressRetriever::GetInstance() .GetStaticAddress("Hud::FindElement"); __asm { push name mov ecx, this call address } } private: static Hud* instance_; }; class DotaSFActionPanel { public: static DotaSFActionPanel* GetInstance() { if (instance_ == nullptr) { instance_ = reinterpret_cast<DotaSFActionPanel*>( Hud::GetInstance()->FindSFElement("CDOTA_SF_Hud_ActionPanel")); } return instance_; } void LoadHUDSkin(EconItemView* item, int unknown) { uint32_t address = GlobalAddressRetriever::GetInstance() .GetStaticAddress("SFActionPanel::LoadHudSkin"); __asm { push unknown push item mov ecx, this call address } } private: static DotaSFActionPanel* instance_; }; class DotaSFHudOverlay { public: static DotaSFHudOverlay* GetInstance() { if (instance_ == nullptr) { instance_ = reinterpret_cast<DotaSFHudOverlay*>( Hud::GetInstance()->FindSFElement("CDOTA_SF_Hud_Overlay")); } return instance_; } void ShowSpecItemPickup(const char* hero, const char* item) { uint32_t address = GlobalAddressRetriever::GetInstance() .GetStaticAddress("SFHudOverlay::ShowSpecItemPickup"); __asm { push item push hero mov ecx, this call address } } void SendRoshanPopup(int alive, float time) { uint32_t address = GlobalAddressRetriever::GetInstance() .GetStaticAddress("SFHudOverlay::SendRoshanPopup"); __asm { mov ecx, this movss xmm0, time push alive call address } } private: static DotaSFHudOverlay* instance_; }; } // namespace dota
0
0.867437
1
0.867437
game-dev
MEDIA
0.830381
game-dev
0.794347
1
0.794347
oot-pc-port/oot-pc-port
1,327
asm/non_matchings/overlays/actors/ovl_Demo_Im/func_80985310.s
glabel func_80985310 /* 00730 80985310 27BDFFE0 */ addiu $sp, $sp, 0xFFE0 ## $sp = FFFFFFE0 /* 00734 80985314 AFA50024 */ sw $a1, 0x0024($sp) /* 00738 80985318 AFBF001C */ sw $ra, 0x001C($sp) /* 0073C 8098531C 3C050600 */ lui $a1, 0x0600 ## $a1 = 06000000 /* 00740 80985320 AFA40020 */ sw $a0, 0x0020($sp) /* 00744 80985324 24A51868 */ addiu $a1, $a1, 0x1868 ## $a1 = 06001868 /* 00748 80985328 AFA00010 */ sw $zero, 0x0010($sp) /* 0074C 8098532C 00003025 */ or $a2, $zero, $zero ## $a2 = 00000000 /* 00750 80985330 0C2614A0 */ jal func_80985280 /* 00754 80985334 24070000 */ addiu $a3, $zero, 0x0000 ## $a3 = 00000000 /* 00758 80985338 3C018099 */ lui $at, %hi(D_809889D8) ## $at = 80990000 /* 0075C 8098533C C42489D8 */ lwc1 $f4, %lo(D_809889D8)($at) /* 00760 80985340 8FAE0020 */ lw $t6, 0x0020($sp) /* 00764 80985344 E5C400BC */ swc1 $f4, 0x00BC($t6) ## 000000BC /* 00768 80985348 8FBF001C */ lw $ra, 0x001C($sp) /* 0076C 8098534C 27BD0020 */ addiu $sp, $sp, 0x0020 ## $sp = 00000000 /* 00770 80985350 03E00008 */ jr $ra /* 00774 80985354 00000000 */ nop
0
0.645203
1
0.645203
game-dev
MEDIA
0.939027
game-dev
0.54385
1
0.54385
H-uru/Plasma
21,567
Sources/Plasma/PubUtilLib/plParticleSystem/plParticleSystem.cpp
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "plParticleSystem.h" #include "plParticle.h" #include "plParticleEffect.h" #include "plParticleEmitter.h" #include "plParticleGenerator.h" #include "plParticleSDLMod.h" #include "plgDispatch.h" #include "plPipeline.h" #include "plProfile.h" #include "hsResMgr.h" #include "hsTimer.h" #include "plTweak.h" #include "pnMessage/plRefMsg.h" #include "pnMessage/plTimeMsg.h" #include "pnNetCommon/plSDLTypes.h" #include "pnSceneObject/plSceneObject.h" #include "pnSceneObject/plDrawInterface.h" #include "pnSceneObject/plCoordinateInterface.h" #include "plDrawable/plParticleFiller.h" #include "plSurface/hsGMaterial.h" #include "plInterp/plController.h" #include "plMessage/plAgeLoadedMsg.h" #include "plMessage/plParticleUpdateMsg.h" #include "plMessage/plRenderMsg.h" plProfile_CreateCounter("Num Particles", "Particles", NumParticles); const float plParticleSystem::GRAVITY_ACCEL_FEET_PER_SEC2 = 32.0f; plParticleSystem::~plParticleSystem() { int i; for (i = 0; i < fNumValidEmitters; i++) { delete fEmitters[i]; } delete [] fEmitters; delete fAmbientCtl; delete fDiffuseCtl; delete fOpacityCtl; delete fWidthCtl; delete fHeightCtl; } void plParticleSystem::Init(uint32_t xTiles, uint32_t yTiles, uint32_t maxTotalParticles, uint32_t maxEmitters, plController *ambientCtl, plController *diffuseCtl, plController *opacityCtl, plController *widthCtl, plController *heightCtl) { fTarget = nullptr; fLastTime = 0; fCurrTime = 0; SetGravity(1.0f); fDrag = 0; fWindMult = 1.f; fNumValidEmitters = 0; fNextEmitterToGo = 0; fMiscFlags = 0; fForces.clear(); fEffects.clear(); fConstraints.clear(); fXTiles = xTiles; fYTiles = yTiles; fMaxTotalParticles = fMaxTotalParticlesLeft = maxTotalParticles; fMaxEmitters = maxEmitters; fEmitters = new plParticleEmitter *[fMaxEmitters]; int i; for (i = 0; i < maxEmitters; i++) fEmitters[i] = nullptr; fAmbientCtl = ambientCtl; fDiffuseCtl = diffuseCtl; fOpacityCtl = opacityCtl; fWidthCtl = widthCtl; fHeightCtl = heightCtl; } void plParticleSystem::IAddEffect(plParticleEffect *effect, uint32_t type) { switch(type) { case kEffectForce: fForces.emplace_back(effect); break; case kEffectMisc: default: fEffects.emplace_back(effect); break; case kEffectConstraint: fConstraints.emplace_back(effect); break; } } plParticleEmitter* plParticleSystem::GetAvailEmitter() { if( !fNumValidEmitters ) // got to start with at least one. return nullptr; float minTTL = 1.e33f; int iMinTTL = -1; int i; for( i = 0; i < fNumValidEmitters; i++ ) { if( fEmitters[i]->GetTimeToLive() < minTTL ) { minTTL = fEmitters[i]->GetTimeToLive(); iMinTTL = i; } } if( minTTL > 0 ) { if( fNumValidEmitters < fMaxEmitters ) { minTTL = 0; iMinTTL = fNumValidEmitters++; fEmitters[iMinTTL] = new plParticleEmitter(); fEmitters[iMinTTL]->Clone(fEmitters[0], iMinTTL); hsAssert(fMaxTotalParticlesLeft >= fEmitters[iMinTTL]->fMaxParticles, "Should have planned better"); fMaxTotalParticlesLeft -= fEmitters[iMinTTL]->fMaxParticles; // Don't really use this. fEmitters[i]->GetSpanIndex() always == i. fNextEmitterToGo = (fNextEmitterToGo + 1) % fMaxEmitters; } } return fEmitters[iMinTTL]; } uint32_t plParticleSystem::AddEmitter(uint32_t maxParticles, plParticleGenerator *gen, uint32_t emitterFlags) { if (fMaxEmitters == 0) // silly rabbit, Trix are for kids! return 0; uint32_t currEmitter; if (fNumValidEmitters == fMaxEmitters) // No more free spots, snag the next in line. { int i; for (i = 0; i < fMaxEmitters; i++) { if (fEmitters[i]->GetSpanIndex() == fNextEmitterToGo) break; } currEmitter = i; fMaxTotalParticlesLeft += fEmitters[currEmitter]->fMaxParticles; hsAssert(fMaxTotalParticlesLeft <= fMaxTotalParticles, "Particle system somehow has more particles than it started with."); delete fEmitters[currEmitter]; } else { currEmitter = fNumValidEmitters; fNumValidEmitters++; } if (maxParticles > fMaxTotalParticlesLeft) maxParticles = fMaxTotalParticlesLeft; fEmitters[currEmitter] = new plParticleEmitter(); fEmitters[currEmitter]->Init(this, maxParticles, fNextEmitterToGo, emitterFlags, gen); fMaxTotalParticlesLeft -= fEmitters[currEmitter]->fMaxParticles; fNextEmitterToGo = (fNextEmitterToGo + 1) % fMaxEmitters; return maxParticles; } void plParticleSystem::AddParticle(hsPoint3 &pos, hsVector3 &velocity, uint32_t tileIndex, float hSize, float vSize, float scale, float invMass, float life, hsPoint3 &orientation, uint32_t miscFlags, float radsPerSec) { hsAssert(fNumValidEmitters > 0, "Trying to explicitly add particles to a system with no valid emitters."); if (fNumValidEmitters == 0) return; fEmitters[0]->AddParticle(pos, velocity, tileIndex, hSize, vSize, scale, invMass, life, orientation, miscFlags, radsPerSec); } void plParticleSystem::GenerateParticles(uint32_t num, float dt /* = 0.f */) { if (num <= 0) return; if (fNumValidEmitters > 0 && fEmitters[0]->fGenerator) fEmitters[0]->fGenerator->AddAutoParticles(fEmitters[0], dt, num); GetTarget(0)->DirtySynchState(kSDLParticleSystem, 0); } void plParticleSystem::WipeExistingParticles() { int i; for (i = 0; i < fNumValidEmitters; i++) fEmitters[i]->WipeExistingParticles(); } void plParticleSystem::KillParticles(float num, float timeToDie, uint8_t flags) { if (fEmitters[0]) fEmitters[0]->KillParticles(num, timeToDie, flags); GetTarget(0)->DirtySynchState(kSDLParticleSystem, 0); } void plParticleSystem::TranslateAllParticles(hsPoint3 &amount) { int i; for (i = 0; i < fNumValidEmitters; i++) fEmitters[i]->TranslateAllParticles(amount); } void plParticleSystem::DisableGenerators() { int i; for (i = 0; i < fNumValidEmitters; i++) fEmitters[i]->UpdateGenerator(plParticleUpdateMsg::kParamEnabled, 0.f); } uint16_t plParticleSystem::StealParticlesFrom(plParticleSystem *victim, uint16_t num) { if (fNumValidEmitters <= 0) return 0; // you just lose if (victim) { uint16_t numStolen = fEmitters[0]->StealParticlesFrom(victim->fNumValidEmitters > 0 ? victim->fEmitters[0] : nullptr, num); GetTarget(0)->DirtySynchState(kSDLParticleSystem, 0); victim->GetTarget(0)->DirtySynchState(kSDLParticleSystem, 0); return numStolen; } return 0; } plParticleGenerator *plParticleSystem::GetExportedGenerator() const { return (fNumValidEmitters > 0 ? fEmitters[0]->fGenerator : nullptr); } plParticleEffect *plParticleSystem::GetEffect(uint16_t type) const { for (plParticleEffect* forceEffect : fForces) if (forceEffect->ClassIndex() == type) return forceEffect; for (plParticleEffect* effect : fEffects) if (effect->ClassIndex() == type) return effect; for (plParticleEffect* constraint : fConstraints) if (constraint->ClassIndex() == type) return constraint; return nullptr; } uint32_t plParticleSystem::GetNumValidParticles(bool immortalOnly /* = false */) const { uint32_t count = 0; int i, j; for (i = 0; i < fNumValidEmitters; i++) { if (immortalOnly) { for (j = 0; j < fEmitters[i]->fNumValidParticles; j++) { if (fEmitters[i]->fParticleExts[j].fMiscFlags & plParticleExt::kImmortal) count++; } } else count += fEmitters[i]->fNumValidParticles; } return count; } const hsMatrix44 &plParticleSystem::GetLocalToWorld() const { return fTarget->GetCoordinateInterface()->GetLocalToWorld(); } bool plParticleSystem::IEval(double secs, float del, uint32_t dirty) { return false; } bool plParticleSystem::IShouldUpdate(plPipeline* pipe) const { if (fMiscFlags & kParticleSystemAlwaysUpdate) return true; if (IGetTargetDrawInterface(0) && IGetTargetDrawInterface(0)->GetProperty(plDrawInterface::kDisable)) return false; // First, what are the cumulative bounds for this system. hsBounds3Ext wBnd; wBnd.MakeEmpty(); int i; for( i = 0; i < fNumValidEmitters; i++ ) { if( fEmitters[i]->GetBoundingBox().GetType() == kBoundsNormal ) wBnd.Union(&fEmitters[i]->GetBoundingBox()); } // Always update if we are currently empty if( wBnd.GetType() == kBoundsEmpty ) { return true; } // Now, are we visible? bool isVisible = pipe->TestVisibleWorld(wBnd); float delta = fLastTime > 0 ? float(fCurrTime - fLastTime) : hsTimer::GetDelSysSeconds(); if( isVisible ) { // If we know how fast the fastest particle is moving, then we can // decide if the system is too far away to need to update every single frame. // In fact, based on the speed of the fastest particle, we can determine an // exact update rate for a given error (say 3 pixels?). // But we don't currently know the speed of the fastest particle, so // until we do, I'm commenting this out. Most of the speed gain from // culling particle updates was from not updating systems that aren't visible // anyway. #if 0 // ALWAYS_IF_VISIBLE // We're in view, but how close are we to the camera? Look at closest point. hsPoint2 depth; wBnd.TestPlane(pipe->GetViewDirWorld(), depth); float eyeDist = pipe->GetViewDirWorld().InnerProduct(pipe->GetViewPositionWorld()); float dist = depth.fX - eyeDist; static float kUpdateCutoffDist = 100.f; if( dist > kUpdateCutoffDist ) { static float kDistantUpdateSecs = 0.1f; return delta >= kDistantUpdateSecs; } #endif // ALWAYS_IF_VISIBLE return true; } static float kOffscreenUpdateSecs = 1.f; return delta >= kOffscreenUpdateSecs; } plDrawInterface* plParticleSystem::ICheckDrawInterface() { plDrawInterface* di = IGetTargetDrawInterface(0); if( !di ) return nullptr; if( di->GetDrawableMeshIndex(0) == uint32_t(-1) ) { di->SetUpForParticleSystem( fMaxEmitters + 1, fMaxTotalParticles, fTexture, fPermaLights ); hsAssert(di->GetDrawableMeshIndex( 0 ) != (uint32_t)-1, "SetUpForParticleSystem should never fail"); // still invalid, didn't fix it. } return di; } void plParticleSystem::IHandleRenderMsg(plPipeline* pipe) { fCurrTime = hsTimer::GetSysSeconds(); float delta = float(fCurrTime - fLastTime); if (delta == 0) return; plConst(float) kMaxDelta(0.3f); if( delta > kMaxDelta ) delta = kMaxDelta; plDrawInterface* di = ICheckDrawInterface(); if( !di ) return; bool disabled = di->GetProperty(plDrawInterface::kDisable); if (!IShouldUpdate(pipe)) { if (disabled) di->ResetParticleSystem(); // Need to call this, otherwise particles get drawn, even though the DI is disabled. // (Yes, it's lame.) // Otherwise, we leave the DI alone, and the particles draw in the same place they were last frame. return; } fContext.fPipeline = pipe; fContext.fSystem = this; fContext.fSecs = fCurrTime; fContext.fDelSecs = delta; di->ResetParticleSystem(); if (fPreSim > 0) IPreSim(); int i; for (i = 0; i < fNumValidEmitters; i++) { fEmitters[i]->IUpdate(delta); plProfile_IncCount(NumParticles, fEmitters[i]->fNumValidParticles); if (!disabled) { if( fEmitters[ i ]->GetParticleCount() > 0 ) di->AssignEmitterToParticleSystem( fEmitters[ i ] ); // Go make those polys! } } // plParticleFiller::FillParticlePolys(pipe, di); fLastTime = fCurrTime; } #include "plProfile.h" plProfile_CreateTimer("ParticleSys", "RenderSetup", ParticleSys); bool plParticleSystem::MsgReceive(plMessage* msg) { plGenRefMsg* refMsg; plParticleUpdateMsg *partMsg; plParticleKillMsg *killMsg; plSceneObject *scene; plParticleEffect *effect; hsGMaterial *mat; plRenderMsg *rend; plAgeLoadedMsg* ageLoaded; if ((rend = plRenderMsg::ConvertNoRef(msg))) { plProfile_BeginLap(ParticleSys, this->GetKey()->GetUoid().GetObjectName()); IHandleRenderMsg(rend->Pipeline()); plProfile_EndLap(ParticleSys, this->GetKey()->GetUoid().GetObjectName()); return true; } else if ((refMsg = plGenRefMsg::ConvertNoRef(msg))) { if ((scene = plSceneObject::ConvertNoRef(refMsg->GetRef()))) { if (refMsg->GetContext() & (plRefMsg::kOnCreate|plRefMsg::kOnRequest|plRefMsg::kOnReplace)) AddTarget(scene); else RemoveTarget(scene); return true; } if ((mat = hsGMaterial::ConvertNoRef(refMsg->GetRef()))) { if (refMsg->GetContext() & (plRefMsg::kOnCreate|plRefMsg::kOnRequest|plRefMsg::kOnReplace)) fTexture = mat; else fTexture = nullptr; return true; } if ((effect = plParticleEffect::ConvertNoRef(refMsg->GetRef()))) { if (refMsg->GetContext() & (plRefMsg::kOnCreate|plRefMsg::kOnRequest|plRefMsg::kOnReplace)) IAddEffect(effect, refMsg->fType); //else // IRemoveEffect(effect, refMsg->fType); return true; } } else if ((partMsg = plParticleUpdateMsg::ConvertNoRef(msg))) { UpdateGenerator(partMsg->GetParamID(), partMsg->GetParamValue()); return true; } else if ((killMsg = plParticleKillMsg::ConvertNoRef(msg))) { KillParticles(killMsg->fNumToKill, killMsg->fTimeLeft, killMsg->fFlags); return true; } else if( (ageLoaded = plAgeLoadedMsg::ConvertNoRef(msg)) && ageLoaded->fLoaded ) { ICheckDrawInterface(); return true; } return plModifier::MsgReceive(msg); } void plParticleSystem::UpdateGenerator(uint32_t paramID, float value) { int i; for (i = 0; i < fNumValidEmitters; i++) fEmitters[i]->UpdateGenerator(paramID, value); } void plParticleSystem::AddTarget(plSceneObject *so) { if (fTarget != nullptr) RemoveTarget(fTarget); fTarget = so; plgDispatch::Dispatch()->RegisterForExactType(plTimeMsg::Index(), GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plRenderMsg::Index(), GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plAgeLoadedMsg::Index(), GetKey()); delete fParticleSDLMod; fParticleSDLMod = new plParticleSDLMod; fParticleSDLMod->SetAttachedToAvatar(fAttachedToAvatar); so->AddModifier(fParticleSDLMod); } void plParticleSystem::RemoveTarget(plSceneObject *so) { if (so == fTarget && so != nullptr) { if (fParticleSDLMod) { so->RemoveModifier(fParticleSDLMod); delete fParticleSDLMod; fParticleSDLMod = nullptr; } fTarget = nullptr; } } // This can be done much faster, but it's only done on load, and very very clean as is. Saving optimization for // when we observe that it's too slow. void plParticleSystem::IPreSim() { const double PRESIM_UPDATE_TICK = 0.1; int i; for (i = 0; i < fNumValidEmitters; i++) { double secs = fPreSim; while (secs > 0) { fEmitters[i]->IUpdateParticles((float)PRESIM_UPDATE_TICK); secs -= PRESIM_UPDATE_TICK; } } fPreSim = 0; } void plParticleSystem::IReadEffectsArray(std::vector<plParticleEffect *> &effects, uint32_t type, hsStream *s, hsResMgr *mgr) { plGenRefMsg *msg; effects.clear(); uint32_t count = s->ReadLE32(); effects.reserve(count); for (uint32_t i = 0; i < count; i++) { msg = new plGenRefMsg(GetKey(), plRefMsg::kOnCreate, 0, (int8_t)type); mgr->ReadKeyNotifyMe(s, msg, plRefFlags::kActiveRef); } } void plParticleSystem::Read(hsStream *s, hsResMgr *mgr) { plModifier::Read(s, mgr); plGenRefMsg* msg; msg = new plGenRefMsg(GetKey(), plRefMsg::kOnCreate, 0, 0); // Material mgr->ReadKeyNotifyMe(s, msg, plRefFlags::kActiveRef); fAmbientCtl = plController::ConvertNoRef(mgr->ReadCreatable(s)); fDiffuseCtl = plController::ConvertNoRef(mgr->ReadCreatable(s)); fOpacityCtl = plController::ConvertNoRef(mgr->ReadCreatable(s)); fWidthCtl = plController::ConvertNoRef(mgr->ReadCreatable(s)); fHeightCtl = plController::ConvertNoRef(mgr->ReadCreatable(s)); uint32_t xTiles = s->ReadLE32(); uint32_t yTiles = s->ReadLE32(); uint32_t maxTotal = s->ReadLE32(); uint32_t maxEmitters = s->ReadLE32(); Init(xTiles, yTiles, maxTotal, maxEmitters, fAmbientCtl, fDiffuseCtl, fOpacityCtl, fWidthCtl, fHeightCtl); fPreSim = s->ReadLEFloat(); fAccel.Read(s); fDrag = s->ReadLEFloat(); fWindMult = s->ReadLEFloat(); fNumValidEmitters = s->ReadLE32(); for (uint32_t i = 0; i < fNumValidEmitters; i++) { fEmitters[i] = plParticleEmitter::ConvertNoRef(mgr->ReadCreatable(s)); fEmitters[i]->ISetSystem(this); } IReadEffectsArray(fForces, kEffectForce, s, mgr); IReadEffectsArray(fEffects, kEffectMisc, s, mgr); IReadEffectsArray(fConstraints, kEffectConstraint, s, mgr); uint32_t count = s->ReadLE32(); fPermaLights.resize(count); for (uint32_t i = 0; i < count; i++) fPermaLights[i] = mgr->ReadKey(s); } void plParticleSystem::Write(hsStream *s, hsResMgr *mgr) { plModifier::Write(s, mgr); int i; mgr->WriteKey(s, fTexture); // Arguments to the Init() function mgr->WriteCreatable(s, fAmbientCtl); mgr->WriteCreatable(s, fDiffuseCtl); mgr->WriteCreatable(s, fOpacityCtl); mgr->WriteCreatable(s, fWidthCtl); mgr->WriteCreatable(s, fHeightCtl); s->WriteLE32(fXTiles); s->WriteLE32(fYTiles); s->WriteLE32(fMaxTotalParticles); s->WriteLE32(fMaxEmitters); s->WriteLEFloat(fPreSim); fAccel.Write(s); s->WriteLEFloat(fDrag); s->WriteLEFloat(fWindMult); s->WriteLE32(fNumValidEmitters); for (i = 0; i < fNumValidEmitters; i++) { mgr->WriteCreatable(s, fEmitters[i]); } s->WriteLE32((uint32_t)fForces.size()); for (plParticleEffect* forceEffect : fForces) mgr->WriteKey(s, forceEffect); s->WriteLE32((uint32_t)fEffects.size()); for (plParticleEffect* effect : fEffects) mgr->WriteKey(s, effect); s->WriteLE32((uint32_t)fConstraints.size()); for (plParticleEffect* constraint : fConstraints) mgr->WriteKey(s, constraint); s->WriteLE32((uint32_t)fPermaLights.size()); for (const plKey& key : fPermaLights) mgr->WriteKey(s, key); } void plParticleSystem::SetAttachedToAvatar(bool attached) { fAttachedToAvatar = attached; if (fParticleSDLMod) fParticleSDLMod->SetAttachedToAvatar(attached); } void plParticleSystem::AddLight(plKey liKey) { fPermaLights.emplace_back(std::move(liKey)); }
0
0.967729
1
0.967729
game-dev
MEDIA
0.679461
game-dev
0.94745
1
0.94745
NathanHandley/EQWOWConverter
2,078
EQWOWConverter/Files/WOWFiles/SQL/World/CreatureTextSQL.cs
// Author: Nathan Handley (nathanhandley@protonmail.com) // Copyright (c) 2025 Nathan Handley // // 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/>. namespace EQWOWConverter.WOWFiles { internal class CreatureTextSQL : SQLFile { public override string DeleteRowSQL() { return "DELETE FROM `creature_text` WHERE `CreatureID` >= " + Configuration.SQL_CREATURETEMPLATE_ENTRY_LOW.ToString() + " AND `CreatureID` <= " + Configuration.SQL_CREATURETEMPLATE_ENTRY_HIGH + ";"; } public void AddRow(int creatureTemplateID, int groupID, int typeID, string messageText, int broadcastTextID, int durationInMS, string comment) { SQLRow newRow = new SQLRow(); newRow.AddInt("CreatureID", creatureTemplateID); newRow.AddInt("GroupID", groupID); newRow.AddInt("ID", 0); newRow.AddString("Text", messageText); newRow.AddInt("Type", typeID); // 12 = Say, 14 = Yell, 16 = Emote, 41 = Boss Emote, 15 = Whisper, 42 = Boss Whisper newRow.AddInt("Language", 0); newRow.AddFloat("Probability", 100); newRow.AddInt("Emote", 0); newRow.AddInt("Duration", durationInMS); newRow.AddInt("Sound", 0); newRow.AddInt("BroadcastTextId", broadcastTextID); newRow.AddInt("TextRange", 0); newRow.AddString("comment", 255, comment); Rows.Add(newRow); } } }
0
0.812904
1
0.812904
game-dev
MEDIA
0.467413
game-dev
0.8962
1
0.8962
quiverteam/Engine
9,944
src/game/server/h_ai.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Utility functions used by AI code. // //=============================================================================// #include "cbase.h" #include "game.h" #include "vstdlib/random.h" #include "movevars_shared.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define NUM_LATERAL_CHECKS 13 // how many checks are made on each side of a NPC looking for lateral cover #define NUM_LATERAL_LOS_CHECKS 6 // how many checks are made on each side of a NPC looking for lateral cover #define TOSS_HEIGHT_MAX 300 // altitude of initial trace done to see how high something can be tossed //float flRandom = random->RandomFloat(0,1); bool g_fDrawLines = FALSE; //========================================================= // FBoxVisible - a more accurate ( and slower ) version // of FVisible. // // !!!UNDONE - make this CAI_BaseNPC? //========================================================= bool FBoxVisible( CBaseEntity *pLooker, CBaseEntity *pTarget, Vector &vecTargetOrigin, float flSize ) { // don't look through water if ((pLooker->GetWaterLevel() != 3 && pTarget->GetWaterLevel() == 3) || (pLooker->GetWaterLevel() == 3 && pTarget->GetWaterLevel() == 0)) return FALSE; trace_t tr; Vector vecLookerOrigin = pLooker->EyePosition();//look through the NPC's 'eyes' for (int i = 0; i < 5; i++) { Vector vecTarget = pTarget->GetAbsOrigin(); vecTarget.x += random->RandomFloat( pTarget->WorldAlignMins().x + flSize, pTarget->WorldAlignMaxs().x - flSize); vecTarget.y += random->RandomFloat( pTarget->WorldAlignMins().y + flSize, pTarget->WorldAlignMaxs().y - flSize); vecTarget.z += random->RandomFloat( pTarget->WorldAlignMins().z + flSize, pTarget->WorldAlignMaxs().z - flSize); UTIL_TraceLine(vecLookerOrigin, vecTarget, MASK_BLOCKLOS, pLooker, COLLISION_GROUP_NONE, &tr); if (tr.fraction == 1.0) { vecTargetOrigin = vecTarget; return TRUE;// line of sight is valid. } } return FALSE;// Line of sight is not established } //----------------------------------------------------------------------------- // Purpose: Returns the correct toss velocity to throw a given object at a point. // Like the other version of VecCheckToss, but allows you to filter for any // number of entities to ignore. // Input : pEntity - The object doing the throwing. Is *NOT* automatically included in the // filter below. // pFilter - A trace filter of entities to ignore in the object's collision sweeps. // It is recommended to include at least the thrower. // vecSpot1 - The point from which the object is being thrown. // vecSpot2 - The point TO which the object is being thrown. // flHeightMaxRatio - A scale factor indicating the maximum ratio of height // to total throw distance, measured from the higher of the two endpoints to // the apex. -1 indicates that there is no maximum. // flGravityAdj - Scale factor for gravity - should match the gravity scale // that the object will use in midair. // bRandomize - when true, introduces a little fudge to the throw // Output : Velocity to throw the object with. //----------------------------------------------------------------------------- Vector VecCheckToss( CBaseEntity *pEntity, ITraceFilter *pFilter, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins, Vector *vecMaxs ) { trace_t tr; Vector vecMidPoint;// halfway point between Spot1 and Spot2 Vector vecApex;// highest point Vector vecScale; Vector vecTossVel; Vector vecTemp; float flGravity = sv_gravity.GetFloat() * flGravityAdj; if (vecSpot2.z - vecSpot1.z > 500) { // to high, fail return vec3_origin; } Vector forward, right; AngleVectors( pEntity->GetLocalAngles(), &forward, &right, NULL ); if (bRandomize) { // toss a little bit to the left or right, not right down on the enemy's bean (head). vecSpot2 += right * ( random->RandomFloat(-8,8) + random->RandomFloat(-16,16) ); vecSpot2 += forward * ( random->RandomFloat(-8,8) + random->RandomFloat(-16,16) ); } // calculate the midpoint and apex of the 'triangle' // UNDONE: normalize any Z position differences between spot1 and spot2 so that triangle is always RIGHT // get a rough idea of how high it can be thrown vecMidPoint = vecSpot1 + (vecSpot2 - vecSpot1) * 0.5; UTIL_TraceLine(vecMidPoint, vecMidPoint + Vector(0,0,TOSS_HEIGHT_MAX), MASK_SOLID_BRUSHONLY, pFilter, &tr); vecMidPoint = tr.endpos; if( tr.fraction != 1.0 ) { // (subtract 15 so the object doesn't hit the ceiling) vecMidPoint.z -= 15; } if (flHeightMaxRatio != -1) { // But don't throw so high that it looks silly. Maximize the height of the // throw above the highest of the two endpoints to a ratio of the throw length. float flHeightMax = flHeightMaxRatio * (vecSpot2 - vecSpot1).Length(); float flHighestEndZ = max(vecSpot1.z, vecSpot2.z); if ((vecMidPoint.z - flHighestEndZ) > flHeightMax) { vecMidPoint.z = flHighestEndZ + flHeightMax; } } if (vecMidPoint.z < vecSpot1.z || vecMidPoint.z < vecSpot2.z) { // Not enough space, fail return vec3_origin; } // How high should the object travel to reach the apex float distance1 = (vecMidPoint.z - vecSpot1.z); float distance2 = (vecMidPoint.z - vecSpot2.z); // How long will it take for the object to travel this distance float time1 = sqrt( distance1 / (0.5 * flGravity) ); float time2 = sqrt( distance2 / (0.5 * flGravity) ); if (time1 < 0.1) { // too close return vec3_origin; } // how hard to throw sideways to get there in time. vecTossVel = (vecSpot2 - vecSpot1) / (time1 + time2); // how hard upwards to reach the apex at the right time. vecTossVel.z = flGravity * time1; // find the apex vecApex = vecSpot1 + vecTossVel * time1; vecApex.z = vecMidPoint.z; // JAY: Repro behavior from HL1 -- toss check went through gratings UTIL_TraceLine(vecSpot1, vecApex, (MASK_SOLID&(~CONTENTS_GRATE)), pFilter, &tr); if (tr.fraction != 1.0) { // fail! return vec3_origin; } // UNDONE: either ignore NPCs or change it to not care if we hit our enemy UTIL_TraceLine(vecSpot2, vecApex, (MASK_SOLID_BRUSHONLY&(~CONTENTS_GRATE)), pFilter, &tr); if (tr.fraction != 1.0) { // fail! return vec3_origin; } if ( vecMins && vecMaxs ) { // Check to ensure the entity's hull can travel the first half of the grenade throw UTIL_TraceHull( vecSpot1, vecApex, *vecMins, *vecMaxs, (MASK_SOLID&(~CONTENTS_GRATE)), pFilter, &tr); if ( tr.fraction < 1.0 ) return vec3_origin; } return vecTossVel; } //----------------------------------------------------------------------------- // Purpose: Returns the correct toss velocity to throw a given object at a point. // Input : pEntity - The entity that is throwing the object. // vecSpot1 - The point from which the object is being thrown. // vecSpot2 - The point TO which the object is being thrown. // flHeightMaxRatio - A scale factor indicating the maximum ratio of height // to total throw distance, measured from the higher of the two endpoints to // the apex. -1 indicates that there is no maximum. // flGravityAdj - Scale factor for gravity - should match the gravity scale // that the object will use in midair. // bRandomize - when true, introduces a little fudge to the throw // Output : Velocity to throw the object with. //----------------------------------------------------------------------------- Vector VecCheckToss( CBaseEntity *pEntity, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins, Vector *vecMaxs ) { // construct a filter and call through to the other version of this function. CTraceFilterSimple traceFilter( pEntity, COLLISION_GROUP_NONE ); return VecCheckToss( pEntity, &traceFilter, vecSpot1, vecSpot2, flHeightMaxRatio, flGravityAdj, bRandomize, vecMins, vecMaxs ); } // // VecCheckThrow - returns the velocity vector at which an object should be thrown from vecspot1 to hit vecspot2. // returns vec3_origin if throw is not feasible. // Vector VecCheckThrow ( CBaseEntity *pEdict, const Vector &vecSpot1, Vector vecSpot2, float flSpeed, float flGravityAdj, Vector *vecMins, Vector *vecMaxs ) { float flGravity = sv_gravity.GetFloat() * flGravityAdj; Vector vecGrenadeVel = (vecSpot2 - vecSpot1); // throw at a constant time float time = vecGrenadeVel.Length( ) / flSpeed; vecGrenadeVel = vecGrenadeVel * (1.0 / time); // adjust upward toss to compensate for gravity loss vecGrenadeVel.z += flGravity * time * 0.5; Vector vecApex = vecSpot1 + (vecSpot2 - vecSpot1) * 0.5; vecApex.z += 0.5 * flGravity * (time * 0.5) * (time * 0.5); trace_t tr; UTIL_TraceLine(vecSpot1, vecApex, MASK_SOLID, pEdict, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) { // fail! //NDebugOverlay::Line( vecSpot1, vecApex, 255, 0, 0, true, 5.0 ); return vec3_origin; } //NDebugOverlay::Line( vecSpot1, vecApex, 0, 255, 0, true, 5.0 ); UTIL_TraceLine(vecSpot2, vecApex, MASK_SOLID_BRUSHONLY, pEdict, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) { // fail! //NDebugOverlay::Line( vecApex, vecSpot2, 255, 0, 0, true, 5.0 ); return vec3_origin; } //NDebugOverlay::Line( vecApex, vecSpot2, 0, 255, 0, true, 5.0 ); if ( vecMins && vecMaxs ) { // Check to ensure the entity's hull can travel the first half of the grenade throw UTIL_TraceHull( vecSpot1, vecApex, *vecMins, *vecMaxs, MASK_SOLID, pEdict, COLLISION_GROUP_NONE, &tr); if ( tr.fraction < 1.0 ) { //NDebugOverlay::SweptBox( vecSpot1, tr.endpos, *vecMins, *vecMaxs, vec3_angle, 255, 0, 0, 64, 5.0 ); return vec3_origin; } } //NDebugOverlay::SweptBox( vecSpot1, vecApex, *vecMins, *vecMaxs, vec3_angle, 0, 255, 0, 64, 5.0 ); return vecGrenadeVel; }
0
0.888672
1
0.888672
game-dev
MEDIA
0.841888
game-dev
0.986837
1
0.986837
Space-Stories/space-station-14
2,665
Content.IntegrationTests/Tests/ConfigPresetTests.cs
using System.Collections.Generic; using System.IO; using Content.Server.Entry; using Robust.Shared.Configuration; using Robust.Shared.ContentPack; namespace Content.IntegrationTests.Tests; [TestFixture] public sealed class ConfigPresetTests { [Test] public async Task TestLoadAll() { var pair = await PoolManager.GetServerClient(); var server = pair.Server; var resources = server.ResolveDependency<IResourceManager>(); var config = server.ResolveDependency<IConfigurationManager>(); await server.WaitPost(() => { var originalCVars = new List<(string, object)>(); foreach (var cvar in config.GetRegisteredCVars()) { var value = config.GetCVar<object>(cvar); originalCVars.Add((cvar, value)); } var originalCVarsStream = new MemoryStream(); config.SaveToTomlStream(originalCVarsStream, config.GetRegisteredCVars()); originalCVarsStream.Position = 0; var presets = resources.ContentFindFiles(EntryPoint.ConfigPresetsDir); Assert.Multiple(() => { foreach (var preset in presets) { var stream = resources.ContentFileRead(preset); Assert.DoesNotThrow(() => config.LoadDefaultsFromTomlStream(stream)); } }); config.LoadDefaultsFromTomlStream(originalCVarsStream); foreach (var (cvar, value) in originalCVars) { config.SetCVar(cvar, value); } foreach (var originalCVar in originalCVars) { var (name, originalValue) = originalCVar; var newValue = config.GetCVar<object>(name); var originalValueType = originalValue.GetType(); var newValueType = newValue.GetType(); if (originalValueType.IsEnum || newValueType.IsEnum) { originalValue = Enum.ToObject(originalValueType, originalValue); newValue = Enum.ToObject(originalValueType, newValue); } if (originalValueType == typeof(float) || newValueType == typeof(float)) { originalValue = Convert.ToSingle(originalValue); newValue = Convert.ToSingle(newValue); } if (!Equals(newValue, originalValue)) Assert.Fail($"CVar {name} was not reset to its original value."); } }); await pair.CleanReturnAsync(); } }
0
0.868961
1
0.868961
game-dev
MEDIA
0.270409
game-dev
0.923136
1
0.923136
kwsch/PKHeX
4,173
PKHeX.Core/Legality/Encounters/Verifiers/MysteryGiftVerifier.cs
using System; using System.Collections.Generic; using static PKHeX.Core.LegalityCheckResultCode; using static System.Buffers.Binary.BinaryPrimitives; namespace PKHeX.Core; public static class MysteryGiftVerifier { private static readonly Dictionary<int, MysteryGiftRestriction>?[] RestrictionSet = Get(); private static Dictionary<int, MysteryGiftRestriction>?[] Get() { var s = new Dictionary<int, MysteryGiftRestriction>?[Latest.Generation + 1]; for (byte i = 3; i < s.Length; i++) s[i] = GetRestriction(i); return s; } private static string RestrictionSetName(byte generation) => $"mgrestrict{generation}.pkl"; private static Dictionary<int, MysteryGiftRestriction> GetRestriction(byte generation) { var resource = RestrictionSetName(generation); var data = Util.GetBinaryResource(resource).AsSpan(); var dict = new Dictionary<int, MysteryGiftRestriction>(); for (int i = 0; i < data.Length; i += 8) { var entry = data[i..]; int hash = ReadInt32LittleEndian(entry); var restrict = ReadInt32LittleEndian(entry[4..]); dict.Add(hash, (MysteryGiftRestriction)restrict); } return dict; } public static CheckResult VerifyGift(PKM pk, MysteryGift g) { bool restricted = TryGetRestriction(g, out var value); if (!restricted) return CheckResult.GetValid(CheckIdentifier.GameOrigin); var version = (int)value >> 16; if (version != 0 && !CanVersionReceiveGift(g.Generation, version, pk.Version)) return CheckResult.Get(Severity.Invalid, CheckIdentifier.GameOrigin, EncGiftVersionNotDistributed); var lang = value & MysteryGiftRestriction.LangRestrict; if (lang != 0 && !lang.HasFlag((MysteryGiftRestriction) (1 << pk.Language))) return CheckResult.Get(Severity.Invalid, CheckIdentifier.GameOrigin, OTLanguageShouldBe_0, (ushort)lang.GetSuggestedLanguage()); if (pk is IRegionOriginReadOnly tr) { var region = value & MysteryGiftRestriction.RegionRestrict; if (region != 0 && !region.HasFlag((MysteryGiftRestriction)((int)MysteryGiftRestriction.RegionBase << tr.ConsoleRegion))) return CheckResult.Get(Severity.Invalid, CheckIdentifier.GameOrigin, EncGiftRegionNotDistributed, (ushort)region.GetSuggestedRegion()); } return CheckResult.GetValid(CheckIdentifier.GameOrigin); } private static bool TryGetRestriction(MysteryGift g, out MysteryGiftRestriction val) { var restrict = RestrictionSet[g.Generation]; if (restrict is not null) return restrict.TryGetValue(g.GetHashCode(), out val); val = MysteryGiftRestriction.None; return false; } public static bool IsValidChangedOTName(PKM pk, MysteryGift g) { bool restricted = TryGetRestriction(g, out var val); if (!restricted) return false; // no data if (!val.HasFlag(MysteryGiftRestriction.OTReplacedOnTrade)) return false; Span<char> trainer = stackalloc char[pk.TrashCharCountTrainer]; int len = pk.LoadString(pk.OriginalTrainerTrash, trainer); trainer = trainer[..len]; return CurrentOTMatchesReplaced(g.Generation, trainer); } private static bool CanVersionReceiveGift(byte generation, int version4bit, GameVersion version) { return generation switch { _ => false, }; } private static bool CurrentOTMatchesReplaced(byte format, ReadOnlySpan<char> pkOtName) { if (format <= 4 && IsMatchName(pkOtName, 4)) return true; if (format <= 5 && IsMatchName(pkOtName, 5)) return true; if (format <= 6 && IsMatchName(pkOtName, 6)) return true; if (format <= 7 && IsMatchName(pkOtName, 7)) return true; return false; } private static bool IsMatchName(ReadOnlySpan<char> ot, byte generation) { return generation switch { _ => false, }; } }
0
0.911344
1
0.911344
game-dev
MEDIA
0.240018
game-dev
0.908236
1
0.908236
mob-sakai/SoftMaskForUGUI
4,421
Packages/src/Runtime/Internal/Utilities/UIExtraCallbacks.cs
using System; using UnityEditor; using UnityEngine; using UnityEngine.UI; using System.Reflection; namespace Coffee.UISoftMaskInternal { /// <summary> /// Provides additional callbacks related to canvas and UI system. /// </summary> internal static class UIExtraCallbacks { private static bool s_IsInitializedAfterCanvasRebuild; private static readonly FastAction s_AfterCanvasRebuildAction = new FastAction(); private static readonly FastAction s_LateAfterCanvasRebuildAction = new FastAction(); private static readonly FastAction s_BeforeCanvasRebuildAction = new FastAction(); private static readonly FastAction s_OnScreenSizeChangedAction = new FastAction(); private static Vector2Int s_LastScreenSize; static UIExtraCallbacks() { Canvas.willRenderCanvases += OnBeforeCanvasRebuild; Logging.LogMulticast(typeof(Canvas), "willRenderCanvases", message: "ctor"); } /// <summary> /// Event that occurs after canvas rebuilds. /// </summary> public static event Action onLateAfterCanvasRebuild { add => s_LateAfterCanvasRebuildAction.Add(value); remove => s_LateAfterCanvasRebuildAction.Remove(value); } /// <summary> /// Event that occurs before canvas rebuilds. /// </summary> public static event Action onBeforeCanvasRebuild { add => s_BeforeCanvasRebuildAction.Add(value); remove => s_BeforeCanvasRebuildAction.Remove(value); } /// <summary> /// Event that occurs after canvas rebuilds. /// </summary> public static event Action onAfterCanvasRebuild { add => s_AfterCanvasRebuildAction.Add(value); remove => s_AfterCanvasRebuildAction.Remove(value); } /// <summary> /// Event that occurs when the screen size changes. /// </summary> public static event Action onScreenSizeChanged { add => s_OnScreenSizeChangedAction.Add(value); remove => s_OnScreenSizeChangedAction.Remove(value); } /// <summary> /// Initializes the UIExtraCallbacks to ensure proper event handling. /// </summary> private static void InitializeAfterCanvasRebuild() { if (s_IsInitializedAfterCanvasRebuild) return; s_IsInitializedAfterCanvasRebuild = true; // Explicitly set `Canvas.willRenderCanvases += CanvasUpdateRegistry.PerformUpdate`. CanvasUpdateRegistry.IsRebuildingLayout(); #if TMP_ENABLE // Explicitly set `Canvas.willRenderCanvases += TMP_UpdateManager.DoRebuilds`. typeof(TMPro.TMP_UpdateManager) .GetProperty("instance", BindingFlags.NonPublic | BindingFlags.Static) .GetValue(null); #endif Canvas.willRenderCanvases -= OnAfterCanvasRebuild; Canvas.willRenderCanvases += OnAfterCanvasRebuild; Logging.LogMulticast(typeof(Canvas), "willRenderCanvases", message: "InitializeAfterCanvasRebuild"); } #if UNITY_EDITOR [InitializeOnLoadMethod] #endif [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] private static void InitializeOnLoad() { Canvas.willRenderCanvases -= OnAfterCanvasRebuild; s_IsInitializedAfterCanvasRebuild = false; } /// <summary> /// Callback method called before canvas rebuilds. /// </summary> private static void OnBeforeCanvasRebuild() { var screenSize = new Vector2Int(Screen.width, Screen.height); if (s_LastScreenSize != screenSize) { if (s_LastScreenSize != default) { s_OnScreenSizeChangedAction.Invoke(); } s_LastScreenSize = screenSize; } s_BeforeCanvasRebuildAction.Invoke(); InitializeAfterCanvasRebuild(); } /// <summary> /// Callback method called after canvas rebuilds. /// </summary> private static void OnAfterCanvasRebuild() { s_AfterCanvasRebuildAction.Invoke(); s_LateAfterCanvasRebuildAction.Invoke(); } } }
0
0.790353
1
0.790353
game-dev
MEDIA
0.521402
game-dev
0.923799
1
0.923799
Razcoina/Bully-SE-scripts
43,289
scripts/chap4/4_02.lua
local gThad, gCorn, gFatty, gBeatriceWave1, gThadWave1 local bWindowSpawners = false local bSpawnersActive = false local numFatty = 0 local numCorny = 0 local numThad = 0 local numMelvin = 0 local bFluxLinePlayed = false local gBlipAlgie local bMissionSuccess = false local bWave3Dead = false local bFattyTalks = false local bCodeGiven = false local bEarnestLockedTheDoor = false local bBreakerAlive = true local bSpudLinePlayed = false local tblCoverProps = {} local bCoverPropsSet = false local bDoorDead = false local nerd_spawner1, nerd_spawner2, nerd_spawner3, nerd_spawner4, nerd_spawner5, nerd_spawner6 local bThadCreate = false local gCannonNerd local bOnCannon = false local gBlipObs, gBlipTransformer, gBlipCannon local bCannonBlipped = false local gBlipObs2 local mission_won = false local mis_obj01 = 0 local mis_obj02 = 0 local mis_obj03 = 0 local mis_obj04 = 0 local mis_obj05 = 0 local mis_obj06 = 0 local mis_obj07 = 0 local mis_obj08 = 0 local bCreateThad = false local bShortCut = false local social_time = 0 local gBlipNerds01 local bDoorLineDone = false local bNerdsHit = false local bPlayerGreets = false local gMelvin, gFattyBlip, gFattyBlip, gBlipThad local bPlayerGreetsFatty = false local bSecDoorIsThere = false local gWindowsStage = 1 local gThadSaysNoWay = false local bPlayerIsAsking = false local bPlayerIsTaunting = false local bFattyBeingCanned = false local bFattyInTheCan = false local bPointOfNoReturn = false local bEndCut = false local bOnSpudCannon = false local bOnCannon = false local bPlayerOffCannon = false local bWave04Engaged = false local bWave04Launched = false local bWave03Engaged = false local bWave03Launched = false local bWave02Engaged = false local bWave02Launched = false local bEnterGauntlet = false local bWave01Engaged = false local bGotTheCode = false local bGotInfo = false local bThadCreated = false local bHitCorn = false local bHitFatty = false local bHitMelvin = false local bFattyGrappled = false local bPlayerAttackDoors = false local bSuperThad = false local bMisobjDoor = false local gSpawned01 = -1 local gSpawned02 = -1 local gSpawned03 = -1 local gSpawned04 = -1 local gSpawned05 = -1 local gSpawned06 = -1 local bSetMove01 = false local bSetMove02 = false local bSetMove03 = false local bSetMove04 = false local bSetMove05 = false local bSetMove06 = false local bHasMoved01 = false local bHasMoved02 = false local bHasMoved03 = false local bHasMoved04 = false local bHasMoved05 = false local bHasMoved06 = false function MissionSetup() MissionDontFadeIn() PlayCutsceneWithLoad("4-02", true, true, true) DATLoad("4_02.DAT", 2) DATInit() AreaTransitionPoint(0, POINTLIST._4_02_PLAYERSTART, nil, true) end function F_MissionSetup() DisablePOI() LoadAnimationGroup("F_NERDS") LoadAnimationGroup("IDLE_NERD_C") LoadActionTree("Act/Conv/4_02.act") LoadPedModels({ 9, 5, 6, 8, 7, 11, 4, 10 }) LoadWeaponModels({ 303, 307, 301, 309 }) numFatty = PedGetUniqueModelStatus(5) PedSetUniqueModelStatus(5, -1) numCorny = PedGetUniqueModelStatus(9) PedSetUniqueModelStatus(9, -1) numThad = PedGetUniqueModelStatus(7) PedSetUniqueModelStatus(7, -1) numMelvin = PedGetUniqueModelStatus(6) PedSetUniqueModelStatus(6, -1) end function main() MissionDontFadeIn() F_MissionSetup() DisablePOI() F_PropSet() PlayerSetControl(1) CameraReturnToPlayer() CreateThread("T_PlayerAsks") CreateThread("T_FattyScared") CameraFade(1000, 1) F_GetInfo() F_GetKeyCode() F_Wave01() F_Wave02() F_Wave03() F_Wave04() F_GetOnSpudCannon() F_DestroyDoors() F_GetInObservatory() if bMissionSuccess then PlayerSetControl(0) CameraLookAtObject(gPlayer, 3, true, 1) CameraSetWidescreen(true) F_MakePlayerSafeForNIS(true) SoundDisableSpeech_ActionTree() PedMoveToPoint(gPlayer, 1, POINTLIST._4_02_OBSERVATORY) CameraFade(500, 1) AreaClearAllPeds() Wait(501) MinigameSetCompletion("M_PASS", true, 0) MinigameAddCompletionMsg("MRESPECT_JP5", 2) MinigameAddCompletionMsg("MRESPECT_NM100", 1) SoundPlayMissionEndMusic(true, 10) while MinigameIsShowingCompletion() do Wait(0) end mission_won = true SetFactionRespect(1, 0) SetFactionRespect(2, 50) F_MakePlayerSafeForNIS(false) PlayerSetControl(1) MissionSucceed(true, false, false) else SoundPlayMissionEndMusic(false, 10) MissionFail() end end function F_PropSet() tblCoverProps = { { trigger = TRIGGER._4_02_BAR_01, id = 0 }, { trigger = TRIGGER._4_02_BAR_02, id = 0 }, { trigger = TRIGGER._4_02_BAR_03, id = 0 } } for i, prop in tblCoverProps do while not PAnimRequest(prop.trigger) do Wait(0) end end for i, prop in tblCoverProps do prop.id = PAnimCreate(prop.trigger) end end function F_GetInObservatory() while MissionActive() do bMissionSuccess = true PlayerSetControl(0) CameraFade(1000, 0) Wait(1000) PedSetActionNode(gPlayer, "/Global/WPCANNON/Disengage", "Act/Props/WPCANNON.act") Wait(250) PlayerSetPosPoint(POINTLIST._4_02_PLAYERENDCUT) F_DeleteWindowsNerds() Wait(250) Wait(0) CameraSetXYZ(43.559174, -140.24785, 3.387123, 43.75394, -139.2694, 3.454439) break end end function F_DestroyDoors() while not (not MissionActive() or bDoorDead) do if not bPlayerOffCannon and not F_PlayerOnSpudCannon() then --print("=== Off the Cannon ===") gBlipCannon = BlipAddPoint(POINTLIST._4_02_SPUD_NERD01, 0) bPlayerOffCannon = true PAnimSetInvulnerable(TRIGGER._DT_OBSERVATORY, true) PAnimMakeTargetable(TRIGGER._DT_OBSERVATORY, false) elseif bPlayerOffCannon and F_PlayerOnSpudCannon() then --print("=== On the Cannon ===") BlipRemove(gBlipCannon) bPlayerOffCannon = false PAnimSetInvulnerable(TRIGGER._DT_OBSERVATORY, false) PAnimMakeTargetable(TRIGGER._DT_OBSERVATORY, true) end if bSetMove01 then bSetMove01 = false end if bSetMove02 then bSetMove02 = false end if bSetMove03 then bSetMove03 = false end if bSetMove04 then bSetMove04 = false end if bSetMove05 then --print("===== gSpawned05 should be walking to attack point ====") PedMoveToPoint(gSpawned05, 0, POINTLIST._4_02_O_R1_2, 1, cbSpawner5, 0.2) bSetMove05 = false end if bSetMove06 then --print("===== gSpawned06 should be walking to attack point ====") PedMoveToPoint(gSpawned06, 0, POINTLIST._4_02_O_R2_2, 1, cbSpawner6, 0.2) bSetMove06 = false end if bHasMoved01 then PedStop(gSpawned01) PedSetStationary(gSpawned01, true) PedAttackPlayer(gSpawned01, 3) bHasMoved01 = false end if bHasMoved02 then PedStop(gSpawned02) PedSetStationary(gSpawned02, true) PedAttackPlayer(gSpawned02, 3) bHasMoved02 = false end Wait(0) if bHasMoved03 then PedStop(gSpawned03) PedSetStationary(gSpawned03, true) PedAttackPlayer(gSpawned03, 3) bHasMoved03 = false end if bHasMoved04 then PedStop(gSpawned04) PedSetStationary(gSpawned04, true) PedAttackPlayer(gSpawned04, 3) bHasMoved04 = false end if bHasMoved05 then PedStop(gSpawned05) PedSetStationary(gSpawned05, true) PedAttackPlayer(gSpawned05, 3) bHasMoved05 = false end if bHasMoved06 then PedStop(gSpawned06) PedSetStationary(gSpawned06, true) PedAttackPlayer(gSpawned06, 3) bHasMoved06 = false end end --print("=== Door Dead ===") end function F_RunEarnestNIS() F_MakePlayerSafeForNIS(true) CameraFade(500, 0) Wait(501) PedStop(gCannonNerd) PedSetPosPoint(gCannonNerd, POINTLIST._4_02_NIS_EARNEST, 1) PedSetActionNode(gCannonNerd, "/Global/4_02/NIS/Earnest_01", "Act/Conv/4_02.act") PedSetEffectedByGravity(gCannonNerd, true) CameraSetWidescreen(true) CameraSetFOV(80) CameraSetPath(PATH._4_02_NIS_CAM, true) CameraSetSpeed(0.5, 1, 0.5) CameraLookAtPath(PATH._4_02_NIS_CAM_LOOK, true) PlayerSetControl(0) CameraFade(500, 1) Wait(501) PedSetActionNode(gCannonNerd, "/Global/4_02/Blank", "Act/Conv/4_02.act") PedFollowPath(gCannonNerd, PATH._4_02_NIS_EARNESTRUN, 0, 2) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 36) Wait(5500) CameraFade(500, 0) Wait(501) LoadActionTree("Act/Props/scObsDr.act") CameraDefaultFOV() CameraSetWidescreen(false) CameraReturnToPlayer(true) F_MakePlayerSafeForNIS(false) PedDelete(gCannonNerd) PlayerSetControl(1) CameraFade(500, 1) Wait(501) AreaSetDoorLocked(TRIGGER._SCGATE_OBSERVATORY, false) AreaSetDoorLockedToPeds(TRIGGER._SCGATE_OBSERVATORY, false) PAnimOpenDoor(TRIGGER._SCGATE_OBSERVATORY) MissionObjectiveComplete(mis_obj05) BlipRemove(gBlipTransformer) TextPrint("4_02_GCANNON", 4, 1) mis_obj06 = MissionObjectiveAdd("4_02_GCANNON") gBlipCannon = BlipAddPoint(POINTLIST._4_02_SPUD_NERD01, 0) end function F_GetOnSpudCannon() while not (not MissionActive() or bOnSpudCannon) do if not bOnCannon and F_PlayerOnCannon() then --print("=== On the Cannon ===") F_PlayerOnCannonAction() bOnCannon = true bOnSpudCannon = true end Wait(0) end --print("==== F_GetOnSpudCannon dead ===") end function F_Wave04() while not (not MissionActive() or bWave04Engaged) do if not bWave04Launched and F_ApproachWave04() then F_Wave4() bWave04Launched = true bWave04Engaged = true end Wait(0) end end function F_Wave03() while not (not MissionActive() or bWave03Engaged) do if not bWave03Launched and F_ApproachWave03() then F_Wave3() bWave03Launched = true bWave03Engaged = true end Wait(0) end end function F_Wave02() while not (not MissionActive() or bWave02Engaged) do if not bWave02Launched and F_ApproachWave02() then F_Wave2() bWave02Launched = true bWave02Engaged = true end Wait(0) end end function F_Wave01() while not (not MissionActive() or bWave01Engaged) do if not bEnterGauntlet and F_EnteringGauntlet() then F_EnteringGauntletAction() bEnterGauntlet = true bWave01Engaged = true end Wait(0) end end function F_GetKeyCode() SoundDisableSpeech_ActionTree() while not (not MissionActive() or bKeyCodeGiven) do if not bGotTheCode and F_ThadSubmitts() then F_ThadCode() bGotTheCode = true bKeyCodeGiven = true end Wait(0) end end function F_GetInfo() F_SetupLibraryNerds() F_CreateDoorAndPad() TextPrint("4_02_NERDS", 5, 1) mis_obj01 = MissionObjectiveAdd("4_02_NERDS") while not (not MissionActive() or bGotInfo) do if not bCreateThad and (PlayerIsInTrigger(TRIGGER._4_02_GATEKEEPER) or PedGetWhoHitMeLast(gThad) == gPlayer) then --print("=== Not Hit Fatty ====") BlipRemove(gBlipNerds01) BlipRemoveFromChar(gFatty) MissionObjectiveRemove(mis_obj01) PedSetPedToTypeAttitude(gThad, 13, 0) BlipRemoveFromChar(gThad) gBlipThad = AddBlipForChar(gThad, 1, 26, 4) if not gThadSaysNoWay then gThadSaysNoWay = true SoundPlayScriptedSpeechEvent(gThad, "M_4_02", 13, "genric", false, true) while SoundSpeechPlaying(gThad) do Wait(0) end PedSetMinHealth(gThad, 0) end bPlayerGreets = false bNerdsHit = false bShortCut = true bCreateThad = true if mis_obj03 == 0 then mis_obj03 = MissionObjectiveAdd("4_02_KEYCODE") TextPrint("4_02_KEYCODE", 4, 1) end PedClearObjectives(gFatty) PedClearObjectives(gCorn) PedMakeAmbient(gFatty) PedMakeAmbient(gCorn) PedWander(gFatty, 0) PedWander(gCorn, 0) gFatty = 0 bGotInfo = true break end if not gThadSaysNoWay and bCreateThad and (PlayerIsInTrigger(TRIGGER._4_02_GATEKEEPER) or PedGetWhoHitMeLast(gThad) == gPlayer) then --print("=== Hit Fatty ====") PedSetPedToTypeAttitude(gThad, 13, 0) BlipRemoveFromChar(gThad) gBlipThad = AddBlipForChar(gThad, 1, 26, 4) if not gThadSaysNoWay then gThadSaysNoWay = true SoundPlayScriptedSpeechEvent(gThad, "M_4_02", 13, "genric", false, true) while SoundSpeechPlaying(gThad) do Wait(0) end end PedSetMinHealth(gThad, 0) if not bShortCut or mis_obj02 ~= 0 then MissionObjectiveComplete(mis_obj02) end if mis_obj03 == 0 then mis_obj03 = MissionObjectiveAdd("4_02_KEYCODE") TextPrint("4_02_KEYCODE", 4, 1) end gFatty = 0 gThadSaysNoWay = true bGotInfo = true break end if not bThadCreated and F_CreateThad() then F_CreateThadAction() bThadCreated = true end if not bHitCorn and F_HittingCorn() then F_HitCorn() bHitCorn = true end if not bHitFatty and F_HittingFatty() then F_HitFatty() bHitFatty = true end Wait(0) end end function F_SetupLibraryNerds() social_time = 1 gCorn = PedCreatePoint(9, POINTLIST._4_02_LIBCORNY) gFatty = PedCreatePoint(5, POINTLIST._4_02_LIBFATTY) gFattyBlip = AddBlipForChar(gFatty, 1, 0, 4) PedSetPedToTypeAttitude(gCorn, 13, 2) PedSetPedToTypeAttitude(gFatty, 13, 2) PedSocialOverrideLoad(7, "Mission/4_02_Taunt.act") PedSocialOverrideLoad(18, "Mission/4_02_Greeting.act") PedOverrideSocialResponseToStimulus(gFatty, 55, 7) PedOverrideSocialResponseToStimulus(gFatty, 10, 18) PedOverrideSocialResponseToStimulus(gFatty, 9, 7) PlayerSocialDisableActionAgainstPed(gFatty, 27, true) PedUseSocialOverride(gFatty, 7, true) PedUseSocialOverride(gFatty, 18, true) PlayerRegisterSocialCallbackVsPed(gFatty, 35, F_Player_Greets_1) PlayerRegisterSocialCallbackVsPed(gFatty, 28, F_Player_Greets_2) PlayerRegisterSocialCallbackVsPed(gCorn, 35, F_Player_Greets_1) PlayerRegisterSocialCallbackVsPed(gCorn, 28, F_Player_Greets_2) end function F_Player_Greets_1() bPlayerGreets = true bPlayerIsAsking = true if not bFattyTalks then SoundPlayScriptedSpeechEvent(gPlayer, "M_4_02", 1, "genric", false, false) bFattyTalks = true end bPlayerGreetsFatty = true end function F_Player_Greets_2() bPlayerGreets = true bPlayerIsAsking = true if not bFattyTalks then SoundPlayScriptedSpeechEvent(gPlayer, "M_4_02", 6, "genric", false, false) bFattyTalks = true end bPlayerGreetsFatty = true end function F_Social_Greet_Fatty() if not bFattyTalks then SoundPlayScriptedSpeechEvent(gFatty, "M_4_02", 2, "genric", false, false) end PlayerSocialDisableActionAgainstPed(gFatty, 35, true) bPlayerGreetsFatty = true end function F_Social_Taunt_Fatty() if social_time == 1 then social_time = 0 bPlayerIsAsking = true PlayerSocialDisableActionAgainstPed(gFatty, 28, true) end end function T_PlayerAsks() while not (not MissionActive() or bFattyInTheCan) do if bNerdsHit then if bFattyBeingCanned then break end local health = PedGetHealth(gFatty) if PedGetLastHitWeapon(gFatty) == 301 or PedGetLastHitWeapon(gFatty) == 308 then break end SoundPlayScriptedSpeechEvent(gFatty, "M_4_02", 26, "genric", false, false) PedSetTypeToTypeAttitude(1, 13, 0) BlipRemove(gBlipNerds01) BlipRemoveFromChar(gFatty) gFattyBlip = AddBlipForChar(gFatty, 1, 26, 4) PedOverrideStat(gCorn, 14, 10) PedOverrideStat(gCorn, 6, 100) PedOverrideStat(gCorn, 7, 100) PedFlee(gCorn, gPlayer) PedAttack(gFatty, gPlayer, 3) PedOverrideStat(gFatty, 0, 362) PedOverrideStat(gFatty, 1, 100) bNerdsHit = false break end if bPlayerIsAsking then bFattyTalks = true while SoundSpeechPlaying(gPlayer) do if PedIsPlaying(gFatty, "/Global/Actions/Grapples/Front/Grapples/Hold_Idle/RCV", true) then bFattyGrappled = true end if bFattyBeingCanned or bFattyGrappled then break end Wait(0) end Wait(100) if bFattyBeingCanned or bFattyGrappled then break end if not bFattyGrappled and not bFattyBeingCanned then SoundPlayScriptedSpeechEvent(gFatty, "M_4_02", 2, "genric", false, true) end PedSetTypeToTypeAttitude(1, 13, 0) BlipRemove(gBlipNerds01) BlipRemoveFromChar(gFatty) gFattyBlip = AddBlipForChar(gFatty, 1, 26, 4) PedOverrideStat(gCorn, 14, 10) PedOverrideStat(gCorn, 6, 100) PedOverrideStat(gCorn, 7, 100) PedFlee(gCorn, gPlayer) PedAttack(gFatty, gPlayer, 3) PedOverrideStat(gFatty, 0, 362) PedOverrideStat(gFatty, 1, 100) break end Wait(0) end --print(" ===== T_PlayerAsks dead =====") collectgarbage() end function F_HittingCorn() if PedGetWhoHitMeLast(gCorn) == gPlayer or bNerdsHit then return true else return false end end function F_HitCorn() bNerdsHit = true end function F_HittingFatty() if PedGetWhoHitMeLast(gFatty) == gPlayer or bNerdsHit then return true else return false end end function F_HitFatty() bNerdsHit = true end function F_HittingMelvin() if PedGetWhoHitMeLast(gMelvin) == gPlayer or bNerdsHit then return true else return false end end function F_HitMelvin() bNerdsHit = true end function T_FattyScared() while not (not (MissionActive() and PedIsValid(gFatty)) or bPointOfNoReturn) do if PedIsPlaying(gFatty, "/Global/Garbagecan/PedPropsActions/StuffGrap/RCV", true) then bFattyBeingCanned = true end if PedIsPlaying(gFatty, "/Global/Garbagecan/PedPropsActions/StuffGrap/RCV/InCan/die", true) then bFattyInTheCan = true end if PedIsPlaying(gFatty, "/Global/Actions/Grapples/Front/Grapples/Hold_Idle/RCV", true) then bFattyGrappled = true end if PedGetHealth(gFatty) <= 25 or bFattyInTheCan then BlipRemoveFromChar(gFatty) BlipRemove(gBlipNerds01) PedLockTarget(gCorn, gPlayer, -1) PedClearObjectives(gCorn) PedMakeAmbient(gCorn) PedFlee(gCorn, gPlayer) F_MakePlayerSafeForNIS(true, true) PlayerSetControl(0) CameraSetWidescreen(true) PedFaceObject(gPlayer, gFatty, 2, 1, true) bFattyTalks = true PedClearObjectives(gFatty) PedIgnoreStimuli(gFatty, true) PedSetInvulnerableToPlayer(gFatty, true) --print("===== bFattyInTheCan? ====", tostring(bFattyInTheCan)) if not bFattyInTheCan and not bFattyGrappled then PedSetActionNode(gFatty, "/Global/4_02/AlgieCower/Cower_Start", "Act/Conv/4_02.act") end SoundPlayScriptedSpeechEvent(gFatty, "M_4_02", 12, "genric", false, false) while SoundSpeechPlaying(gFatty) do Wait(0) end PlayerSetControl(1) CameraSetWidescreen(false) F_MakePlayerSafeForNIS(false, true) bCreateThad = true MissionObjectiveComplete(mis_obj01) mis_obj02 = MissionObjectiveAdd("4_02_SECDOOR") TextPrint("4_02_SECDOOR", 5, 1) if not bFattyInTheCan then PedSetInvulnerableToPlayer(gFatty, false) PedIgnoreStimuli(gFatty, false) PedSetActionNode(gFatty, "/Global/N_Striker_A", "Act/Anim/N_Striker_A.act") PedMakeAmbient(gFatty) PedClearObjectives(gFatty) PedFlee(gFatty, gPlayer) end break end Wait(0) end --print(" ===== T_FattyScared dead =====") collectgarbage() end function F_CreateThad() return bCreateThad end function F_CreateThadAction() if not bShortCut then bPlayerGreets = false bNerdsHit = false gBlipThad = AddBlipForChar(gThad, 1, 0, 4) end end function F_Player_Greets_3() bPlayerGreets = true if not bFattyTalks then SoundPlayScriptedSpeechEvent(gPlayer, "M_4_02", 3, "genric", false, false) end end function F_Social_Greet_Thad() if bPlayerGreets then end SoundPlayScriptedSpeechEvent(gThad, "M_4_02", 15, "genric", false, false) PlayerSocialDisableActionAgainstPed(gThad, 35, true) end function F_Social_Taunt_Thad() if not gThadSaysNoWay then gThadSaysNoWay = true SoundPlayScriptedSpeechEvent(gThad, "M_4_02", 13, "genric", false, true) end BlipRemove(gBlipAlgie) BlipRemoveFromChar(gFatty) PedSetTypeToTypeAttitude(1, 13, 0) BlipRemoveFromChar(gThad) gBlipThad = AddBlipForChar(gThad, 0, 26) PedAttack(gThad, gPlayer, 3) end function F_ThadHit() return bThadCreate and PedGetWhoHitMeLast(gThad) == gPlayer and not bNerdsHit and not bPlayerGreets end function F_ThadHitAction() bNerdsHit = true F_Social_Taunt_Thad() end function F_ThadSubmitts() return bThadCreate and PedGetHealth(gThad) <= 45 end function F_ThadCode() PedSetTypeToTypeAttitude(1, 13, 2) PedSetInvulnerableToPlayer(gThad, true) if PedGetGrappleTargetPed(gPlayer) == -1 then PedSetActionNode(gThad, "/Global/4_02/AlgieCower/Cower_Start", "Act/Conv/4_02.act") end bCodeGiven = true BlipRemoveFromChar(gThad) SoundPlayScriptedSpeechEvent(gThad, "M_4_02", 17, "genric", false, true) while SoundSpeechPlaying(gThad) do Wait(0) end PedClearObjectives(gThad) PedIgnoreStimuli(gThad, true) PedMakeTargetable(gThad, false) PedOverrideStat(gThad, 14, 10) PedOverrideStat(gThad, 6, 100) PedOverrideStat(gThad, 7, 100) mis_objDoor = MissionObjectiveAdd("4_02_OPENDOOR") bMisobjDoor = true SoundDisableSpeech_ActionTree() if PedGetGrappleTargetPed(gPlayer) == -1 then PedSetActionNode(gThad, "/Global/4_02/Break/BreakNode", "Act/Conv/4_02.act") end PedSetMinHealth(gThad, 0) PedSetInvulnerableToPlayer(gThad, false) PedIgnoreStimuli(gThad, false) PedMakeTargetable(gThad, true) PedMakeAmbient(gThad) PedMoveToPoint(gThad, 1, POINTLIST._4_02_PLAYERSTART, 1, nil, 0.3, false, true) bCoverPropsSet = true TextPrint("4_02_OPENDOOR", 5, 1) door_blip = BlipAddPoint(POINTLIST._4_02_SECDOORBLIP, 0) SoundPlayAmbientSpeechEvent(gThad, "SCARED") MissionObjectiveComplete(mis_obj03) end function F_CreateDoorAndPad() PedSetTypeToTypeAttitude(1, 13, 0) gThad = PedCreatePoint(7, POINTLIST._4_02_GATEKEEPER) local health = PedGetHealth(gThad) PedSetMinHealth(gThad, health) PedSetPedToTypeAttitude(gThad, 13, 2) bThadCreate = true PedOverrideSocialResponseToStimulus(gThad, 10, 18) PedOverrideSocialResponseToStimulus(gThad, 55, 7) PedOverrideSocialResponseToStimulus(gThad, 9, 7) PlayerSocialDisableActionAgainstPed(gThad, 27, true) PedUseSocialOverride(gThad, 7, true) PedUseSocialOverride(gThad, 18, true) PlayerRegisterSocialCallbackVsPed(gThad, 35, F_Player_Greets_3) PlayerRegisterSocialCallbackVsPed(gThad, 28, F_Player_Greets_3) AreaSetDoorLockedToPeds(TRIGGER._NERDPATH_BRDOOR, true) bSecDoorIsThere = true end function F_OpenDoors() if bCodeGiven then AreaSetDoorLocked(TRIGGER._NERDPATH_BRDOOR, false) PAnimOpenDoor(TRIGGER._NERDPATH_BRDOOR) bDoorLineDone = false if mis_obj04 == 0 then if bMisobjDoor then MissionObjectiveComplete(mis_objDoor) bMisobjDoor = false end mis_obj04 = MissionObjectiveAdd("4_02_GO_OBS") TextPrint("4_02_GO_OBS", 5, 1) BlipRemove(door_blip) gBlipObs = BlipAddPoint(POINTLIST._4_02_OBSERVATORY, 0) end elseif not bEarnestLockedTheDoor then TextPrint("4_02_CODE", 5, 1) end end function F_CloseDoors() PAnimCloseDoor(TRIGGER._NERDPATH_BRDOOR) if bCodeGiven then end end function F_EnteringGauntlet() if AreaGetVisible() ~= 0 then bCodeGiven = true end return PlayerIsInTrigger(TRIGGER._4_02_SPOTTED_SCOUT) end function F_EnteringGauntletAction() F_SetUpEnemies1() F_SetUpWave(tblNerd01) bCodeGiven = false bEarnestLockedTheDoor = true PAnimCloseDoor(TRIGGER._NERDPATH_BRDOOR) AreaSetDoorLocked(TRIGGER._NERDPATH_BRDOOR, true) bPointOfNoReturn = true PickupRemoveAll() SoundPlayInteractiveStreamLocked("MS_ActionHigh.rsm", MUSIC_DEFAULT_VOLUME) Wait(3000) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 19) PedSetTypeToTypeAttitude(1, 13, 0) PAnimSetInvulnerable(TRIGGER._4_02_BAR_01, true) PAnimMakeTargetable(TRIGGER._4_02_BAR_01, false) PAnimSetInvulnerable(TRIGGER._4_02_BAR_02, true) PAnimMakeTargetable(TRIGGER._4_02_BAR_02, false) end function F_ApproachWave02() return PlayerIsInTrigger(TRIGGER._4_02_P_WAVE2) end function F_Wave2() F_SetUpEnemies2() F_SetUpWave(tblNerd02) Wait(50) PickupCreatePoint(301, POINTLIST._4_02_ISLANDPICKUP, 1, 0, "MissionPermanent") Wait(5000) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 21) end function F_Delete_Wave1_1() return PlayerIsInTrigger(TRIGGER._4_02_DELETE_WAVE1) end function F_Delete_Wave1_2() for n, nerd in tblNerd01 do if PedIsValid(nerd.id) then PedDelete(nerd.id) end end end function F_ApproachWave03() return PlayerIsInTrigger(TRIGGER._4_02_P_WAVE3) end function F_Wave3() F_SetUpEnemies3() F_SetUpWave(tblNerd03) PAnimSetInvulnerable(TRIGGER._4_02_BAR_03, true) PAnimMakeTargetable(TRIGGER._4_02_BAR_03, false) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 21) end function F_ApproachWave04() return PlayerIsInTrigger(TRIGGER._4_02_P_WAVE4) end function F_Wave4() F_MakePlayerSafeForNIS(true, true) CameraSetWidescreen(true) PlayerSetControl(0) for n, nerd in tblNerd02 do if PedIsValid(nerd.id) then PedDelete(nerd.id) end end for n, nerd in tblNerd03 do if PedIsValid(nerd.id) then PedDelete(nerd.id) end end AreaSetDoorLocked(TRIGGER._SCGATE_OBSERVATORY, true) AreaSetDoorLockedToPeds(TRIGGER._SCGATE_OBSERVATORY, true) PAnimSetInvulnerable(TRIGGER._DT_OBSERVATORY, true) Wait(0) while not PAnimRequest(TRIGGER._4_02_OBSDOOR) do Wait(0) end PAnimCreate(TRIGGER._4_02_OBSDOOR) gCannonNerd = PedCreatePoint(10, POINTLIST._4_02_SPUD_NERD01) PedSetEffectedByGravity(gCannonNerd, false) Wait(50) PedDestroyWeapon(gCannonNerd, 299) PedClearAllWeapons(gCannonNerd) PedClearObjectives(gCannonNerd) PedOverrideStat(gCannonNerd, 3, 80) Wait(50) BlipRemove(gBlipObs) gBlipTransformer = BlipAddPoint(POINTLIST._4_02_FUSE_POINT, 26, 0, 4) PedStop(gPlayer) Wait(1000) while not PedIsPlaying(gCannonNerd, "/Global/Ambient/MissionSpec/GetOnCannon", true) do PedSetActionNode(gCannonNerd, "/Global/Ambient/MissionSpec/GetOnCannon", "Act/Anim/Ambient.act") Wait(0) end PedLockTarget(gCannonNerd, gPlayer, 3) SoundSetAudioFocusCamera() CameraLookAtObject(gCannonNerd, 2, true) CameraSetPath(PATH._4_02_CANNON_PATH, true) CameraSetSpeed(15, 5, 30) Wait(1500) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 21) Wait(6000) PedSetTaskNode(gCannonNerd, "/Global/AI/GeneralObjectives/SpecificObjectives/UseSpudCannon/PreFireWait/Fire", "Act/AI/AI.act") Wait(2000) PedLockTarget(gCannonNerd, -1) PedClearObjectives(gCannonNerd) PedSetActionTree(gCannonNerd, "/Global/N_Ranged_A", "Act/Anim/N_Ranged_A.act") PedIgnoreStimuli(gCannonNerd, true) bSpudLinePlayed = true local fx, fy, fz = GetPointList(POINTLIST._4_02_FUSE_POINT) CameraLookAtXYZ(fx, fy, fz, false) Wait(500) SoundPlayScriptedSpeechEvent_2D("M_4_02_2D", 31) Wait(3000) CameraSetWidescreen(false) F_MakePlayerSafeForNIS(false, true) PlayerSetControl(1) CameraReturnToPlayer() SoundSetAudioFocusPlayer() F_SetUpEnemies4() F_SetUpWave(tblNerd04) CreateThread("T_Breaker_Box") CreateThread("T_Delete_Wave3_2") MissionObjectiveComplete(mis_obj04) mis_obj05 = MissionObjectiveAdd("4_02_TRANS") TextPrint("4_02_TRANS", 5, 1) end function T_Delete_Wave3_2() while not (not MissionActive() or bWave3Dead) do if PlayerIsInTrigger(TRIGGER._4_02_DELETE_WAVE3) then bWave3Dead = true PedDelete(gCannonNerd) Wait(50) gCannonNerd = PedCreatePoint(10, POINTLIST._4_02_SPUD_NERD01) PedSetEffectedByGravity(gCannonNerd, false) Wait(50) PedDestroyWeapon(gCannonNerd, 299) PedClearAllWeapons(gCannonNerd) PedClearObjectives(gCannonNerd) AddBlipForChar(gCannonNerd, 2, 2, 1) PedOverrideStat(gCannonNerd, 3, 80) Wait(50) PedSetActionNode(gCannonNerd, "/Global/Ambient/MissionSpec/GetOnCannon", "Act/Anim/Ambient.act") PedLockTarget(gCannonNerd, gPlayer, 3) Wait(50) PedSetTaskNode(gCannonNerd, "/Global/AI/GeneralObjectives/SpecificObjectives/UseSpudCannon", "Act/AI/AI.act") bFluxLinePlayed = true end Wait(0) end Wait(0) collectgarbage() end function T_Breaker_Box() while MissionActive() and bBreakerAlive do local index_light, simplePool_light = PAnimGetPoolIndex("SC_ObservTrans", 33.1794, -130.376, 10.681, 1) if PAnimIsDestroyed(index_light, simplePool_light) then F_RunEarnestNIS() bBreakerAlive = false end Wait(0) end Wait(0) collectgarbage() end function cbCannonNerd() PedAttackPlayer(gCannonNerd, 3) end function F_PlayerOnSpudCannon() return PedIsPlaying(gPlayer, "/Global/WPCANNON/UseSpudCannon/In/In/Use/MasterSpawns", true) end function F_PlayerOnCannon() return PedIsPlaying(gPlayer, "/Global/WPCANNON/UseSpudCannon/In/In/Use/MasterSpawns", false) end function F_PlayerOnCannonAction() CreateThread("T_Door_Health") bOnCannon = true PAnimSetInvulnerable(TRIGGER._DT_OBSERVATORY, false) PAnimOverrideDamage(TRIGGER._DT_OBSERVATORY, 1200) PAnimShowHealthBar(TRIGGER._DT_OBSERVATORY, true, "4_02_OBSDOOR", true) PAnimMakeTargetable(TRIGGER._DT_OBSERVATORY, true) bPlayerAttackDoors = true MissionObjectiveComplete(mis_obj06) TextPrint("4_02_KILLDOORS", 4, 1) mis_obj07 = MissionObjectiveAdd("4_02_KILLDOORS") gBlipObsDoor = BlipAddPoint(POINTLIST._4_02_OBSDOORBLIP, 0) BlipRemove(gBlipCannon) F_SpawnerAttackPlayer5() F_SpawnerAttackPlayer6() CreateThread("T_Spawn_Window") Wait(500) end function T_Spawn_Window() while not (not MissionActive() or bDoorDead) do if gWindowsStage == 1 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) <= 0.75 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) >= 0.55 then F_SpawnerAttackPlayer4() F_SpawnerAttackPlayer3() gWindowsStage = 2 elseif gWindowsStage == 2 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) <= 0.5 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) >= 0.25 then F_SpawnerAttackPlayer2() F_SpawnerAttackPlayer1() gWindowsStage = 3 elseif gWindowsStage == 3 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) <= 0.2 and PAnimGetHealth(TRIGGER._DT_OBSERVATORY) >= 0 then if not PedIsValid(gSpawned05) then F_SpawnerAttackPlayer5() end if not PedIsValid(gSpawned06) then F_SpawnerAttackPlayer6() end if not PedIsValid(gSpawned04) then F_SpawnerAttackPlayer4() end if not PedIsValid(gSpawned03) then F_SpawnerAttackPlayer3() end gWindowsStage = 4 end Wait(0) end Wait(0) collectgarbage() --print("=== T_Spawn_Window Dead ===") end function T_Door_Health() while not (not MissionActive() or bDoorDead) do if PAnimIsDestroyed(TRIGGER._DT_OBSERVATORY) then while not PAnimRequest(TRIGGER._DT_OBSERVATORY) do Wait(0) end BlipRemove(gBlipObsDoor) bDoorDead = true PAnimHideHealthBar(TRIGGER._DT_OBSERVATORY) PAnimMakeTargetable(TRIGGER._DT_OBSERVATORY, false) PAnimSetActionNode(TRIGGER._DT_OBSERVATORY, "/Global/scObsDr/Functions/Open", "Act/Props/scObsDr.act") MissionObjectiveComplete(mis_obj07) BlipRemove(gBlipObs) bEndCut = true end Wait(0) end Wait(0) collectgarbage() end function F_CreateWindowSnipers(idPed, spudbool) PedClearObjectives(idPed) PedDestroyWeapon(idPed, 299) PedClearAllWeapons(idPed) if spudbool then PedSetWeapon(idPed, 307, 30) else PedSetWeapon(idPed, 307, 30) end PedLockTarget(idPed, gPlayer, 3) PedOverrideStat(idPed, 3, 50) PedOverrideStat(idPed, 11, 85) end function F_DeleteWindowsNerds() F_WindowNerdDelete(gSpawned01) F_WindowNerdDelete(gSpawned02) F_WindowNerdDelete(gSpawned03) F_WindowNerdDelete(gSpawned04) F_WindowNerdDelete(gSpawned05) F_WindowNerdDelete(gSpawned06) end function F_WindowNerdDelete(nerd) if PedIsValid(nerd) then PedDelete(nerd) end end function F_SpawnerAttackPlayer1(idPed, nerd_spawner1) gSpawned01 = PedCreatePoint(5, POINTLIST._4_02_O_WN4_2) F_CreateWindowSnipers(gSpawned01, false) bSetMove01 = true end function F_SpawnerAttackPlayer2(idPed, nerd_spawner2) gSpawned02 = PedCreatePoint(6, POINTLIST._4_02_O_WN2_2) F_CreateWindowSnipers(gSpawned02, true) bSetMove02 = true end function F_SpawnerAttackPlayer3(idPed, nerd_spawner3) gSpawned03 = PedCreatePoint(7, POINTLIST._4_02_O_WN3_2) F_CreateWindowSnipers(gSpawned03, false) bSetMove03 = true end function F_SpawnerAttackPlayer4(idPed, nerd_spawner4) gSpawned04 = PedCreatePoint(11, POINTLIST._4_02_O_WN1_2) F_CreateWindowSnipers(gSpawned04, true) bSetMove04 = true end function F_SpawnerAttackPlayer5(idPed, nerd_spawner5) gSpawned05 = PedCreatePoint(9, POINTLIST._4_02_O_R1_1) F_CreateWindowSnipers(gSpawned05, true) bSetMove05 = true end function F_SpawnerAttackPlayer6(idPed, nerd_spawner6) gSpawned06 = PedCreatePoint(8, POINTLIST._4_02_O_R2_1) F_CreateWindowSnipers(gSpawned06, false) bSetMove06 = true end function cbSpawner1() bHasMoved01 = true end function cbSpawner2() bHasMoved02 = true end function cbSpawner3() bHasMoved03 = true end function cbSpawner4() bHasMoved04 = true end function cbSpawner5() bHasMoved05 = true end function cbSpawner6() bHasMoved06 = true end function F_SetUpWave(tbl) for n, nerd in tbl do nerd.id = PedCreatePoint(nerd.model, nerd.point) if not nerd.bNoCover then PedDestroyWeapon(nerd.id, 299) PedClearAllWeapons(nerd.id) PedSetWeaponNow(nerd.id, nerd.p_weapon, nerd.ammo, false) end PedOverrideStat(nerd.id, 3, 80) PedOverrideStat(nerd.id, 0, 362) PedOverrideStat(nerd.id, 1, 100) PedSetFlag(nerd.id, 134, true) if not nerd.bNoCover then PedCoverSetFromProfile(nerd.id, nerd.target, nerd.cover, nerd.cover_file) end PedAttackPlayer(nerd.id, 3) end end function F_SetUpEnemies1() tblNerd01 = { { model = 6, point = POINTLIST._4_02_P_NERD01, target = gPlayer, cover = POINTLIST._4_02_P_NERD01, p_weapon = 301, ammo = 50, cover_file = "4_02_p1_1_cover" }, { model = 11, point = POINTLIST._4_02_P_NERD02, target = gPlayer, cover = POINTLIST._4_02_P_NERD02, p_weapon = 307, ammo = 50, cover_file = "4_02_p1_2_cover" }, { model = 7, point = POINTLIST._4_02_P_NERD05, target = gPlayer, cover = POINTLIST._4_02_P_NERD05, p_weapon = 307, ammo = 50, cover_file = "4_02_p1_5_cover" } } end function F_SetUpEnemies2() tblNerd02 = { { model = 11, point = POINTLIST._4_02_NERD_SCOUT2_01, target = gPlayer, cover = POINTLIST._4_02_NERD_SCOUT2_01, p_weapon = 307, ammo = 50, cover_file = "4_02_p2_scout_cover" }, { model = 8, point = POINTLIST._4_02_P2_NERD01, target = gPlayer, cover = POINTLIST._4_02_P2_NERD01, p_weapon = 309, ammo = 50, cover_file = "4_02_p1_1_cover" }, { model = 5, point = POINTLIST._4_02_P2_NERD02, target = gPlayer, cover = POINTLIST._4_02_P2_NERD02, p_weapon = 301, ammo = 50, cover_file = "4_02_p1_1_cover" }, { model = 9, point = POINTLIST._4_02_P2_NERD03, target = gPlayer, cover = POINTLIST._4_02_P2_NERD03, p_weapon = 307, ammo = 50, cover_file = "4_02_p1_scout_cover" } } end function F_SetUpEnemies3() tblNerd03 = { { model = 7, point = POINTLIST._4_02_P3_NERD_SCOUT1_01, target = gPlayer, cover = POINTLIST._4_02_P3_NERD_SCOUT1_02, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_scout1_cover", bNoCover = true }, { model = 8, point = POINTLIST._4_02_P3_NERD_SCOUT2_01, target = gPlayer, cover = POINTLIST._4_02_P3_NERD_SCOUT2_02, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_scout2_cover", bNoCover = true }, { model = 5, point = POINTLIST._4_02_P3_NERD01, target = gPlayer, cover = POINTLIST._4_02_P3_NERD01, p_weapon = 301, ammo = 50, cover_file = "4_02_p3_1_cover" }, { model = 9, point = POINTLIST._4_02_P3_NERD02, target = gPlayer, cover = POINTLIST._4_02_P3_NERD02, p_weapon = 307, ammo = 50, cover_file = "4_02_p2_scout_cover" }, { model = 11, point = POINTLIST._4_02_P3_NERD05, target = gPlayer, cover = POINTLIST._4_02_P3_NERD05, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_5_cover" }, { model = 6, point = POINTLIST._4_02_P3_NERD07, target = gPlayer, cover = POINTLIST._4_02_P3_NERD07, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_7_cover" } } end function F_SetUpEnemies4() tblNerd04 = { { model = 9, point = POINTLIST._4_02_P4_NERD02, target = gPlayer, cover = POINTLIST._4_02_P4_NERD02, p_weapon = 307, ammo = 50, cover_file = "4_02_p4_2_cover" }, { model = 8, point = POINTLIST._4_02_P4_NERD03, target = gPlayer, cover = POINTLIST._4_02_P4_NERD03, p_weapon = 301, ammo = 50, cover_file = "4_02_p3_1_cover" }, { model = 4, point = POINTLIST._4_02_P4_NERD05, target = gPlayer, cover = POINTLIST._4_02_P4_NERD05, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_1_cover" }, { model = 6, point = POINTLIST._4_02_P4_NERD06, target = gPlayer, cover = POINTLIST._4_02_P4_NERD06, p_weapon = 307, ammo = 50, cover_file = "4_02_p3_1_cover" } } end function F_FailMission() mission_completed = true Wait(3000) SoundPlayMissionEndMusic(false, 10) MissionFail() end function MissionCleanup() SoundStopInteractiveStream() PAnimHideHealthBar() PedSetUniqueModelStatus(5, numFatty) PedSetUniqueModelStatus(9, numCorny) PedSetUniqueModelStatus(7, numThad) PedSetUniqueModelStatus(6, numMelvin) BlipRemove(gBlipObs2) BlipRemove(gBlipObs) CameraReturnToPlayer() PAnimSetActionNode(TRIGGER._DT_OBSERVATORY, "/Global/scObsDr/Functions/Close", "/Act/Props/scObsDr.act") AreaSetDoorLocked(TRIGGER._SCGATE_OBSERVATORY, false) EnablePOI() CameraSetWidescreen(false) DATUnload(2) PlayerSetControl(1) UnLoadAnimationGroup("F_NERDS") UnLoadAnimationGroup("IDLE_NERD_C") end
0
0.815594
1
0.815594
game-dev
MEDIA
0.963766
game-dev
0.919453
1
0.919453
Moolt/LevelGenerator
2,274
Assets/Scripts/ProdecuralGeneration/Editor/ChunkTagsEditor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor (typeof(ChunkTags))] public class ChunkTagsEditor : Editor { private ChunkTags tags; private bool isShowUserTags = false; private bool isShowAutoTags = false; void OnEnable(){ tags = target as ChunkTags; } public override void OnInspectorGUI(){ SerializedObject serTagObj = new SerializedObject (tags); SerializedProperty serTagList = serTagObj.FindProperty ("userGenerated"); if (IsChunk) { EditorGUILayout.Space (); isShowAutoTags = EditorGUILayout.Foldout (isShowAutoTags, "Auto generated"); if (isShowAutoTags) { foreach (TagInstance tag in tags.autoGenerated) { EditorGUILayout.LabelField (tag.Descriptor + ": " + tag.Name); } EditorGUILayout.Space (); EditorGUILayout.BeginHorizontal (); string autoUpdateState = tags.AutoUpdate ? "On" : "Off"; if (!tags.AutoUpdate) { if (GUILayout.Button ("Update Tags")) { tags.UpdateTags (); } } if (GUILayout.Button ("Auto Update: " + autoUpdateState)) { tags.AutoUpdate = !tags.AutoUpdate; } EditorGUILayout.EndHorizontal (); EditorGUILayout.Space (); } isShowUserTags = EditorGUILayout.Foldout (isShowUserTags, "User defined"); } if (isShowUserTags || !IsChunk) { for (int i = 0; i < serTagList.arraySize; i++) { EditorGUILayout.BeginHorizontal (); SerializedProperty serTagInstance = serTagList.GetArrayElementAtIndex (i); SerializedProperty serTagName = serTagInstance.FindPropertyRelative ("Name"); serTagName.stringValue = EditorGUILayout.TextField (serTagName.stringValue); if (GUILayout.Button ("x", GUILayout.Width (20))) { serTagList.DeleteArrayElementAtIndex (i); } EditorGUILayout.EndHorizontal (); } if (GUILayout.Button ("New Tag")) { serTagList.InsertArrayElementAtIndex (serTagList.arraySize); SerializedProperty newlyCreated = serTagList.GetArrayElementAtIndex (serTagList.arraySize - 1); SerializedProperty newTagName = newlyCreated.FindPropertyRelative ("Name"); newTagName.stringValue = "New Tag"; } } serTagObj.ApplyModifiedProperties (); } private bool IsChunk{ get{ return tags.gameObject.tag == "Chunk"; } } }
0
0.827262
1
0.827262
game-dev
MEDIA
0.739437
game-dev
0.775495
1
0.775495
IllusionMods/BepisPlugins
3,742
src/Core_Sideloader/Core.Sideloader.BundleManager.cs
using Shared; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using UnityEngine; namespace Sideloader { internal static class BundleManager { internal static Dictionary<string, List<LazyCustom<AssetBundle>>> Bundles = new Dictionary<string, List<LazyCustom<AssetBundle>>>(); private static long CABCounter; // Only ASCII chars or we'll explode internal static string GenerateCAB() => "CAB-" + Interlocked.Increment(ref CABCounter).ToString("x32"); internal static void RandomizeCAB(byte[] assetBundleData) { var ascii = Encoding.ASCII.GetString(assetBundleData, 0, Mathf.Min(1024, assetBundleData.Length - 4)); var origCabIndex = ascii.IndexOf("CAB-", StringComparison.Ordinal); if (origCabIndex < 0) return; var origCabLength = ascii.Substring(origCabIndex).IndexOf('\0'); if (origCabLength < 0) return; var CAB = GenerateCAB().Substring(4); var cabBytes = Encoding.ASCII.GetBytes(CAB); if (origCabLength > 36) return; Buffer.BlockCopy(cabBytes, 36 - origCabLength, assetBundleData, origCabIndex + 4, origCabLength - 4); } internal static void AddBundleLoader(Func<AssetBundle> func, string path) { if (!Bundles.TryGetValue(path, out var lazyList)) { lazyList = new List<LazyCustom<AssetBundle>>(); Bundles.Add(path, lazyList); } lazyList.Add(LazyCustom<AssetBundle>.Create(func)); } internal static bool TryGetObjectFromName<T>(string name, string assetBundle, out T obj) where T : UnityEngine.Object { var result = TryGetObjectFromName(name, assetBundle, typeof(T), out var tObj); obj = (T)tObj; return result; } internal static bool TryGetObjectFromName(string name, string assetBundle, Type type, out UnityEngine.Object obj) { obj = null; if (Bundles.TryGetValue(assetBundle, out var lazyBundleList)) { var found = -1; for (int i = 0; i < lazyBundleList.Count; i++) { AssetBundle bundle = lazyBundleList[i]; if (bundle.Contains(name)) { // If using debug logging, check all override bundles for this asset and warn if multiple copies exist. // This will force all override bundles to load so it's slower. if (Sideloader.DebugLoggingModLoading.Value) { if (found >= 0) { Sideloader.Logger.LogWarning($"Asset [{name}] in bundle [{assetBundle}] is overridden by multiple zipmods! " + $"Only asset from override #{found + 1} will be used! It also exists in override #{i + 1}."); } else { found = i; obj = bundle.LoadAsset(name, type); } continue; } obj = bundle.LoadAsset(name, type); return true; } } // Needed for the logging codepath if (found >= 0) return true; } return false; } } }
0
0.805521
1
0.805521
game-dev
MEDIA
0.778838
game-dev
0.958315
1
0.958315
focus-creative-games/luban_examples
1,150
Projects/Csharp_NewtonSoft_json/Benchmark.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; class CacheLoader { public string Dir { get; } private readonly Dictionary<string, string> cache = new(); public CacheLoader(string dir) { Dir = dir; } public JArray LoadOrFromCache(string name) { if (!cache.TryGetValue(name, out string result)) { result = File.ReadAllText($"{Dir}/{name}.json"); cache.Add(name, result); } return JsonConvert.DeserializeObject(result) as JArray; } } internal class Benchmark { public static void Run(string dir) { var loader = new CacheLoader(dir); var tables = new List<cfg.Tables>(); for (int k = 0; k < 10; k++) { var w = new Stopwatch(); w.Start(); for (int i = 0; i < 100; i++) { tables.Add(new cfg.Tables(loader.LoadOrFromCache)); } w.Stop(); Console.WriteLine("== cost {0} ms", w.ElapsedMilliseconds); } } }
0
0.746612
1
0.746612
game-dev
MEDIA
0.358893
game-dev
0.864626
1
0.864626
openfl/starling
10,463
src/starling/utils/ButtonBehavior.hx
// ================================================================================================= // // Starling Framework // Copyright Gamua GmbH. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.utils; import haxe.Constraints.Function; import openfl.errors.ArgumentError; import openfl.geom.Point; import openfl.geom.Rectangle; import openfl.ui.Mouse; import openfl.ui.MouseCursor; import starling.display.ButtonState; import starling.display.DisplayObject; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; /** A utility class that can help with creating button-like display objects. * * <p>When reacting to touch input, taps can easily be recognized through standard touch * events via <code>TouchPhase.ENDED</code>. However, you often want a more elaborate kind of * input handling, like that provide by Starling's <em>Button</em> class and its * <em>TRIGGERED</em> event. It allows users to cancel a tap by moving the finger away from * the object, for example; and it supports changing its appearance depending on its state.</p> * * <p>Here is an example: a class that extends <em>TextField</em> and uses * <em>ButtonBehavior</em> to add TRIGGER events and state-based coloring.</p> * * <listing> * public class TextButton extends TextField * { * private var _behavior:ButtonBehavior; * private var _tint:uint = 0xffaaff; * * public function TextButton(width:int, height:int, text:String="", * format:TextFormat=null, options:TextOptions=null) * { * super(width, height, text, format, options); * _behavior = new ButtonBehavior(this, onStateChange); * } * * private function onStateChange(state:String):void * { * if (state == ButtonState.DOWN) format.color = _tint; * else format.color = 0xffffff; * } * * public override function hitTest(localPoint:Point):DisplayObject * { * return _behavior.hitTest(localPoint); * } * }</listing> * * <p>Instances of this class will now dispatch <em>Event.TRIGGERED</em> events (just like * conventional buttons) and they will change their color when being touched.</p> */ class ButtonBehavior { // 'minHitAreaSize' defaults to 44 points, as recommended by Apple Human Interface Guidelines. // -> https://developer.apple.com/ios/human-interface-guidelines/visual-design/adaptivity-and-layout/ @:noCompletion private var __state:String; @:noCompletion private var __target:DisplayObject; @:noCompletion private var __triggerBounds:Rectangle; @:noCompletion private var __minHitAreaSize:Float; @:noCompletion private var __abortDistance:Float; @:noCompletion private var __onStateChange:Function; @:noCompletion private var __useHandCursor:Bool; @:noCompletion private var __enabled:Bool; private static var sBounds:Rectangle = new Rectangle(); #if commonjs private static function __init__ () { untyped Object.defineProperties (ButtonBehavior.prototype, { "state": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_state (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_state (v); }") }, "target": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_target (); }") }, "onStateChange": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_onStateChange (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_onStateChange (v); }") }, "useHandCursor": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_useHandCursor (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_useHandCursor (v); }") }, "enabled": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_enabled (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_enabled (v); }") }, "minHitAreaSize": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_minHitAreaSize (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_minHitAreaSize (v); }") }, "abortDistance": { get: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function () { return this.get_abortDistance (); }"), set: untyped #if haxe4 js.Syntax.code #else __js__ #end ("function (v) { return this.set_abortDistance (v); }") }, }); } #end /** Create a new ButtonBehavior. * * @param target The object on which to listen for touch events. * @param onStateChange This callback will be executed whenever the button's state ought * to change. <code>function(state:String):void</code> * @param minHitAreaSize If the display area of 'target' is smaller than a square of this * size, its hit area will be extended accordingly. * @param abortDistance The distance you can move away your finger before triggering * is aborted. */ public function new(target:DisplayObject, onStateChange:Function, minHitAreaSize:Float = 44, abortDistance:Float = 50) { if (target == null) throw new ArgumentError("target cannot be null"); if (onStateChange == null) throw new ArgumentError("onStateChange cannot be null"); __target = target; __target.addEventListener(TouchEvent.TOUCH, onTouch); __onStateChange = onStateChange; __minHitAreaSize = minHitAreaSize; __abortDistance = abortDistance; __triggerBounds = new Rectangle(); __state = ButtonState.UP; __useHandCursor = true; __enabled = true; } private function onTouch(event:TouchEvent):Void { Mouse.cursor = (__useHandCursor && __enabled && event.interactsWith(__target)) ? MouseCursor.BUTTON : MouseCursor.AUTO; var touch:Touch = event.getTouch(__target); var isWithinBounds:Bool; if (!__enabled) { // do nothing } else if (touch == null) { state = ButtonState.UP; } else if (touch.phase == TouchPhase.HOVER) { state = ButtonState.OVER; } else if (touch.phase == TouchPhase.BEGAN && __state != ButtonState.DOWN) { __triggerBounds = __target.getBounds(__target.stage, __triggerBounds); __triggerBounds.inflate(__abortDistance, __abortDistance); state = ButtonState.DOWN; } else if (touch.phase == TouchPhase.MOVED) { isWithinBounds = __triggerBounds.contains(touch.globalX, touch.globalY); if (__state == ButtonState.DOWN && !isWithinBounds) { // reset button when finger is moved too far away ... state = ButtonState.UP; } else if (__state == ButtonState.UP && isWithinBounds) { // ... and reactivate when the finger moves back into the bounds. state = ButtonState.DOWN; } } else if (touch.phase == TouchPhase.ENDED && __state == ButtonState.DOWN) { state = ButtonState.UP; if (!touch.cancelled) __target.dispatchEventWith(Event.TRIGGERED, true); } } /** Forward your target's <code>hitTests</code> to this method to make sure that the hit * area is extended to <code>minHitAreaSize</code>. */ public function hitTest(localPoint:Point):DisplayObject { if (!__target.visible || !__target.touchable || !__target.hitTestMask(localPoint)) return null; __target.getBounds(__target, sBounds); if (sBounds.width < __minHitAreaSize) sBounds.inflate((__minHitAreaSize - sBounds.width) / 2, 0); if (sBounds.height < __minHitAreaSize) sBounds.inflate(0, (__minHitAreaSize - sBounds.height) / 2); if (sBounds.containsPoint(localPoint)) return __target; else return null; } /** The current state of the button. The corresponding strings are found * in the ButtonState class. */ public var state(get, set):String; private function get_state():String { return __state; } private function set_state(value:String):String { if (__state != value) { if (ButtonState.isValid(value)) { __state = value; Execute.execute(__onStateChange, [value]); } else throw new ArgumentError("Invalid button state: " + value); } return value; } /** The target on which this behavior operates. */ public var target(get, never):DisplayObject; public function get_target():DisplayObject { return __target; } /** The callback that is executed whenever the state changes. * Format: <code>function(state:String):void</code> */ public var onStateChange(get, set):Function; public function get_onStateChange():Function { return __onStateChange; } public function set_onStateChange(value:Function):Function { return __onStateChange = value; } /** Indicates if the mouse cursor should transform into a hand while it's over the button. * @default true */ public var useHandCursor(get, set):Bool; public function get_useHandCursor():Bool { return __useHandCursor; } public function set_useHandCursor(value:Bool):Bool { return __useHandCursor = value; } /** Indicates if the button can be triggered. */ public var enabled(get, set):Bool; public function get_enabled():Bool { return __enabled; } public function set_enabled(value:Bool):Bool { if (__enabled != value) { __enabled = value; state = value ? ButtonState.UP : ButtonState.DISABLED; } return __enabled; } /** The target's hit area will be extended to have at least this width / height. * Note that for this to work, you need to forward your hit tests to this class. */ public var minHitAreaSize(get, set):Float; public function get_minHitAreaSize():Float { return __minHitAreaSize; } public function set_minHitAreaSize(value:Float):Float { return __minHitAreaSize = value; } /** The distance you can move away your finger before triggering is aborted. */ public var abortDistance(get, set):Float; public function get_abortDistance():Float { return __abortDistance; } public function set_abortDistance(value:Float):Float { return __abortDistance = value; } }
0
0.922629
1
0.922629
game-dev
MEDIA
0.596057
game-dev
0.854992
1
0.854992
id-Software/DOOM-3-BFG
45,253
neo/framework/Common.cpp
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition 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. Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../idlib/precompiled.h" #pragma hdrstop #include "Common_local.h" #include "ConsoleHistory.h" #include "../renderer/AutoRenderBink.h" #include "../sound/sound.h" #include "../../doomclassic/doom/doomlib.h" #include "../../doomclassic/doom/d_event.h" #include "../../doomclassic/doom/d_main.h" #include "../sys/sys_savegame.h" #if defined( _DEBUG ) #define BUILD_DEBUG "-debug" #else #define BUILD_DEBUG "" #endif struct version_s { version_s() { sprintf( string, "%s.%d%s %s %s %s", ENGINE_VERSION, BUILD_NUMBER, BUILD_DEBUG, BUILD_STRING, __DATE__, __TIME__ ); } char string[256]; } version; idCVar com_version( "si_version", version.string, CVAR_SYSTEM|CVAR_ROM|CVAR_SERVERINFO, "engine version" ); idCVar com_forceGenericSIMD( "com_forceGenericSIMD", "0", CVAR_BOOL | CVAR_SYSTEM | CVAR_NOCHEAT, "force generic platform independent SIMD" ); #ifdef ID_RETAIL idCVar com_allowConsole( "com_allowConsole", "0", CVAR_BOOL | CVAR_SYSTEM | CVAR_INIT, "allow toggling console with the tilde key" ); #else idCVar com_allowConsole( "com_allowConsole", "1", CVAR_BOOL | CVAR_SYSTEM | CVAR_INIT, "allow toggling console with the tilde key" ); #endif idCVar com_developer( "developer", "0", CVAR_BOOL|CVAR_SYSTEM|CVAR_NOCHEAT, "developer mode" ); idCVar com_speeds( "com_speeds", "0", CVAR_BOOL|CVAR_SYSTEM|CVAR_NOCHEAT, "show engine timings" ); idCVar com_showFPS( "com_showFPS", "0", CVAR_BOOL|CVAR_SYSTEM|CVAR_ARCHIVE|CVAR_NOCHEAT, "show frames rendered per second" ); idCVar com_showMemoryUsage( "com_showMemoryUsage", "0", CVAR_BOOL|CVAR_SYSTEM|CVAR_NOCHEAT, "show total and per frame memory usage" ); idCVar com_updateLoadSize( "com_updateLoadSize", "0", CVAR_BOOL | CVAR_SYSTEM | CVAR_NOCHEAT, "update the load size after loading a map" ); idCVar com_productionMode( "com_productionMode", "0", CVAR_SYSTEM | CVAR_BOOL, "0 - no special behavior, 1 - building a production build, 2 - running a production build" ); idCVar com_japaneseCensorship( "com_japaneseCensorship", "0", CVAR_NOCHEAT, "Enable Japanese censorship" ); idCVar preload_CommonAssets( "preload_CommonAssets", "1", CVAR_SYSTEM | CVAR_BOOL, "preload common assets" ); idCVar net_inviteOnly( "net_inviteOnly", "1", CVAR_BOOL | CVAR_ARCHIVE, "whether or not the private server you create allows friends to join or invite only" ); extern idCVar g_demoMode; idCVar com_engineHz( "com_engineHz", "60", CVAR_FLOAT | CVAR_ARCHIVE, "Frames per second the engine runs at", 10.0f, 1024.0f ); float com_engineHz_latched = 60.0f; // Latched version of cvar, updated between map loads int64 com_engineHz_numerator = 100LL * 1000LL; int64 com_engineHz_denominator = 100LL * 60LL; HWND com_hwndMsg = NULL; #ifdef __DOOM_DLL__ idGame * game = NULL; idGameEdit * gameEdit = NULL; #endif idCommonLocal commonLocal; idCommon * common = &commonLocal; idCVar com_skipIntroVideos( "com_skipIntroVideos", "0", CVAR_BOOL , "skips intro videos" ); // For doom classic struct Globals; /* ================== idCommonLocal::idCommonLocal ================== */ idCommonLocal::idCommonLocal() : readSnapshotIndex( 0 ), writeSnapshotIndex( 0 ), optimalTimeBuffered( 0.0f ), optimalTimeBufferedWindow( 0.0f ), optimalPCTBuffer( 0.5f ), lastPacifierSessionTime( 0 ), lastPacifierGuiTime( 0 ), lastPacifierDialogState( false ), showShellRequested( false ), currentGame( DOOM3_BFG ), idealCurrentGame( DOOM3_BFG ), doomClassicMaterial( NULL ) { snapCurrent.localTime = -1; snapPrevious.localTime = -1; snapCurrent.serverTime = -1; snapPrevious.serverTime = -1; snapTimeBuffered = 0.0f; effectiveSnapRate = 0.0f; totalBufferedTime = 0; totalRecvTime = 0; com_fullyInitialized = false; com_refreshOnPrint = false; com_errorEntered = ERP_NONE; com_shuttingDown = false; com_isJapaneseSKU = false; logFile = NULL; strcpy( errorMessage, "" ); rd_buffer = NULL; rd_buffersize = 0; rd_flush = NULL; gameDLL = 0; loadGUI = NULL; nextLoadTip = 0; isHellMap = false; wipeForced = false; defaultLoadscreen = false; menuSoundWorld = NULL; insideUpdateScreen = false; insideExecuteMapChange = false; mapSpawnData.savegameFile = NULL; currentMapName.Clear(); aviDemoShortName.Clear(); renderWorld = NULL; soundWorld = NULL; menuSoundWorld = NULL; readDemo = NULL; writeDemo = NULL; gameFrame = 0; gameTimeResidual = 0; syncNextGameFrame = true; mapSpawned = false; aviCaptureMode = false; timeDemo = TD_NO; nextSnapshotSendTime = 0; nextUsercmdSendTime = 0; clientPrediction = 0; saveFile = NULL; stringsFile = NULL; ClearWipe(); } /* ================== idCommonLocal::Quit ================== */ void idCommonLocal::Quit() { // don't try to shutdown if we are in a recursive error if ( !com_errorEntered ) { Shutdown(); } Sys_Quit(); } /* ============================================================================ COMMAND LINE FUNCTIONS + characters separate the commandLine string into multiple console command lines. All of these are valid: doom +set test blah +map test doom set test blah+map test doom set test blah + map test ============================================================================ */ #define MAX_CONSOLE_LINES 32 int com_numConsoleLines; idCmdArgs com_consoleLines[MAX_CONSOLE_LINES]; /* ================== idCommonLocal::ParseCommandLine ================== */ void idCommonLocal::ParseCommandLine( int argc, const char * const * argv ) { int i, current_count; com_numConsoleLines = 0; current_count = 0; // API says no program path for ( i = 0; i < argc; i++ ) { if ( idStr::Icmp( argv[ i ], "+connect_lobby" ) == 0 ) { // Handle Steam bootable invites. session->HandleBootableInvite( _atoi64( argv[ i + 1 ] ) ); } else if ( argv[ i ][ 0 ] == '+' ) { com_numConsoleLines++; com_consoleLines[ com_numConsoleLines-1 ].AppendArg( argv[ i ] + 1 ); } else { if ( !com_numConsoleLines ) { com_numConsoleLines++; } com_consoleLines[ com_numConsoleLines-1 ].AppendArg( argv[ i ] ); } } } /* ================== idCommonLocal::SafeMode Check for "safe" on the command line, which will skip loading of config file (DoomConfig.cfg) ================== */ bool idCommonLocal::SafeMode() { int i; for ( i = 0 ; i < com_numConsoleLines ; i++ ) { if ( !idStr::Icmp( com_consoleLines[ i ].Argv(0), "safe" ) || !idStr::Icmp( com_consoleLines[ i ].Argv(0), "cvar_restart" ) ) { com_consoleLines[ i ].Clear(); return true; } } return false; } /* ================== idCommonLocal::StartupVariable Searches for command line parameters that are set commands. If match is not NULL, only that cvar will be looked for. That is necessary because cddir and basedir need to be set before the filesystem is started, but all other sets should be after execing the config and default. ================== */ void idCommonLocal::StartupVariable( const char *match ) { int i = 0; while ( i < com_numConsoleLines ) { if ( strcmp( com_consoleLines[ i ].Argv( 0 ), "set" ) != 0 ) { i++; continue; } const char * s = com_consoleLines[ i ].Argv(1); if ( !match || !idStr::Icmp( s, match ) ) { cvarSystem->SetCVarString( s, com_consoleLines[ i ].Argv( 2 ) ); } i++; } } /* ================== idCommonLocal::AddStartupCommands Adds command line parameters as script statements Commands are separated by + signs Returns true if any late commands were added, which will keep the demoloop from immediately starting ================== */ void idCommonLocal::AddStartupCommands() { // quote every token, so args with semicolons can work for ( int i = 0; i < com_numConsoleLines; i++ ) { if ( !com_consoleLines[i].Argc() ) { continue; } // directly as tokenized so nothing gets screwed cmdSystem->BufferCommandArgs( CMD_EXEC_APPEND, com_consoleLines[i] ); } } /* ================== idCommonLocal::WriteConfigToFile ================== */ void idCommonLocal::WriteConfigToFile( const char *filename ) { idFile * f = fileSystem->OpenFileWrite( filename ); if ( !f ) { Printf ("Couldn't write %s.\n", filename ); return; } idKeyInput::WriteBindings( f ); cvarSystem->WriteFlaggedVariables( CVAR_ARCHIVE, "set", f ); fileSystem->CloseFile( f ); } /* =============== idCommonLocal::WriteConfiguration Writes key bindings and archived cvars to config file if modified =============== */ void idCommonLocal::WriteConfiguration() { // if we are quiting without fully initializing, make sure // we don't write out anything if ( !com_fullyInitialized ) { return; } if ( !( cvarSystem->GetModifiedFlags() & CVAR_ARCHIVE ) ) { return; } cvarSystem->ClearModifiedFlags( CVAR_ARCHIVE ); // save to the profile idLocalUser * user = session->GetSignInManager().GetMasterLocalUser(); if ( user != NULL ) { user->SaveProfileSettings(); } #ifdef CONFIG_FILE // disable printing out the "Writing to:" message bool developer = com_developer.GetBool(); com_developer.SetBool( false ); WriteConfigToFile( CONFIG_FILE ); // restore the developer cvar com_developer.SetBool( developer ); #endif } /* =============== KeysFromBinding() Returns the key bound to the command =============== */ const char* idCommonLocal::KeysFromBinding( const char *bind ) { return idKeyInput::KeysFromBinding( bind ); } /* =============== BindingFromKey() Returns the binding bound to key =============== */ const char* idCommonLocal::BindingFromKey( const char *key ) { return idKeyInput::BindingFromKey( key ); } /* =============== ButtonState() Returns the state of the button =============== */ int idCommonLocal::ButtonState( int key ) { return usercmdGen->ButtonState(key); } /* =============== ButtonState() Returns the state of the key =============== */ int idCommonLocal::KeyState( int key ) { return usercmdGen->KeyState(key); } /* ============ idCmdSystemLocal::PrintMemInfo_f This prints out memory debugging data ============ */ CONSOLE_COMMAND( printMemInfo, "prints memory debugging data", NULL ) { MemInfo_t mi; memset( &mi, 0, sizeof( mi ) ); mi.filebase = commonLocal.GetCurrentMapName(); renderSystem->PrintMemInfo( &mi ); // textures and models soundSystem->PrintMemInfo( &mi ); // sounds common->Printf( " Used image memory: %s bytes\n", idStr::FormatNumber( mi.imageAssetsTotal ).c_str() ); mi.assetTotals += mi.imageAssetsTotal; common->Printf( " Used model memory: %s bytes\n", idStr::FormatNumber( mi.modelAssetsTotal ).c_str() ); mi.assetTotals += mi.modelAssetsTotal; common->Printf( " Used sound memory: %s bytes\n", idStr::FormatNumber( mi.soundAssetsTotal ).c_str() ); mi.assetTotals += mi.soundAssetsTotal; common->Printf( " Used asset memory: %s bytes\n", idStr::FormatNumber( mi.assetTotals ).c_str() ); // write overview file idFile *f; f = fileSystem->OpenFileAppend( "maps/printmeminfo.txt" ); if ( !f ) { return; } f->Printf( "total(%s ) image(%s ) model(%s ) sound(%s ): %s\n", idStr::FormatNumber( mi.assetTotals ).c_str(), idStr::FormatNumber( mi.imageAssetsTotal ).c_str(), idStr::FormatNumber( mi.modelAssetsTotal ).c_str(), idStr::FormatNumber( mi.soundAssetsTotal ).c_str(), mi.filebase.c_str() ); fileSystem->CloseFile( f ); } /* ================== Com_Error_f Just throw a fatal error to test error shutdown procedures. ================== */ CONSOLE_COMMAND( error, "causes an error", NULL ) { if ( !com_developer.GetBool() ) { commonLocal.Printf( "error may only be used in developer mode\n" ); return; } if ( args.Argc() > 1 ) { commonLocal.FatalError( "Testing fatal error" ); } else { commonLocal.Error( "Testing drop error" ); } } /* ================== Com_Freeze_f Just freeze in place for a given number of seconds to test error recovery. ================== */ CONSOLE_COMMAND( freeze, "freezes the game for a number of seconds", NULL ) { float s; int start, now; if ( args.Argc() != 2 ) { commonLocal.Printf( "freeze <seconds>\n" ); return; } if ( !com_developer.GetBool() ) { commonLocal.Printf( "freeze may only be used in developer mode\n" ); return; } s = atof( args.Argv(1) ); start = eventLoop->Milliseconds(); while ( 1 ) { now = eventLoop->Milliseconds(); if ( ( now - start ) * 0.001f > s ) { break; } } } /* ================= Com_Crash_f A way to force a bus error for development reasons ================= */ CONSOLE_COMMAND( crash, "causes a crash", NULL ) { if ( !com_developer.GetBool() ) { commonLocal.Printf( "crash may only be used in developer mode\n" ); return; } * ( int * ) 0 = 0x12345678; } /* ================= Com_Quit_f ================= */ CONSOLE_COMMAND_SHIP( quit, "quits the game", NULL ) { commonLocal.Quit(); } CONSOLE_COMMAND_SHIP( exit, "exits the game", NULL ) { commonLocal.Quit(); } /* =============== Com_WriteConfig_f Write the config file to a specific name =============== */ CONSOLE_COMMAND( writeConfig, "writes a config file", NULL ) { idStr filename; if ( args.Argc() != 2 ) { commonLocal.Printf( "Usage: writeconfig <filename>\n" ); return; } filename = args.Argv(1); filename.DefaultFileExtension( ".cfg" ); commonLocal.Printf( "Writing %s.\n", filename.c_str() ); commonLocal.WriteConfigToFile( filename ); } /* ======================== idCommonLocal::CheckStartupStorageRequirements ======================== */ void idCommonLocal::CheckStartupStorageRequirements() { int64 availableSpace = 0; // ------------------------------------------------------------------------ // Savegame and Profile required storage // ------------------------------------------------------------------------ { // Make sure the save path exists in case it was deleted. // If the path cannot be created we can safely assume there is no // free space because in that case nothing can be saved anyway. const char * savepath = cvarSystem->GetCVarString( "fs_savepath" ); idStr directory = savepath; //idStr directory = fs_savepath.GetString(); directory += "\\"; // so it doesn't think the last part is a file and ignores in the directory creation fileSystem->CreateOSPath( directory ); // Get the free space on the save path. availableSpace = Sys_GetDriveFreeSpaceInBytes( savepath ); // If free space fails then get space on drive as a fall back // (the directory will be created later anyway) if ( availableSpace <= 1 ) { idStr savePath( savepath ); if ( savePath.Length() >= 3 ) { if ( savePath[ 1 ] == ':' && savePath[ 2 ] == '\\' && ( ( savePath[ 0 ] >= 'A' && savePath[ 0 ] <= 'Z' ) || ( savePath[ 0 ] >= 'a' && savePath[ 0 ] <= 'z' ) ) ) { savePath = savePath.Left( 3 ); availableSpace = Sys_GetDriveFreeSpaceInBytes( savePath ); } } } } const int MIN_SAVE_STORAGE_PROFILE = 1024 * 1024; const int MIN_SAVE_STORAGE_SAVEGAME = MIN_SAVEGAME_SIZE_BYTES; uint64 requiredSizeBytes = MIN_SAVE_STORAGE_SAVEGAME + MIN_SAVE_STORAGE_PROFILE; idLib::Printf( "requiredSizeBytes: %lld\n", requiredSizeBytes ); if ( (int64)( requiredSizeBytes - availableSpace ) > 0 ) { class idSWFScriptFunction_Continue : public idSWFScriptFunction_RefCounted { public: virtual ~idSWFScriptFunction_Continue() {} idSWFScriptVar Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { common->Dialog().ClearDialog( GDM_INSUFFICENT_STORAGE_SPACE ); common->Quit(); return idSWFScriptVar(); } }; idStaticList< idSWFScriptFunction *, 4 > callbacks; idStaticList< idStrId, 4 > optionText; callbacks.Append( new (TAG_SWF) idSWFScriptFunction_Continue() ); optionText.Append( idStrId( "#STR_SWF_ACCEPT" ) ); // build custom space required string // #str_dlg_space_required ~= "There is insufficient storage available. Please free %s and try again." idStr format = idStrId( "#str_dlg_startup_insufficient_storage" ).GetLocalizedString(); idStr size; if ( requiredSizeBytes > ( 1024 * 1024 ) ) { size = va( "%.1f MB", (float)requiredSizeBytes / ( 1024.0f * 1024.0f ) + 0.1f ); // +0.1 to avoid truncation } else { size = va( "%.1f KB", (float)requiredSizeBytes / 1024.0f + 0.1f ); } idStr msg = va( format.c_str(), size.c_str() ); common->Dialog().AddDynamicDialog( GDM_INSUFFICENT_STORAGE_SPACE, callbacks, optionText, true, msg ); } session->GetAchievementSystem().Start(); } /* =============== idCommonLocal::JapaneseCensorship =============== */ bool idCommonLocal::JapaneseCensorship() const { return com_japaneseCensorship.GetBool() || com_isJapaneseSKU; } /* =============== idCommonLocal::FilterLangList =============== */ void idCommonLocal::FilterLangList( idStrList* list, idStr lang ) { idStr temp; for( int i = 0; i < list->Num(); i++ ) { temp = (*list)[i]; temp = temp.Right(temp.Length()-strlen("strings/")); temp = temp.Left(lang.Length()); if(idStr::Icmp(temp, lang) != 0) { list->RemoveIndex(i); i--; } } } /* =============== idCommonLocal::InitLanguageDict =============== */ extern idCVar sys_lang; void idCommonLocal::InitLanguageDict() { idStr fileName; //D3XP: Instead of just loading a single lang file for each language //we are going to load all files that begin with the language name //similar to the way pak files work. So you can place english001.lang //to add new strings to the english language dictionary idFileList* langFiles; langFiles = fileSystem->ListFilesTree( "strings", ".lang", true ); idStrList langList = langFiles->GetList(); // Loop through the list and filter idStrList currentLangList = langList; FilterLangList( &currentLangList, sys_lang.GetString() ); if ( currentLangList.Num() == 0 ) { // reset to english and try to load again sys_lang.SetString( ID_LANG_ENGLISH ); currentLangList = langList; FilterLangList( &currentLangList, sys_lang.GetString() ); } idLocalization::ClearDictionary(); for( int i = 0; i < currentLangList.Num(); i++ ) { //common->Printf("%s\n", currentLangList[i].c_str()); const byte * buffer = NULL; int len = fileSystem->ReadFile( currentLangList[i], (void**)&buffer ); if ( len <= 0 ) { assert( false && "couldn't read the language dict file" ); break; } idLocalization::LoadDictionary( buffer, len, currentLangList[i] ); fileSystem->FreeFile( (void *)buffer ); } fileSystem->FreeFileList(langFiles); } /* ================= ReloadLanguage_f ================= */ CONSOLE_COMMAND( reloadLanguage, "reload language dict", NULL ) { commonLocal.InitLanguageDict(); } #include "../renderer/Image.h" /* ================= Com_StartBuild_f ================= */ CONSOLE_COMMAND( startBuild, "prepares to make a build", NULL ) { globalImages->StartBuild(); } /* ================= Com_FinishBuild_f ================= */ CONSOLE_COMMAND( finishBuild, "finishes the build process", NULL ) { if ( game ) { game->CacheDictionaryMedia( NULL ); } globalImages->FinishBuild( ( args.Argc() > 1 ) ); } /* ================= idCommonLocal::RenderSplash ================= */ void idCommonLocal::RenderSplash() { const float sysWidth = renderSystem->GetWidth() * renderSystem->GetPixelAspect(); const float sysHeight = renderSystem->GetHeight(); const float sysAspect = sysWidth / sysHeight; const float splashAspect = 16.0f / 9.0f; const float adjustment = sysAspect / splashAspect; const float barHeight = ( adjustment >= 1.0f ) ? 0.0f : ( 1.0f - adjustment ) * (float)SCREEN_HEIGHT * 0.25f; const float barWidth = ( adjustment <= 1.0f ) ? 0.0f : ( adjustment - 1.0f ) * (float)SCREEN_WIDTH * 0.25f; if ( barHeight > 0.0f ) { renderSystem->SetColor( colorBlack ); renderSystem->DrawStretchPic( 0, 0, SCREEN_WIDTH, barHeight, 0, 0, 1, 1, whiteMaterial ); renderSystem->DrawStretchPic( 0, SCREEN_HEIGHT - barHeight, SCREEN_WIDTH, barHeight, 0, 0, 1, 1, whiteMaterial ); } if ( barWidth > 0.0f ) { renderSystem->SetColor( colorBlack ); renderSystem->DrawStretchPic( 0, 0, barWidth, SCREEN_HEIGHT, 0, 0, 1, 1, whiteMaterial ); renderSystem->DrawStretchPic( SCREEN_WIDTH - barWidth, 0, barWidth, SCREEN_HEIGHT, 0, 0, 1, 1, whiteMaterial ); } renderSystem->SetColor4( 1, 1, 1, 1 ); renderSystem->DrawStretchPic( barWidth, barHeight, SCREEN_WIDTH - barWidth * 2.0f, SCREEN_HEIGHT - barHeight * 2.0f, 0, 0, 1, 1, splashScreen ); const emptyCommand_t * cmd = renderSystem->SwapCommandBuffers( &time_frontend, &time_backend, &time_shadows, &time_gpu ); renderSystem->RenderCommandBuffers( cmd ); } /* ================= idCommonLocal::RenderBink ================= */ void idCommonLocal::RenderBink( const char * path ) { const float sysWidth = renderSystem->GetWidth() * renderSystem->GetPixelAspect(); const float sysHeight = renderSystem->GetHeight(); const float sysAspect = sysWidth / sysHeight; const float movieAspect = ( 16.0f / 9.0f ); const float imageWidth = SCREEN_WIDTH * movieAspect / sysAspect; const float chop = 0.5f * ( SCREEN_WIDTH - imageWidth ); idStr materialText; materialText.Format( "{ translucent { videoMap %s } }", path ); idMaterial * material = const_cast<idMaterial*>( declManager->FindMaterial( "splashbink" ) ); material->Parse( materialText.c_str(), materialText.Length(), false ); material->ResetCinematicTime( Sys_Milliseconds() ); while ( Sys_Milliseconds() <= material->GetCinematicStartTime() + material->CinematicLength() ) { renderSystem->DrawStretchPic( chop, 0, imageWidth, SCREEN_HEIGHT, 0, 0, 1, 1, material ); const emptyCommand_t * cmd = renderSystem->SwapCommandBuffers( &time_frontend, &time_backend, &time_shadows, &time_gpu ); renderSystem->RenderCommandBuffers( cmd ); Sys_GenerateEvents(); Sys_Sleep( 10 ); } material->MakeDefault(); } /* ================= idCommonLocal::InitSIMD ================= */ void idCommonLocal::InitSIMD() { idSIMD::InitProcessor( "doom", com_forceGenericSIMD.GetBool() ); com_forceGenericSIMD.ClearModified(); } /* ================= idCommonLocal::LoadGameDLL ================= */ void idCommonLocal::LoadGameDLL() { #ifdef __DOOM_DLL__ char dllPath[ MAX_OSPATH ]; gameImport_t gameImport; gameExport_t gameExport; GetGameAPI_t GetGameAPI; fileSystem->FindDLL( "game", dllPath, true ); if ( !dllPath[ 0 ] ) { common->FatalError( "couldn't find game dynamic library" ); return; } common->DPrintf( "Loading game DLL: '%s'\n", dllPath ); gameDLL = sys->DLL_Load( dllPath ); if ( !gameDLL ) { common->FatalError( "couldn't load game dynamic library" ); return; } const char * functionName = "GetGameAPI"; GetGameAPI = (GetGameAPI_t) Sys_DLL_GetProcAddress( gameDLL, functionName ); if ( !GetGameAPI ) { Sys_DLL_Unload( gameDLL ); gameDLL = NULL; common->FatalError( "couldn't find game DLL API" ); return; } gameImport.version = GAME_API_VERSION; gameImport.sys = ::sys; gameImport.common = ::common; gameImport.cmdSystem = ::cmdSystem; gameImport.cvarSystem = ::cvarSystem; gameImport.fileSystem = ::fileSystem; gameImport.renderSystem = ::renderSystem; gameImport.soundSystem = ::soundSystem; gameImport.renderModelManager = ::renderModelManager; gameImport.uiManager = ::uiManager; gameImport.declManager = ::declManager; gameImport.AASFileManager = ::AASFileManager; gameImport.collisionModelManager = ::collisionModelManager; gameExport = *GetGameAPI( &gameImport ); if ( gameExport.version != GAME_API_VERSION ) { Sys_DLL_Unload( gameDLL ); gameDLL = NULL; common->FatalError( "wrong game DLL API version" ); return; } game = gameExport.game; gameEdit = gameExport.gameEdit; #endif // initialize the game object if ( game != NULL ) { game->Init(); } } /* ================= idCommonLocal::UnloadGameDLL ================= */ void idCommonLocal::CleanupShell() { if ( game != NULL ) { game->Shell_Cleanup(); } } /* ================= idCommonLocal::UnloadGameDLL ================= */ void idCommonLocal::UnloadGameDLL() { // shut down the game object if ( game != NULL ) { game->Shutdown(); } #ifdef __DOOM_DLL__ if ( gameDLL ) { Sys_DLL_Unload( gameDLL ); gameDLL = NULL; } game = NULL; gameEdit = NULL; #endif } /* ================= idCommonLocal::IsInitialized ================= */ bool idCommonLocal::IsInitialized() const { return com_fullyInitialized; } //====================================================================================== /* ================= idCommonLocal::Init ================= */ void idCommonLocal::Init( int argc, const char * const * argv, const char *cmdline ) { try { // set interface pointers used by idLib idLib::sys = sys; idLib::common = common; idLib::cvarSystem = cvarSystem; idLib::fileSystem = fileSystem; // initialize idLib idLib::Init(); // clear warning buffer ClearWarnings( GAME_NAME " initialization" ); idLib::Printf( va( "Command line: %s\n", cmdline ) ); //::MessageBox( NULL, cmdline, "blah", MB_OK ); // parse command line options idCmdArgs args; if ( cmdline ) { // tokenize if the OS doesn't do it for us args.TokenizeString( cmdline, true ); argv = args.GetArgs( &argc ); } ParseCommandLine( argc, argv ); // init console command system cmdSystem->Init(); // init CVar system cvarSystem->Init(); // register all static CVars idCVar::RegisterStaticVars(); idLib::Printf( "QA Timing INIT: %06dms\n", Sys_Milliseconds() ); // print engine version Printf( "%s\n", version.string ); // initialize key input/binding, done early so bind command exists idKeyInput::Init(); // init the console so we can take prints console->Init(); // get architecture info Sys_Init(); // initialize networking Sys_InitNetworking(); // override cvars from command line StartupVariable( NULL ); consoleUsed = com_allowConsole.GetBool(); if ( Sys_AlreadyRunning() ) { Sys_Quit(); } // initialize processor specific SIMD implementation InitSIMD(); // initialize the file system fileSystem->Init(); const char * defaultLang = Sys_DefaultLanguage(); com_isJapaneseSKU = ( idStr::Icmp( defaultLang, ID_LANG_JAPANESE ) == 0 ); // Allow the system to set a default lanugage Sys_SetLanguageFromSystem(); // Pre-allocate our 20 MB save buffer here on time, instead of on-demand for each save.... saveFile.SetNameAndType( SAVEGAME_CHECKPOINT_FILENAME, SAVEGAMEFILE_BINARY ); saveFile.PreAllocate( MIN_SAVEGAME_SIZE_BYTES ); stringsFile.SetNameAndType( SAVEGAME_STRINGS_FILENAME, SAVEGAMEFILE_BINARY ); stringsFile.PreAllocate( MAX_SAVEGAME_STRING_TABLE_SIZE ); fileSystem->BeginLevelLoad( "_startup", saveFile.GetDataPtr(), saveFile.GetAllocated() ); // initialize the declaration manager declManager->Init(); // init journalling, etc eventLoop->Init(); // init the parallel job manager parallelJobManager->Init(); // exec the startup scripts cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "exec default.cfg\n" ); #ifdef CONFIG_FILE // skip the config file if "safe" is on the command line if ( !SafeMode() && !g_demoMode.GetBool() ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "exec " CONFIG_FILE "\n" ); } #endif cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "exec autoexec.cfg\n" ); // run cfg execution cmdSystem->ExecuteCommandBuffer(); // re-override anything from the config files with command line args StartupVariable( NULL ); // if any archived cvars are modified after this, we will trigger a writing of the config file cvarSystem->ClearModifiedFlags( CVAR_ARCHIVE ); // init OpenGL, which will open a window and connect sound and input hardware renderSystem->InitOpenGL(); // Support up to 2 digits after the decimal point com_engineHz_denominator = 100LL * com_engineHz.GetFloat(); com_engineHz_latched = com_engineHz.GetFloat(); // start the sound system, but don't do any hardware operations yet soundSystem->Init(); // initialize the renderSystem data structures renderSystem->Init(); whiteMaterial = declManager->FindMaterial( "_white" ); if ( idStr::Icmp( sys_lang.GetString(), ID_LANG_FRENCH ) == 0 ) { // If the user specified french, we show french no matter what SKU splashScreen = declManager->FindMaterial( "guis/assets/splash/legal_french" ); } else if ( idStr::Icmp( defaultLang, ID_LANG_FRENCH ) == 0 ) { // If the lead sku is french (ie: europe), display figs splashScreen = declManager->FindMaterial( "guis/assets/splash/legal_figs" ); } else { // Otherwise show it in english splashScreen = declManager->FindMaterial( "guis/assets/splash/legal_english" ); } const int legalMinTime = 4000; const bool showVideo = ( !com_skipIntroVideos.GetBool () && fileSystem->UsingResourceFiles() ); if ( showVideo ) { RenderBink( "video\\loadvideo.bik" ); RenderSplash(); RenderSplash(); } else { idLib::Printf( "Skipping Intro Videos!\n" ); // display the legal splash screen // No clue why we have to render this twice to show up... RenderSplash(); RenderSplash(); } int legalStartTime = Sys_Milliseconds(); declManager->Init2(); // initialize string database so we can use it for loading messages InitLanguageDict(); // spawn the game thread, even if we are going to run without SMP // one meg stack, because it can parse decls from gui surfaces (unfortunately) // use a lower priority so job threads can run on the same core gameThread.StartWorkerThread( "Game/Draw", CORE_1B, THREAD_BELOW_NORMAL, 0x100000 ); // boost this thread's priority, so it will prevent job threads from running while // the render back end still has work to do // init the user command input code usercmdGen->Init(); Sys_SetRumble( 0, 0, 0 ); // initialize the user interfaces uiManager->Init(); // startup the script debugger // DebuggerServerInit(); // load the game dll LoadGameDLL(); // On the PC touch them all so they get included in the resource build if ( !fileSystem->UsingResourceFiles() ) { declManager->FindMaterial( "guis/assets/splash/legal_english" ); declManager->FindMaterial( "guis/assets/splash/legal_french" ); declManager->FindMaterial( "guis/assets/splash/legal_figs" ); // register the japanese font so it gets included renderSystem->RegisterFont( "DFPHeiseiGothicW7" ); // Make sure all videos get touched because you can bring videos from one map to another, they need to be included in all maps for ( int i = 0; i < declManager->GetNumDecls( DECL_VIDEO ); i++ ) { declManager->DeclByIndex( DECL_VIDEO, i ); } } fileSystem->UnloadResourceContainer( "_ordered" ); // the same idRenderWorld will be used for all games // and demos, insuring that level specific models // will be freed renderWorld = renderSystem->AllocRenderWorld(); soundWorld = soundSystem->AllocSoundWorld( renderWorld ); menuSoundWorld = soundSystem->AllocSoundWorld( NULL ); menuSoundWorld->PlaceListener( vec3_origin, mat3_identity, 0 ); // init the session session->Initialize(); session->InitializeSoundRelatedSystems(); InitializeMPMapsModes(); // leaderboards need to be initialized after InitializeMPMapsModes, which populates the MP Map list. if( game != NULL ) { game->Leaderboards_Init(); } CreateMainMenu(); commonDialog.Init(); // load the console history file consoleHistory.LoadHistoryFile(); AddStartupCommands(); StartMenu( true ); while ( Sys_Milliseconds() - legalStartTime < legalMinTime ) { RenderSplash(); Sys_GenerateEvents(); Sys_Sleep( 10 ); }; // print all warnings queued during initialization PrintWarnings(); // remove any prints from the notify lines console->ClearNotifyLines(); CheckStartupStorageRequirements(); if ( preload_CommonAssets.GetBool() && fileSystem->UsingResourceFiles() ) { idPreloadManifest manifest; manifest.LoadManifest( "_common.preload" ); globalImages->Preload( manifest, false ); soundSystem->Preload( manifest ); } fileSystem->EndLevelLoad(); // Initialize support for Doom classic. doomClassicMaterial = declManager->FindMaterial( "_doomClassic" ); idImage *image = globalImages->GetImage( "_doomClassic" ); if ( image != NULL ) { idImageOpts opts; opts.format = FMT_RGBA8; opts.colorFormat = CFM_DEFAULT; opts.width = DOOMCLASSIC_RENDERWIDTH; opts.height = DOOMCLASSIC_RENDERHEIGHT; opts.numLevels = 1; image->AllocImage( opts, TF_LINEAR, TR_REPEAT ); } com_fullyInitialized = true; // No longer need the splash screen if ( splashScreen != NULL ) { for ( int i = 0; i < splashScreen->GetNumStages(); i++ ) { idImage * image = splashScreen->GetStage( i )->texture.image; if ( image != NULL ) { image->PurgeImage(); } } } Printf( "--- Common Initialization Complete ---\n" ); idLib::Printf( "QA Timing IIS: %06dms\n", Sys_Milliseconds() ); } catch( idException & ) { Sys_Error( "Error during initialization" ); } } /* ================= idCommonLocal::Shutdown ================= */ void idCommonLocal::Shutdown() { if ( com_shuttingDown ) { return; } com_shuttingDown = true; // Kill any pending saves... printf( "session->GetSaveGameManager().CancelToTerminate();\n" ); session->GetSaveGameManager().CancelToTerminate(); // kill sound first printf( "soundSystem->StopAllSounds();\n" ); soundSystem->StopAllSounds(); // shutdown the script debugger // DebuggerServerShutdown(); if ( aviCaptureMode ) { printf( "EndAVICapture();\n" ); EndAVICapture(); } printf( "Stop();\n" ); Stop(); printf( "CleanupShell();\n" ); CleanupShell(); printf( "delete loadGUI;\n" ); delete loadGUI; loadGUI = NULL; printf( "delete renderWorld;\n" ); delete renderWorld; renderWorld = NULL; printf( "delete soundWorld;\n" ); delete soundWorld; soundWorld = NULL; printf( "delete menuSoundWorld;\n" ); delete menuSoundWorld; menuSoundWorld = NULL; // shut down the session printf( "session->ShutdownSoundRelatedSystems();\n" ); session->ShutdownSoundRelatedSystems(); printf( "session->Shutdown();\n" ); session->Shutdown(); // shutdown, deallocate leaderboard definitions. if( game != NULL ) { printf( "game->Leaderboards_Shutdown();\n" ); game->Leaderboards_Shutdown(); } // shut down the user interfaces printf( "uiManager->Shutdown();\n" ); uiManager->Shutdown(); // shut down the sound system printf( "soundSystem->Shutdown();\n" ); soundSystem->Shutdown(); // shut down the user command input code printf( "usercmdGen->Shutdown();\n" ); usercmdGen->Shutdown(); // shut down the event loop printf( "eventLoop->Shutdown();\n" ); eventLoop->Shutdown(); // shutdown the decl manager printf( "declManager->Shutdown();\n" ); declManager->Shutdown(); // shut down the renderSystem printf( "renderSystem->Shutdown();\n" ); renderSystem->Shutdown(); printf( "commonDialog.Shutdown();\n" ); commonDialog.Shutdown(); // unload the game dll printf( "UnloadGameDLL();\n" ); UnloadGameDLL(); printf( "saveFile.Clear( true );\n" ); saveFile.Clear( true ); printf( "stringsFile.Clear( true );\n" ); stringsFile.Clear( true ); // only shut down the log file after all output is done printf( "CloseLogFile();\n" ); CloseLogFile(); // shut down the file system printf( "fileSystem->Shutdown( false );\n" ); fileSystem->Shutdown( false ); // shut down non-portable system services printf( "Sys_Shutdown();\n" ); Sys_Shutdown(); // shut down the console printf( "console->Shutdown();\n" ); console->Shutdown(); // shut down the key system printf( "idKeyInput::Shutdown();\n" ); idKeyInput::Shutdown(); // shut down the cvar system printf( "cvarSystem->Shutdown();\n" ); cvarSystem->Shutdown(); // shut down the console command system printf( "cmdSystem->Shutdown();\n" ); cmdSystem->Shutdown(); // free any buffered warning messages printf( "ClearWarnings( GAME_NAME \" shutdown\" );\n" ); ClearWarnings( GAME_NAME " shutdown" ); printf( "warningCaption.Clear();\n" ); warningCaption.Clear(); printf( "errorList.Clear();\n" ); errorList.Clear(); // shutdown idLib printf( "idLib::ShutDown();\n" ); idLib::ShutDown(); } /* ======================== idCommonLocal::CreateMainMenu ======================== */ void idCommonLocal::CreateMainMenu() { if ( game != NULL ) { // note which media we are going to need to load declManager->BeginLevelLoad(); renderSystem->BeginLevelLoad(); soundSystem->BeginLevelLoad(); uiManager->BeginLevelLoad(); // create main inside an "empty" game level load - so assets get // purged automagically when we transition to a "real" map game->Shell_CreateMenu( false ); game->Shell_Show( true ); game->Shell_SyncWithSession(); // load renderSystem->EndLevelLoad(); soundSystem->EndLevelLoad(); declManager->EndLevelLoad(); uiManager->EndLevelLoad( "" ); } } /* =============== idCommonLocal::Stop called on errors and game exits =============== */ void idCommonLocal::Stop( bool resetSession ) { ClearWipe(); // clear mapSpawned and demo playing flags UnloadMap(); soundSystem->StopAllSounds(); insideUpdateScreen = false; insideExecuteMapChange = false; // drop all guis ExitMenu(); if ( resetSession ) { session->QuitMatchToTitle(); } } /* =============== idCommonLocal::BusyWait =============== */ void idCommonLocal::BusyWait() { Sys_GenerateEvents(); const bool captureToImage = false; UpdateScreen( captureToImage ); session->UpdateSignInManager(); session->Pump(); } /* =============== idCommonLocal::WaitForSessionState =============== */ bool idCommonLocal::WaitForSessionState( idSession::sessionState_t desiredState ) { if ( session->GetState() == desiredState ) { return true; } while ( true ) { BusyWait(); idSession::sessionState_t sessionState = session->GetState(); if ( sessionState == desiredState ) { return true; } if ( sessionState != idSession::LOADING && sessionState != idSession::SEARCHING && sessionState != idSession::CONNECTING && sessionState != idSession::BUSY && sessionState != desiredState ) { return false; } Sys_Sleep( 10 ); } } /* ======================== idCommonLocal::LeaveGame ======================== */ void idCommonLocal::LeaveGame() { const bool captureToImage = false; UpdateScreen( captureToImage ); ResetNetworkingState(); Stop( false ); CreateMainMenu(); StartMenu(); } /* =============== idCommonLocal::ProcessEvent =============== */ bool idCommonLocal::ProcessEvent( const sysEvent_t *event ) { // hitting escape anywhere brings up the menu if ( game && game->IsInGame() ) { if ( event->evType == SE_KEY && event->evValue2 == 1 && ( event->evValue == K_ESCAPE || event->evValue == K_JOY9 ) ) { if ( !game->Shell_IsActive() ) { // menus / etc if ( MenuEvent( event ) ) { return true; } console->Close(); StartMenu(); return true; } else { console->Close(); // menus / etc if ( MenuEvent( event ) ) { return true; } game->Shell_ClosePause(); } } } // let the pull-down console take it if desired if ( console->ProcessEvent( event, false ) ) { return true; } if ( session->ProcessInputEvent( event ) ) { return true; } if ( Dialog().IsDialogActive() ) { Dialog().HandleDialogEvent( event ); return true; } // Let Doom classic run events. if ( IsPlayingDoomClassic() ) { // Translate the event to Doom classic format. event_t classicEvent; if ( event->evType == SE_KEY ) { if( event->evValue2 == 1 ) { classicEvent.type = ev_keydown; } else if( event->evValue2 == 0 ) { classicEvent.type = ev_keyup; } DoomLib::SetPlayer( 0 ); extern Globals * g; if ( g != NULL ) { classicEvent.data1 = DoomLib::RemapControl( event->GetKey() ); D_PostEvent( &classicEvent ); } DoomLib::SetPlayer( -1 ); } // Let the classics eat all events. return true; } // menus / etc if ( MenuEvent( event ) ) { return true; } // if we aren't in a game, force the console to take it if ( !mapSpawned ) { console->ProcessEvent( event, true ); return true; } // in game, exec bindings for all key downs if ( event->evType == SE_KEY && event->evValue2 == 1 ) { idKeyInput::ExecKeyBinding( event->evValue ); return true; } return false; } /* ======================== idCommonLocal::ResetPlayerInput ======================== */ void idCommonLocal::ResetPlayerInput( int playerIndex ) { userCmdMgr.ResetPlayer( playerIndex ); } /* ======================== idCommonLocal::SwitchToGame ======================== */ void idCommonLocal::SwitchToGame( currentGame_t newGame ) { idealCurrentGame = newGame; } /* ======================== idCommonLocal::PerformGameSwitch ======================== */ void idCommonLocal::PerformGameSwitch() { // If the session state is past the menu, we should be in Doom 3. // This will happen if, for example, we accept an invite while playing // Doom or Doom 2. if ( session->GetState() > idSession::IDLE ) { idealCurrentGame = DOOM3_BFG; } if ( currentGame == idealCurrentGame ) { return; } const int DOOM_CLASSIC_HZ = 35; if ( idealCurrentGame == DOOM_CLASSIC || idealCurrentGame == DOOM2_CLASSIC ) { // Pause Doom 3 sound. if ( menuSoundWorld != NULL ) { menuSoundWorld->Pause(); } DoomLib::skipToNew = false; DoomLib::skipToLoad = false; // Reset match parameters for the classics. DoomLib::matchParms = idMatchParameters(); // The classics use the usercmd manager too, clear it. userCmdMgr.SetDefaults(); // Classics need a local user too. session->UpdateSignInManager(); session->GetSignInManager().RegisterLocalUser( 0 ); com_engineHz_denominator = 100LL * DOOM_CLASSIC_HZ; com_engineHz_latched = DOOM_CLASSIC_HZ; DoomLib::SetCurrentExpansion( idealCurrentGame ); } else if ( idealCurrentGame == DOOM3_BFG ) { DoomLib::Interface.Shutdown(); com_engineHz_denominator = 100LL * com_engineHz.GetFloat(); com_engineHz_latched = com_engineHz.GetFloat(); // Don't MoveToPressStart if we have an invite, we need to go // directly to the lobby. if ( session->GetState() <= idSession::IDLE ) { session->MoveToPressStart(); } // Unpause Doom 3 sound. if ( menuSoundWorld != NULL ) { menuSoundWorld->UnPause(); } } currentGame = idealCurrentGame; } /* ================== Common_WritePrecache_f ================== */ CONSOLE_COMMAND( writePrecache, "writes precache commands", NULL ) { if ( args.Argc() != 2 ) { common->Printf( "USAGE: writePrecache <execFile>\n" ); return; } idStr str = args.Argv(1); str.DefaultFileExtension( ".cfg" ); idFile *f = fileSystem->OpenFileWrite( str ); declManager->WritePrecacheCommands( f ); renderModelManager->WritePrecacheCommands( f ); uiManager->WritePrecacheCommands( f ); fileSystem->CloseFile( f ); } /* ================ Common_Disconnect_f ================ */ CONSOLE_COMMAND_SHIP( disconnect, "disconnects from a game", NULL ) { session->QuitMatch(); } /* =============== Common_Hitch_f =============== */ CONSOLE_COMMAND( hitch, "hitches the game", NULL ) { if ( args.Argc() == 2 ) { Sys_Sleep( atoi(args.Argv(1)) ); } else { Sys_Sleep( 100 ); } } CONSOLE_COMMAND( showStringMemory, "shows memory used by strings", NULL ) { idStr::ShowMemoryUsage_f( args ); } CONSOLE_COMMAND( showDictMemory, "shows memory used by dictionaries", NULL ) { idDict::ShowMemoryUsage_f( args ); } CONSOLE_COMMAND( listDictKeys, "lists all keys used by dictionaries", NULL ) { idDict::ListKeys_f( args ); } CONSOLE_COMMAND( listDictValues, "lists all values used by dictionaries", NULL ) { idDict::ListValues_f( args ); } CONSOLE_COMMAND( testSIMD, "test SIMD code", NULL ) { idSIMD::Test_f( args ); }
0
0.91466
1
0.91466
game-dev
MEDIA
0.878173
game-dev
0.759396
1
0.759396
DK22Pac/plugin-sdk
2,924
plugin_sa/game_sa/CCullZones.cpp
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CCullZones.h" int& CCullZones::NumMirrorAttributeZones = *(int*)0xC87AC4; CCullZoneReflection(&CCullZones::aMirrorAttributeZones)[72] = *(CCullZoneReflection(*)[72])0xC815C0; int& CCullZones::NumTunnelAttributeZones = *(int*)0xC87AC0; CCullZone(&CCullZones::aTunnelAttributeZones)[40] = *(CCullZone(*)[40])0xC81C80; int& CCullZones::NumAttributeZones = *(int*)0xC87AC8; CCullZone(&CCullZones::aAttributeZones)[1300] = *(CCullZone(*)[1300])0xC81F50; int& CCullZones::CurrentFlags_Player = *(int*)0xC87AB8; int& CCullZones::CurrentFlags_Camera = *(int*)0xC87ABC; bool& CCullZones::bMilitaryZonesDisabled = *(bool*)0xC87ACD; bool CZoneDef::IsPointWithin(const CVector& point) { return plugin::CallMethodAndReturn<bool, 0x72D850>(this, point); } void CCullZones::Init() { plugin::Call<0x72D6B0>(); } void CCullZones::Update() { plugin::Call<0x72DEC0>(); } void CCullZones::AddCullZone(const CVector& center, float unk1, float fWidthY, float fBottomZ, float fWidthX, float unk2, float fTopZ, ushort flags) { plugin::Call<0x72DF70>(); } void CCullZones::AddTunnelAttributeZone(const CVector& center, float unk1, float fWidthY, float fBottomZ, float fWidthX, float unk2, float fTopZ, ushort flags) { plugin::Call<0x72DB50>(); } void CCullZones::AddMirrorAttributeZone(const CVector& center, float unk1, float fWidthY, float fBottomZ, float fWidthX, float unk2, float fTopZ, eZoneAttributes flags, float cm, float vX, float vY, float vZ) { plugin::Call<0x72DC10>(); } bool CCullZones::InRoomForAudio() { return plugin::CallAndReturn<bool, 0x72DD70>(); } bool CCullZones::FewerCars() { return plugin::CallAndReturn<bool, 0x72DD80>(); } bool CCullZones::CamNoRain() { return plugin::CallAndReturn<bool, 0x72DDB0>(); } bool CCullZones::PlayerNoRain() { return plugin::CallAndReturn<bool, 0x72DDC0>(); } bool CCullZones::FewerPeds() { return plugin::CallAndReturn<bool, 0x72DD90>(); } bool CCullZones::NoPolice() { return plugin::CallAndReturn<bool, 0x72DD50>(); } bool CCullZones::DoExtraAirResistanceForPlayer() { return plugin::CallAndReturn<bool, 0x72DDD0>(); } eZoneAttributes CCullZones::FindTunnelAttributesForCoors(CVector point) { return plugin::CallAndReturn<eZoneAttributes, 0x72D9F0>(point); } CCullZoneReflection* CCullZones::FindMirrorAttributesForCoors(CVector cameraPosition) { return plugin::CallAndReturn<CCullZoneReflection*, 0x72DA70>(cameraPosition); } CCullZone* CCullZones::FindZoneWithStairsAttributeForPlayer() { return plugin::CallAndReturn<CCullZone*, 0x72DAD0>(); } eZoneAttributes CCullZones::FindAttributesForCoors(CVector pos) { return plugin::CallAndReturn<eZoneAttributes, 0x72D970>(pos); }
0
0.500523
1
0.500523
game-dev
MEDIA
0.735233
game-dev
0.589076
1
0.589076
mcclure/bitbucket-backup
4,378
repos/jpeg/contents/desktop/static_lib/constraints/util.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. */ #define CP_DefineClassGetter(t) const cpConstraintClass * t##GetClass(){return (cpConstraintClass *)&klass;} void cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *klass, cpBody *a, cpBody *b); #define J_MAX(constraint, dt) (((cpConstraint *)constraint)->maxForce*(dt)) // Get valid body pointers and exit early if the bodies are idle #define CONSTRAINT_BEGIN(constraint, a_var, b_var) \ cpBody *a_var, *b_var; { \ a_var = ((cpConstraint *)constraint)->a; \ b_var = ((cpConstraint *)constraint)->b; \ if( \ (cpBodyIsSleeping(a_var) || cpBodyIsStatic(a_var)) && \ (cpBodyIsSleeping(b_var) || cpBodyIsStatic(b_var)) \ ) return; \ } static inline cpVect relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2){ cpVect v1_sum = cpvadd(a->v, cpvmult(cpvperp(r1), a->w)); cpVect v2_sum = cpvadd(b->v, cpvmult(cpvperp(r2), b->w)); return cpvsub(v2_sum, v1_sum); } static inline cpFloat normal_relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n){ return cpvdot(relative_velocity(a, b, r1, r2), n); } static inline void apply_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j) { cpBodyApplyImpulse(a, cpvneg(j), r1); cpBodyApplyImpulse(b, j, r2); } static inline void apply_bias_impulse(cpBody *body, cpVect j, cpVect r) { body->v_bias = cpvadd(body->v_bias, cpvmult(j, body->m_inv)); body->w_bias += body->i_inv*cpvcross(r, j); } static inline void apply_bias_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j) { apply_bias_impulse(a, cpvneg(j), r1); apply_bias_impulse(b, j, r2); } static inline cpVect clamp_vect(cpVect v, cpFloat len) { return cpvclamp(v, len); // return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v; } static inline cpFloat k_scalar(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n) { cpFloat mass_sum = a->m_inv + b->m_inv; cpFloat r1cn = cpvcross(r1, n); cpFloat r2cn = cpvcross(r2, n); cpFloat value = mass_sum + a->i_inv*r1cn*r1cn + b->i_inv*r2cn*r2cn; cpAssert(value != 0.0, "Unsolvable collision or constraint."); return value; } static inline void k_tensor(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect *k1, cpVect *k2) { // calculate mass matrix // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross... cpFloat k11, k12, k21, k22; cpFloat m_sum = a->m_inv + b->m_inv; // start with I*m_sum k11 = m_sum; k12 = 0.0f; k21 = 0.0f; k22 = m_sum; // add the influence from r1 cpFloat a_i_inv = a->i_inv; cpFloat r1xsq = r1.x * r1.x * a_i_inv; cpFloat r1ysq = r1.y * r1.y * a_i_inv; cpFloat r1nxy = -r1.x * r1.y * a_i_inv; k11 += r1ysq; k12 += r1nxy; k21 += r1nxy; k22 += r1xsq; // add the influnce from r2 cpFloat b_i_inv = b->i_inv; cpFloat r2xsq = r2.x * r2.x * b_i_inv; cpFloat r2ysq = r2.y * r2.y * b_i_inv; cpFloat r2nxy = -r2.x * r2.y * b_i_inv; k11 += r2ysq; k12 += r2nxy; k21 += r2nxy; k22 += r2xsq; // invert cpFloat determinant = k11*k22 - k12*k21; cpAssert(determinant != 0.0, "Unsolvable constraint."); cpFloat det_inv = 1.0f/determinant; *k1 = cpv( k22*det_inv, -k12*det_inv); *k2 = cpv(-k21*det_inv, k11*det_inv); } static inline cpVect mult_k(cpVect vr, cpVect k1, cpVect k2) { return cpv(cpvdot(vr, k1), cpvdot(vr, k2)); }
0
0.929669
1
0.929669
game-dev
MEDIA
0.751696
game-dev
0.962576
1
0.962576
steipete/AXorcist
9,909
Sources/AXorcist/Core/CommandEnvelope.swift
// CommandEnvelope.swift - Main command envelope structure import CoreGraphics // For CGPoint import Foundation /// The main command envelope structure for AXorcist operations. /// /// CommandEnvelope wraps all the information needed to execute an accessibility /// command, including the command type, target application, parameters, and options. /// It serves as the primary interface for all AXorcist operations. /// /// ## Topics /// /// ### Core Properties /// - ``commandId`` /// - ``command`` /// - ``application`` /// /// ### Command Parameters /// - ``attributes`` /// - ``locator`` /// - ``maxElements`` /// - ``maxDepth`` /// /// ### Action Parameters /// - ``actionName`` /// - ``actionValue`` /// - ``point`` /// - ``pid`` /// /// ### Batch Operations /// - ``subCommands`` /// /// ### Observation /// - ``notifications`` /// - ``includeElementDetails`` /// - ``watchChildren`` /// /// ## Usage /// /// ```swift /// let command = CommandEnvelope( /// commandId: "find-button", /// command: .query, /// application: "MyApp", /// locator: Locator(role: "button", title: "OK") /// ) /// let response = axorcist.runCommand(command) /// ``` public struct CommandEnvelope: Codable { // MARK: Lifecycle public init(commandId: String, command: CommandType, application: String? = nil, attributes: [String]? = nil, payload: [String: String]? = nil, debugLogging: Bool = false, locator: Locator? = nil, pathHint: [String]? = nil, maxElements: Int? = nil, maxDepth: Int? = nil, outputFormat: OutputFormat? = nil, actionName: String? = nil, actionValue: AnyCodable? = nil, subCommands: [CommandEnvelope]? = nil, point: CGPoint? = nil, pid: Int? = nil, notifications: [String]? = nil, includeElementDetails: [String]? = nil, watchChildren: Bool? = nil, filterCriteria: [String: String]? = nil, includeChildrenBrief: Bool? = nil, includeChildrenInText: Bool? = nil, includeIgnoredElements: Bool? = nil) { self.commandId = commandId self.command = command self.application = application self.attributes = attributes self.payload = payload self.debugLogging = debugLogging self.locator = locator self.pathHint = pathHint self.maxElements = maxElements self.maxDepth = maxDepth self.outputFormat = outputFormat self.actionName = actionName self.actionValue = actionValue self.subCommands = subCommands self.point = point self.pid = pid self.notifications = notifications self.includeElementDetails = includeElementDetails self.watchChildren = watchChildren self.filterCriteria = filterCriteria self.includeChildrenBrief = includeChildrenBrief self.includeChildrenInText = includeChildrenInText self.includeIgnoredElements = includeIgnoredElements } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) commandId = try container.decode(String.self, forKey: .commandId) command = try container.decode(CommandType.self, forKey: .command) application = try container.decodeIfPresent(String.self, forKey: .application) attributes = try container.decodeIfPresent([String].self, forKey: .attributes) payload = try container.decodeIfPresent([String: String].self, forKey: .payload) debugLogging = try container.decodeIfPresent(Bool.self, forKey: .debugLogging) ?? false locator = try container.decodeIfPresent(Locator.self, forKey: .locator) pathHint = try container.decodeIfPresent([String].self, forKey: .pathHint) maxElements = try container.decodeIfPresent(Int.self, forKey: .maxElements) maxDepth = try container.decodeIfPresent(Int.self, forKey: .maxDepth) outputFormat = try container.decodeIfPresent(OutputFormat.self, forKey: .outputFormat) actionName = try container.decodeIfPresent(String.self, forKey: .actionName) actionValue = try container.decodeIfPresent(AnyCodable.self, forKey: .actionValue) subCommands = try container.decodeIfPresent([CommandEnvelope].self, forKey: .subCommands) point = try container.decodeIfPresent(CGPoint.self, forKey: .point) pid = try container.decodeIfPresent(Int.self, forKey: .pid) notifications = try container.decodeIfPresent([String].self, forKey: .notifications) includeElementDetails = try container.decodeIfPresent([String].self, forKey: .includeElementDetails) watchChildren = try container.decodeIfPresent(Bool.self, forKey: .watchChildren) filterCriteria = try container.decodeIfPresent([String: String].self, forKey: .filterCriteria) includeChildrenBrief = try container.decodeIfPresent(Bool.self, forKey: .includeChildrenBrief) includeChildrenInText = try container.decodeIfPresent(Bool.self, forKey: .includeChildrenInText) includeIgnoredElements = try container.decodeIfPresent(Bool.self, forKey: .includeIgnoredElements) } // MARK: Public /// Unique identifier for this command execution. /// /// This ID is used for tracking and correlating commands with their responses, /// especially useful in batch operations or asynchronous processing. public let commandId: String /// The type of command to execute. /// /// Determines what operation will be performed (query, action, observation, etc.). public let command: CommandType /// Target application name or bundle identifier. /// /// Specifies which application the command should operate on. Can be an /// application name like "Safari" or a bundle identifier like "com.apple.Safari". public let application: String? /// Specific attributes to retrieve or filter by. /// /// When provided, limits the operation to only the specified accessibility attributes. public let attributes: [String]? /// Key-value payload for compatibility with ping operations. public let payload: [String: String]? /// Whether to enable debug logging for this command. public let debugLogging: Bool /// Element locator specifying how to find the target element. /// /// Provides search criteria for identifying specific UI elements within the application. public let locator: Locator? /// Legacy path hint for element location (deprecated). /// /// > Important: Use ``locator`` instead of this property for new code. public let pathHint: [String]? /// Maximum number of elements to return in search results. public let maxElements: Int? /// Maximum depth for hierarchical searches. /// /// Controls how deep into the UI element tree the search should traverse. public let maxDepth: Int? /// Output format for the command response. public let outputFormat: OutputFormat? /// Name of the action to perform for action commands. /// /// Examples: "AXPress", "AXShowMenu", "AXScrollToVisible" public let actionName: String? /// Value parameter for action commands. /// /// Some actions require additional parameters (e.g., scroll amount, text to enter). public let actionValue: AnyCodable? /// Sub-commands for batch operations. /// /// When present, this command represents a batch operation containing /// multiple individual commands to execute in sequence. public let subCommands: [CommandEnvelope]? /// Screen coordinates for point-based operations. /// /// Used with commands that need to interact with elements at specific screen locations. public let point: CGPoint? /// Process ID for targeting specific application instances. /// /// When multiple instances of an application are running, this specifies /// which instance to target. public let pid: Int? // MARK: - Observation Parameters /// Notification types to observe for observation commands. /// /// List of accessibility notification names to monitor (e.g., "AXValueChanged"). public let notifications: [String]? /// Element details to include in observation notifications. /// /// Specifies which element attributes should be included when notifications are triggered. public let includeElementDetails: [String]? /// Whether to monitor child elements for notifications. /// /// When true, notifications from child elements will also be captured. public let watchChildren: Bool? // New field for collectAll filtering public let filterCriteria: [String: String]? // Additional fields for various commands public let includeChildrenBrief: Bool? public let includeChildrenInText: Bool? public let includeIgnoredElements: Bool? // MARK: Internal enum CodingKeys: String, CodingKey { case commandId case command case application case attributes case payload case debugLogging case locator case pathHint case maxElements case maxDepth case outputFormat case actionName case actionValue case subCommands case point case pid // CodingKeys for observe parameters case notifications case includeElementDetails case watchChildren // CodingKey for new field case filterCriteria // Additional CodingKeys case includeChildrenBrief case includeChildrenInText case includeIgnoredElements } }
0
0.911939
1
0.911939
game-dev
MEDIA
0.325745
game-dev
0.947148
1
0.947148
FishRPG/FishRPG-public
3,423
RPG-Lobby/src/main/java/me/acraftingfish/mcrpglobby/entrance/EntranceManager.java
package me.acraftingfish.mcrpglobby.entrance; import com.marcusslover.plus.lib.sound.Note; import com.marcusslover.plus.lib.title.Title; import me.acraftingfish.api.data.xdata.data.user.ServerRank; import me.acraftingfish.fishmcutils.BoundingBox; import me.acraftingfish.fishmcutils.CooldownUtil; import me.acraftingfish.mcrpglobby.MCRPGLobby; import me.acraftingfish.mcrpglobby.bungee.MessageManager; import me.acraftingfish.mcrpglobby.menu.MenuRegistry; import me.acraftingfish.mcrpglobby.menu.custom.ClassSelectionMenuOld; import me.acraftingfish.mcrpglobby.util.MCText; import me.acraftingfish.mcrpglobby.util.PlayerMemory; import me.acraftingfish.mcrpglobby.util.RankUtil; import me.acraftingfish.mcrpglobby.util.Texts; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; public class EntranceManager { private static EntranceManager instance; private final BoundingBox ENTRANCE_BOX = new BoundingBox( new Vector(2, 4, -13), new Vector(-2, 8, -17) ); private EntranceManager(){ instance = this; } public static EntranceManager get(){ return instance == null ? new EntranceManager() : instance; } public void tick(@NotNull Player player){ if(ENTRANCE_BOX.isInBox(player.getLocation())){ PlayerMemory memory = PlayerMemory.of(player); if(memory.isInClassSelection()) return; //ClassSelectionMenuOld menu = MCRPGLobby.getInstance().getMenuManager().get(ClassSelectionMenuOld.class); //if(menu.getMenuAdapters().containsKey(player.getUniqueId())) return; if(memory.isEnteringMain()) return; /*if(player.getResourcePackStatus() == null){ if(!CooldownUtil.get().isOnCooldown(player, "kickout", 500)){ player.setVelocity(new Vector(0, 0.75, 1.5)); Note.of(Sound.BLOCK_ANVIL_PLACE, 0.4f, 1f).play(player); Texts.subtitle(player, "&cYou have the resource pack to play!", 0, 20, 3); } return; }*/ if(memory.getSelectedProfile() == null){ if(!CooldownUtil.get().isOnCooldown(player, "kickout", 500)){ player.setVelocity(new Vector(0, 0.75, 1.5)); Note.of(Sound.ENTITY_IRON_GOLEM_ATTACK, 0.4f, 1f).send(player); Texts.subtitle(player, "&cYou must select a profile!", 0, 20, 3); } return; } if(memory.isSelectedProfileExists()){ memory.setEnteringMain(true); Title.of(MCText.ofText("c")).times(20, 200, 20).send(player); player.getInventory().clear(); player.closeInventory(); new BukkitRunnable() { @Override public void run() { MessageManager.get().send(player, memory.prefOrNull(), getPriority(player)); } }.runTaskLater(MCRPGLobby.getInstance(), 30); return; } MenuRegistry.SELECTION.send(player); } } private int getPriority(@NotNull Player player) { return RankUtil.hasRank(player, ServerRank.ALPHA_TESTER) ? 2 : 0; } }
0
0.918737
1
0.918737
game-dev
MEDIA
0.891312
game-dev
0.991979
1
0.991979
Lyall/ClairObscurFix
16,305
src/SDK/ABP_PostProcess_Short_Hair_structs.hpp
#pragma once /* * SDK generated by Dumper-7 * * https://github.com/Encryqed/Dumper-7 */ // Package: ABP_PostProcess_Short_Hair #include "Basic.hpp" #include "Engine_structs.hpp" namespace SDK { // ScriptStruct ABP_PostProcess_Short_Hair.ABP_PostProcess_Short_Hair_C.AnimBlueprintGeneratedConstantData // 0x075F (0x0760 - 0x0001) struct ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData final : public FAnimBlueprintConstantData { public: uint8 Pad_1[0x7]; // 0x0001(0x0007)(Fixing Size After Last Property [ Dumper-7 ]) struct FAnimNodeFunctionRef __StructProperty_103; // 0x0008(0x0020)(BlueprintVisible, NoDestructor) class FName __NameProperty_104; // 0x0028(0x0008)(BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class FName __NameProperty_105; // 0x0030(0x0008)(BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FAnimSubsystem_PropertyAccess AnimBlueprintExtension_PropertyAccess; // 0x0038(0x0080)() struct FAnimSubsystem_Base AnimBlueprintExtension_Base; // 0x00B8(0x0018)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_ComponentToLocalSpace; // 0x00D0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_LinkedInputPose; // 0x0100(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_LocalToComponentSpace; // 0x0130(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_30; // 0x0160(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_29; // 0x0190(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_28; // 0x01C0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_27; // 0x01F0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_26; // 0x0220(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_25; // 0x0250(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_24; // 0x0280(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_23; // 0x02B0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_22; // 0x02E0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_21; // 0x0310(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_20; // 0x0340(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_19; // 0x0370(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_18; // 0x03A0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_17; // 0x03D0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_16; // 0x0400(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_15; // 0x0430(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_14; // 0x0460(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_13; // 0x0490(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_12; // 0x04C0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_11; // 0x04F0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_10; // 0x0520(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_9; // 0x0550(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_8; // 0x0580(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_7; // 0x05B0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_6; // 0x05E0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_5; // 0x0610(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_4; // 0x0640(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_3; // 0x0670(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_2; // 0x06A0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics_1; // 0x06D0(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_KawaiiPhysics; // 0x0700(0x0030)() struct FAnimNodeExposedValueHandler_PropertyAccess AnimGraphNode_Root; // 0x0730(0x0030)() }; static_assert(alignof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData) == 0x000008, "Wrong alignment on ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData"); static_assert(sizeof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData) == 0x000760, "Wrong size on ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, __StructProperty_103) == 0x000008, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::__StructProperty_103' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, __NameProperty_104) == 0x000028, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::__NameProperty_104' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, __NameProperty_105) == 0x000030, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::__NameProperty_105' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimBlueprintExtension_PropertyAccess) == 0x000038, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimBlueprintExtension_PropertyAccess' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimBlueprintExtension_Base) == 0x0000B8, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimBlueprintExtension_Base' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_ComponentToLocalSpace) == 0x0000D0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_ComponentToLocalSpace' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_LinkedInputPose) == 0x000100, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_LinkedInputPose' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_LocalToComponentSpace) == 0x000130, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_LocalToComponentSpace' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_30) == 0x000160, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_30' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_29) == 0x000190, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_29' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_28) == 0x0001C0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_28' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_27) == 0x0001F0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_27' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_26) == 0x000220, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_26' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_25) == 0x000250, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_25' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_24) == 0x000280, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_24' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_23) == 0x0002B0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_23' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_22) == 0x0002E0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_22' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_21) == 0x000310, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_21' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_20) == 0x000340, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_20' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_19) == 0x000370, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_19' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_18) == 0x0003A0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_18' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_17) == 0x0003D0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_17' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_16) == 0x000400, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_16' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_15) == 0x000430, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_15' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_14) == 0x000460, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_14' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_13) == 0x000490, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_13' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_12) == 0x0004C0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_12' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_11) == 0x0004F0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_11' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_10) == 0x000520, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_10' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_9) == 0x000550, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_9' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_8) == 0x000580, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_8' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_7) == 0x0005B0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_7' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_6) == 0x0005E0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_6' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_5) == 0x000610, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_5' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_4) == 0x000640, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_4' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_3) == 0x000670, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_3' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_2) == 0x0006A0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_2' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics_1) == 0x0006D0, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics_1' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_KawaiiPhysics) == 0x000700, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_KawaiiPhysics' has a wrong offset!"); static_assert(offsetof(ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData, AnimGraphNode_Root) == 0x000730, "Member 'ABP_PostProcess_Short_Hair::FAnimBlueprintGeneratedConstantData::AnimGraphNode_Root' has a wrong offset!"); }
0
0.753007
1
0.753007
game-dev
MEDIA
0.859442
game-dev
0.755737
1
0.755737
oot-pc-port/oot-pc-port
2,816
asm/non_matchings/overlays/actors/ovl_En_Dog/func_809FB3AC.s
glabel func_809FB3AC /* 003DC 809FB3AC 27BDFFD0 */ addiu $sp, $sp, 0xFFD0 ## $sp = FFFFFFD0 /* 003E0 809FB3B0 AFBF0024 */ sw $ra, 0x0024($sp) /* 003E4 809FB3B4 AFB00020 */ sw $s0, 0x0020($sp) /* 003E8 809FB3B8 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 003EC 809FB3BC AFA50034 */ sw $a1, 0x0034($sp) /* 003F0 809FB3C0 860601E6 */ lh $a2, 0x01E6($s0) ## 000001E6 /* 003F4 809FB3C4 8E0501E0 */ lw $a1, 0x01E0($s0) ## 000001E0 /* 003F8 809FB3C8 0C023948 */ jal func_8008E520 /* 003FC 809FB3CC 27A7002E */ addiu $a3, $sp, 0x002E ## $a3 = FFFFFFFE /* 00400 809FB3D0 240E0001 */ addiu $t6, $zero, 0x0001 ## $t6 = 00000001 /* 00404 809FB3D4 AFAE0010 */ sw $t6, 0x0010($sp) /* 00408 809FB3D8 26040032 */ addiu $a0, $s0, 0x0032 ## $a0 = 00000032 /* 0040C 809FB3DC 87A5002E */ lh $a1, 0x002E($sp) /* 00410 809FB3E0 2406000A */ addiu $a2, $zero, 0x000A ## $a2 = 0000000A /* 00414 809FB3E4 240703E8 */ addiu $a3, $zero, 0x03E8 ## $a3 = 000003E8 /* 00418 809FB3E8 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 0041C 809FB3EC E7A00028 */ swc1 $f0, 0x0028($sp) /* 00420 809FB3F0 C7A20028 */ lwc1 $f2, 0x0028($sp) /* 00424 809FB3F4 44802000 */ mtc1 $zero, $f4 ## $f4 = 0.00 /* 00428 809FB3F8 3C01447A */ lui $at, 0x447A ## $at = 447A0000 /* 0042C 809FB3FC 00001025 */ or $v0, $zero, $zero ## $v0 = 00000000 /* 00430 809FB400 4602203C */ c.lt.s $f4, $f2 /* 00434 809FB404 00000000 */ nop /* 00438 809FB408 4500000B */ bc1f .L809FB438 /* 0043C 809FB40C 00000000 */ nop /* 00440 809FB410 44813000 */ mtc1 $at, $f6 ## $f6 = 1000.00 /* 00444 809FB414 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 00448 809FB418 4606103C */ c.lt.s $f2, $f6 /* 0044C 809FB41C 00000000 */ nop /* 00450 809FB420 45000005 */ bc1f .L809FB438 /* 00454 809FB424 00000000 */ nop /* 00458 809FB428 0C27ECC8 */ jal func_809FB320 /* 0045C 809FB42C 8FA50034 */ lw $a1, 0x0034($sp) /* 00460 809FB430 10000002 */ beq $zero, $zero, .L809FB43C /* 00464 809FB434 8FBF0024 */ lw $ra, 0x0024($sp) .L809FB438: /* 00468 809FB438 8FBF0024 */ lw $ra, 0x0024($sp) .L809FB43C: /* 0046C 809FB43C 8FB00020 */ lw $s0, 0x0020($sp) /* 00470 809FB440 27BD0030 */ addiu $sp, $sp, 0x0030 ## $sp = 00000000 /* 00474 809FB444 03E00008 */ jr $ra /* 00478 809FB448 00000000 */ nop
0
0.620262
1
0.620262
game-dev
MEDIA
0.955669
game-dev
0.526584
1
0.526584
albin-johansson/tactile
6,199
source/app/core/layer/tile_layer.cpp
/* * This source file is a part of the Tactile map editor. * * Copyright (C) 2022 Albin Johansson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "tile_layer.hpp" #include <queue> // queue #include <utility> // move #include "core/common/functional.hpp" #include "core/common/math.hpp" #include "core/ctx/context_visitor.hpp" #include "core/layer/layer_visitor.hpp" #include "core/tile_pos.hpp" #include "core/util/tiles.hpp" #include "misc/assert.hpp" #include "misc/panic.hpp" namespace tactile { TileLayer::TileLayer() : TileLayer {5, 5} {} TileLayer::TileLayer(const usize rows, const usize columns) : mTiles {make_tile_matrix(rows, columns)} {} auto TileLayer::make() -> Shared<TileLayer> { return std::make_shared<TileLayer>(); } auto TileLayer::make(const usize rows, const usize columns) -> Shared<TileLayer> { return std::make_shared<TileLayer>(rows, columns); } void TileLayer::accept(ILayerVisitor& visitor) { visitor.visit(*this); } void TileLayer::accept(IConstLayerVisitor& visitor) const { visitor.visit(*this); } void TileLayer::flood(const TilePos& origin, const TileID replacement, std::vector<TilePos>* affected) { const auto target = tile_at(origin); if (!is_valid(origin) || (target == replacement)) { return; } std::queue<TilePos> positions; positions.push(origin); set_tile(origin, replacement); if (affected) { affected->push_back(origin); } /* Determines whether a position should be flooded */ auto check = [&](const TilePos& position) { if (is_valid(position)) { const auto tile = tile_at(position); if (tile == target) { set_tile(position, replacement); if (affected) { affected->push_back(position); } positions.push(position); } } }; while (!positions.empty()) { const auto position = positions.front(); positions.pop(); check(position.west()); check(position.east()); check(position.south()); check(position.north()); } } void TileLayer::add_row() { mTiles.push_back(make_tile_row(column_count())); } void TileLayer::add_column() { for (auto& row : mTiles) { row.push_back(empty_tile); } } void TileLayer::remove_row() { TACTILE_ASSERT(row_count() > 1); mTiles.pop_back(); } void TileLayer::remove_column() { for (auto& row : mTiles) { TACTILE_ASSERT(row.size() > 1); row.pop_back(); } } void TileLayer::resize(const usize rows, const usize columns) { const auto currentRows = row_count(); const auto currentCols = column_count(); if (const auto n = udiff(currentRows, rows); currentRows < rows) { invoke_n(n, [this] { add_row(); }); } else { invoke_n(n, [this] { remove_row(); }); } if (const auto n = udiff(currentCols, columns); currentCols < columns) { invoke_n(n, [this] { add_column(); }); } else { invoke_n(n, [this] { remove_column(); }); } } void TileLayer::set_opacity(const float opacity) { mDelegate.set_opacity(opacity); } void TileLayer::set_visible(const bool visible) { mDelegate.set_visible(visible); } void TileLayer::set_parent(const Maybe<UUID>& parentId) { mDelegate.set_parent(parentId); } void TileLayer::set_meta_id(const int32 id) { mDelegate.set_meta_id(id); } void TileLayer::accept(IContextVisitor& visitor) const { visitor.visit(*this); } void TileLayer::set_name(std::string name) { mDelegate.set_name(std::move(name)); } void TileLayer::set_tile(const TilePos& pos, const TileID id) { if (is_valid(pos)) [[likely]] { mTiles[pos.urow()][pos.ucol()] = id; } else { throw TactileError {"Invalid position!"}; } } void TileLayer::set_tiles(const TileCache& cache) { for (const auto& [pos, tile] : cache) { set_tile(pos, tile); } } auto TileLayer::tile_at(const TilePos& pos) const -> TileID { if (is_valid(pos)) [[likely]] { return mTiles[pos.urow()][pos.ucol()]; } else { throw TactileError {"Invalid position!"}; } } auto TileLayer::is_valid(const TilePos& pos) const -> bool { return pos.row() >= 0 && // pos.col() >= 0 && // pos.urow() < row_count() && // pos.ucol() < column_count(); } auto TileLayer::row_count() const -> usize { return mTiles.size(); } auto TileLayer::column_count() const -> usize { TACTILE_ASSERT(mTiles.size() > 0); return mTiles.at(0).size(); } auto TileLayer::get_tiles() const -> const TileMatrix& { return mTiles; } auto TileLayer::get_opacity() const -> float { return mDelegate.get_opacity(); } auto TileLayer::is_visible() const -> bool { return mDelegate.is_visible(); } auto TileLayer::clone() const -> Shared<ILayer> { auto layer = make(); layer->mDelegate = mDelegate.clone(); layer->mTiles = mTiles; return layer; } auto TileLayer::get_uuid() const -> const UUID& { return mDelegate.get_uuid(); } auto TileLayer::get_name() const -> const std::string& { return mDelegate.get_name(); } auto TileLayer::get_props() -> PropertyBundle& { return mDelegate.get_props(); } auto TileLayer::get_props() const -> const PropertyBundle& { return mDelegate.get_props(); } auto TileLayer::get_comps() -> ComponentBundle& { return mDelegate.get_comps(); } auto TileLayer::get_comps() const -> const ComponentBundle& { return mDelegate.get_comps(); } auto TileLayer::get_parent() const -> Maybe<UUID> { return mDelegate.get_parent(); } auto TileLayer::get_meta_id() const -> Maybe<int32> { return mDelegate.get_meta_id(); } } // namespace tactile
0
0.952093
1
0.952093
game-dev
MEDIA
0.476422
game-dev,desktop-app
0.902924
1
0.902924
GNOME/gnome-shell
9,337
js/ui/grabHelper.js
import Clutter from 'gi://Clutter'; import St from 'gi://St'; import * as Main from './main.js'; import * as Params from '../misc/params.js'; /** * GrabHelper: * * Creates a new GrabHelper object, for dealing with keyboard and pointer grabs * associated with a set of actors. * * Note that the grab can be automatically dropped at any time by the user, and * your code just needs to deal with it; you shouldn't adjust behavior directly * after you call ungrab(), but instead pass an 'onUngrab' callback when you * call grab(). */ export class GrabHelper { /** * @param {Clutter.Actor} owner the actor that owns the GrabHelper * @param {*} params optional parameters to pass to Main.pushModal() */ constructor(owner, params) { if (!(owner instanceof Clutter.Actor)) throw new Error('GrabHelper owner must be a Clutter.Actor'); this._owner = owner; this._modalParams = params; this._grabStack = []; this._ignoreUntilRelease = false; this._modalCount = 0; } _isWithinGrabbedActor(actor) { let currentActor = this.currentGrab.actor; while (actor) { if (actor === currentActor) return true; actor = actor.get_parent(); } return false; } get currentGrab() { return this._grabStack[this._grabStack.length - 1] || {}; } get grabbed() { return this._grabStack.length > 0; } get grabStack() { return this._grabStack; } _findStackIndex(actor) { if (!actor) return -1; for (let i = 0; i < this._grabStack.length; i++) { if (this._grabStack[i].actor === actor) return i; } return -1; } _actorInGrabStack(actor) { while (actor) { let idx = this._findStackIndex(actor); if (idx >= 0) return idx; actor = actor.get_parent(); } return -1; } isActorGrabbed(actor) { return this._findStackIndex(actor) >= 0; } // grab: // @params: A bunch of parameters, see below // // The general effect of a "grab" is to ensure that the passed in actor // and all actors inside the grab get exclusive control of the mouse and // keyboard, with the grab automatically being dropped if the user tries // to dismiss it. The actor is passed in through @params.actor. // // grab() can be called multiple times, with the scope of the grab being // changed to a different actor every time. A nested grab does not have // to have its grabbed actor inside the parent grab actors. // // Grabs can be automatically dropped if the user tries to dismiss it // in one of two ways: the user clicking outside the currently grabbed // actor, or the user typing the Escape key. // // If the user clicks outside the grabbed actors, and the clicked on // actor is part of a previous grab in the stack, grabs will be popped // until that grab is active. However, the click event will not be // replayed to the actor. // // If the user types the Escape key, one grab from the grab stack will // be popped. // // When a grab is popped by user interacting as described above, if you // pass a callback as @params.onUngrab, it will be called with %true. // // If @params.focus is not null, we'll set the key focus directly // to that actor instead of navigating in @params.actor. This is for // use cases like menus, where we want to grab the menu actor, but keep // focus on the clicked on menu item. grab(params) { params = Params.parse(params, { actor: null, focus: null, onUngrab: null, }); let focus = global.stage.key_focus; let hadFocus = focus && this._isWithinGrabbedActor(focus); let newFocus = params.actor; if (this.isActorGrabbed(params.actor)) return true; params.savedFocus = focus; if (!this._takeModalGrab()) return false; this._grabStack.push(params); if (params.focus) { params.focus.grab_key_focus(); } else if (newFocus && hadFocus) { if (!newFocus.navigate_focus(null, St.DirectionType.TAB_FORWARD, false)) newFocus.grab_key_focus(); } return true; } grabAsync(params) { return new Promise((resolve, reject) => { params.onUngrab = resolve; if (!this.grab(params)) reject(new Error('Grab failed')); }); } _takeModalGrab() { let firstGrab = this._modalCount === 0; if (firstGrab) { let grab = Main.pushModal(this._owner, this._modalParams); if (grab.get_seat_state() !== Clutter.GrabState.ALL) { Main.popModal(grab); return false; } this._grab = grab; this._capturedEventId = this._owner.connect('captured-event', (actor, event) => { return this.onCapturedEvent(event); }); } this._modalCount++; return true; } _releaseModalGrab() { this._modalCount--; if (this._modalCount > 0) return; this._owner.disconnect(this._capturedEventId); this._ignoreUntilRelease = false; Main.popModal(this._grab); this._grab = null; } // ignoreRelease: // // Make sure that the next button release event evaluated by the // capture event handler returns false. This is designed for things // like the ComboBoxMenu that go away on press, but need to eat // the next release event. ignoreRelease() { this._ignoreUntilRelease = true; } // ungrab: // @params: The parameters for the grab; see below. // // Pops @params.actor from the grab stack, potentially dropping // the grab. If the actor is not on the grab stack, this call is // ignored with no ill effects. // // If the actor is not at the top of the grab stack, grabs are // popped until the grabbed actor is at the top of the grab stack. // The onUngrab callback for every grab is called for every popped // grab with the parameter %false. ungrab(params) { params = Params.parse(params, { actor: this.currentGrab.actor, isUser: false, }); let grabStackIndex = this._findStackIndex(params.actor); if (grabStackIndex < 0) return; let focus = global.stage.key_focus; let hadFocus = focus && this._isWithinGrabbedActor(focus); let poppedGrabs = this._grabStack.slice(grabStackIndex); // "Pop" all newly ungrabbed actors off the grab stack // by truncating the array. this._grabStack.length = grabStackIndex; for (let i = poppedGrabs.length - 1; i >= 0; i--) { let poppedGrab = poppedGrabs[i]; if (poppedGrab.onUngrab) poppedGrab.onUngrab(params.isUser); this._releaseModalGrab(); } if (hadFocus) { let poppedGrab = poppedGrabs[0]; if (poppedGrab.savedFocus) poppedGrab.savedFocus.grab_key_focus(); } } onCapturedEvent(event) { let type = event.type(); if (type === Clutter.EventType.KEY_PRESS && event.get_key_symbol() === Clutter.KEY_Escape) { this.ungrab({isUser: true}); return Clutter.EVENT_STOP; } let motion = type === Clutter.EventType.MOTION; let press = type === Clutter.EventType.BUTTON_PRESS; let release = type === Clutter.EventType.BUTTON_RELEASE; let button = press || release; let touchUpdate = type === Clutter.EventType.TOUCH_UPDATE; let touchBegin = type === Clutter.EventType.TOUCH_BEGIN; let touchEnd = type === Clutter.EventType.TOUCH_END; let touch = touchUpdate || touchBegin || touchEnd; if (touch && !global.display.is_pointer_emulating_sequence(event.get_event_sequence())) return Clutter.EVENT_PROPAGATE; if (this._ignoreUntilRelease && (motion || release || touch)) { if (release || touchEnd) this._ignoreUntilRelease = false; return Clutter.EVENT_PROPAGATE; } const targetActor = global.stage.get_event_actor(event); if (type === Clutter.EventType.ENTER || type === Clutter.EventType.LEAVE || this.currentGrab.actor.contains(targetActor)) return Clutter.EVENT_PROPAGATE; if (Main.keyboard.maybeHandleEvent(event)) return Clutter.EVENT_PROPAGATE; if (button || touchBegin) { // If we have a press event, ignore the next // motion/release events. if (press || touchBegin) this._ignoreUntilRelease = true; let i = this._actorInGrabStack(targetActor) + 1; this.ungrab({actor: this._grabStack[i].actor, isUser: true}); return Clutter.EVENT_STOP; } return Clutter.EVENT_STOP; } }
0
0.912271
1
0.912271
game-dev
MEDIA
0.682448
game-dev
0.95632
1
0.95632
V-Sekai/godot-vrm
1,191
addons/vrm/vrm_toplevel.gd
@tool class_name VRMTopLevel extends Node3D const vrm_meta_class = preload("./vrm_meta.gd") const spring_bone_class = preload("./vrm_spring_bone.gd") const collider_class = preload("./vrm_collider.gd") const collider_group_class = preload("./vrm_collider_group.gd") @export var vrm_meta: Resource = (func(): var ret: vrm_meta_class = vrm_meta_class.new() ret.resource_name = "CLICK TO SEE METADATA" return ret ).call() @export_category("Springbone Settings") @export var update_secondary_fixed: bool = false @export var disable_colliders: bool = false @export var override_springbone_center: bool = false @export var default_springbone_center: Node3D @export var springbone_gravity_multiplier: float = 1.0 @export var springbone_gravity_rotation: Quaternion = Quaternion.IDENTITY @export var springbone_add_force: Vector3 = Vector3.ZERO @export_category("Run in Editor") @export var update_in_editor: bool = false @export var gizmo_spring_bone: bool = false @export var gizmo_spring_bone_color: Color = Color.LIGHT_YELLOW @export var spring_bones: Array[spring_bone_class] @export var collider_groups: Array[collider_group_class] @export var collider_library: Array[collider_class]
0
0.565343
1
0.565343
game-dev
MEDIA
0.834147
game-dev
0.779418
1
0.779418
oculus-samples/Unity-StarterSamples
5,083
Assets/StarterSamples/Core/Locomotion/Scripts/TeleportOrientationHandlerHMD.cs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * Licensed under the Oculus SDK License Agreement (the "License"); * you may not use the Oculus SDK except in compliance with the License, * which is provided at the time of installation or download, or which * otherwise accompanies this software in either electronic or hard copy form. * * You may obtain a copy of the License at * * https://developer.oculus.com/licenses/oculussdk/ * * Unless required by applicable law or agreed to in writing, the Oculus SDK * 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. */ using Meta.XR.Samples; using UnityEngine; /// <summary> /// This orientation handler will aim the player at the point they aim the HMD at after they choose the teleport location. /// </summary> [MetaCodeSample("StarterSample.Core-Locomotion")] public class TeleportOrientationHandlerHMD : TeleportOrientationHandler { /// <summary> /// HeadRelative=Character will orient to match the arrow. ForwardFacing=When user orients to match the arrow, they will be facing the sensors. /// </summary> [Tooltip("HeadRelative=Character will orient to match the arrow. ForwardFacing=When user orients to " + "match the arrow, they will be facing the sensors.")] public OrientationModes OrientationMode; /// <summary> /// Should the destination orientation be updated during the aim state in addition to the PreTeleport state? /// </summary> [Tooltip("Should the destination orientation be updated during the aim state in addition to " + "the PreTeleport state?")] public bool UpdateOrientationDuringAim; /// <summary> /// How far from the destination must the HMD be pointing before using it for orientation /// </summary> [Tooltip("How far from the destination must the HMD be pointing before using it for orientation")] public float AimDistanceThreshold; /// <summary> /// How far from the destination must the HMD be pointing before rejecting the teleport /// </summary> [Tooltip("How far from the destination must the HMD be pointing before rejecting the teleport")] public float AimDistanceMaxRange; private Quaternion _initialRotation; protected override void InitializeTeleportDestination() { _initialRotation = Quaternion.identity; } protected override void UpdateTeleportDestination() { // Only update the orientation during preteleport, or if configured to do updates during aim. if (AimData.Destination.HasValue && (UpdateOrientationDuringAim || LocomotionTeleport.CurrentState == LocomotionTeleport.States.PreTeleport)) { var t = LocomotionTeleport.LocomotionController.CameraRig.centerEyeAnchor; var destination = AimData.Destination.GetValueOrDefault(); // create a plane that contains the destination, with the normal pointing to the HMD. var plane = new Plane(Vector3.up, destination); // find the point on the plane that the HMD is looking at. float d; bool hit = plane.Raycast(new Ray(t.position, t.forward), out d); if (hit) { var target = t.position + t.forward * d; var local = target - destination; local.y = 0; var distance = local.magnitude; if (distance > AimDistanceThreshold) { local.Normalize(); // Some debug draw code to visualize what the math is doing. //OVRDebugDraw.AddCross(target, 0.2f, 0.01f, Color.yellow, 0.1f); //OVRDebugDraw.AddCross(destination + new Vector3(local.x, 0, local.z), 0.2f, 0.01f, Color.blue, 0.1f); //OVRDebugDraw.AddLine(t.position + new Vector3(0, 0.1f, 0), target, 0.01f, Color.yellow, 1.0f); //OVRDebugDraw.AddLine(target + new Vector3(0, 1f, 0), target - new Vector3(0, 1f, 0), 0.01f, Color.blue, 1.0f); var rot = Quaternion.LookRotation(new Vector3(local.x, 0, local.z), Vector3.up); _initialRotation = rot; if (AimDistanceMaxRange > 0 && distance > AimDistanceMaxRange) { AimData.TargetValid = false; } LocomotionTeleport.OnUpdateTeleportDestination(AimData.TargetValid, AimData.Destination, rot, GetLandingOrientation(OrientationMode, rot)); return; } } } LocomotionTeleport.OnUpdateTeleportDestination(AimData.TargetValid, AimData.Destination, _initialRotation, GetLandingOrientation(OrientationMode, _initialRotation)); } }
0
0.859963
1
0.859963
game-dev
MEDIA
0.930268
game-dev
0.825816
1
0.825816
s-grigorov/block-puzzle-game
2,517
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Triggers/ObservableTrigger2DTrigger.cs
using System; // require keep for Windows Universal App using UnityEngine; namespace UniRx.Triggers { [DisallowMultipleComponent] public class ObservableTrigger2DTrigger : ObservableTriggerBase { Subject<Collider2D> onTriggerEnter2D; /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary> void OnTriggerEnter2D(Collider2D other) { if (onTriggerEnter2D != null) onTriggerEnter2D.OnNext(other); } /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerEnter2DAsObservable() { return onTriggerEnter2D ?? (onTriggerEnter2D = new Subject<Collider2D>()); } Subject<Collider2D> onTriggerExit2D; /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary> void OnTriggerExit2D(Collider2D other) { if (onTriggerExit2D != null) onTriggerExit2D.OnNext(other); } /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerExit2DAsObservable() { return onTriggerExit2D ?? (onTriggerExit2D = new Subject<Collider2D>()); } Subject<Collider2D> onTriggerStay2D; /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary> void OnTriggerStay2D(Collider2D other) { if (onTriggerStay2D != null) onTriggerStay2D.OnNext(other); } /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerStay2DAsObservable() { return onTriggerStay2D ?? (onTriggerStay2D = new Subject<Collider2D>()); } protected override void RaiseOnCompletedOnDestroy() { if (onTriggerEnter2D != null) { onTriggerEnter2D.OnCompleted(); } if (onTriggerExit2D != null) { onTriggerExit2D.OnCompleted(); } if (onTriggerStay2D != null) { onTriggerStay2D.OnCompleted(); } } } }
0
0.716648
1
0.716648
game-dev
MEDIA
0.94488
game-dev
0.806073
1
0.806073
oiuv/mud
1,170
cmds/usr/finger.c
// finger.c inherit F_CLEAN_UP; void create() { seteuid(getuid()); } int main(object me, string arg) { object *ob; if (time() - me->query_temp("scan_time") < 10 && !wizardp(me)) return notify_fail("等等,系统喘气中……\n"); if (!arg) { if ((int)me->query("jing") < 50) return notify_fail("你的精神无法集中。\n"); me->receive_damage("jing", 50); me->set_temp("scan_time", time()); me->start_more(FINGER_D->finger_all()); } else if (arg == "-m") { if (!wizardp(this_player())) return notify_fail("你无权使用 -m 参数。\n"); ob = filter_array(users(), (: $1->name() != $1->name(1) :)); me->set_temp("scan_time", time()); me->start_more(FINGER_D->user_list(ob), 0); } else { if ((int)me->query("jing") < 20) return notify_fail("你的精神无法集中。\n"); me->set_temp("scan_time", time()); write(FINGER_D->finger_user(arg)); } return 1; } int help(object me) { write(@HELP 指令格式:finger [-m] [使用者姓名] 这个指令,如果没有指定使用者姓明,会显示出所有正在线上玩家 的连线资料。反之,则可显示有关某个玩家的连线,权限等资料。 如果使用了 -m 参数,可以列出使用面具的玩家。 相关指令:who HELP); return 1; }
0
0.84318
1
0.84318
game-dev
MEDIA
0.594722
game-dev
0.962035
1
0.962035
glKarin/com.n0n3m4.diii4a
19,427
Q3E/src/main/jni/doom3/neo/mod/doom3/librecoopxp/script/Script_Program.h
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 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. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #ifndef __SCRIPT_PROGRAM_H__ #define __SCRIPT_PROGRAM_H__ #include "idlib/containers/StrList.h" #include "idlib/containers/StaticList.h" #include "idlib/containers/HashIndex.h" #include "idlib/math/Vector.h" #include "GameBase.h" class idEventDef; class idVarDef; class idTypeDef; class idEntity; class idSaveGame; class idRestoreGame; #define MAX_STRING_LEN 128 #ifdef _D3XP #define MAX_GLOBALS 296608 // in bytes #else #define MAX_GLOBALS 196608 // in bytes #endif #define MAX_STRINGS 1024 #ifdef _D3XP #define MAX_FUNCS 3584 #else #define MAX_FUNCS 3072 #endif #ifdef _D3XP #define MAX_STATEMENTS 131072 // statement_t - 18 bytes last I checked #else #define MAX_STATEMENTS 81920 // statement_t - 18 bytes last I checked #endif typedef enum { ev_error = -1, ev_void, ev_scriptevent, ev_namespace, ev_string, ev_float, ev_vector, ev_entity, ev_field, ev_function, ev_virtualfunction, ev_pointer, ev_object, ev_jumpoffset, ev_argsize, ev_boolean } etype_t; class function_t { public: function_t(); size_t Allocated( void ) const; void SetName( const char *name ); const char *Name( void ) const; void Clear( void ); private: idStr name; public: const idEventDef *eventdef; idVarDef *def; const idTypeDef *type; int firstStatement; int numStatements; int parmTotal; int locals; // total ints of parms + locals int filenum; // source file defined in idList<int> parmSize; }; typedef union eval_s { const char *stringPtr; float _float; float vector[ 3 ]; function_t *function; int _int; int entity; } eval_t; /*********************************************************************** idTypeDef Contains type information for variables and functions. ***********************************************************************/ class idTypeDef { private: etype_t type; idStr name; int size; // function types are more complex idTypeDef *auxType; // return type idList<idTypeDef *> parmTypes; idStrList parmNames; idList<const function_t *> functions; public: idVarDef *def; // a def that points to this type idTypeDef( const idTypeDef &other ); idTypeDef( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ); void operator=( const idTypeDef& other ); size_t Allocated( void ) const; bool Inherits( const idTypeDef *basetype ) const; bool MatchesType( const idTypeDef &matchtype ) const; bool MatchesVirtualFunction( const idTypeDef &matchfunc ) const; void AddFunctionParm( idTypeDef *parmtype, const char *name ); void AddField( idTypeDef *fieldtype, const char *name ); void SetName( const char *newname ); const char *Name( void ) const; etype_t Type( void ) const; int Size( void ) const; idTypeDef *SuperClass( void ) const; idTypeDef *ReturnType( void ) const; void SetReturnType( idTypeDef *type ); idTypeDef *FieldType( void ) const; void SetFieldType( idTypeDef *type ); idTypeDef *PointerType( void ) const; void SetPointerType( idTypeDef *type ); int NumParameters( void ) const; idTypeDef *GetParmType( int parmNumber ) const; const char *GetParmName( int parmNumber ) const; int NumFunctions( void ) const; int GetFunctionNumber( const function_t *func ) const; const function_t *GetFunction( int funcNumber ) const; void AddFunction( const function_t *func ); }; /*********************************************************************** idScriptObject In-game representation of objects in scripts. Use the idScriptVariable template (below) to access variables. ***********************************************************************/ class idScriptObject { private: idTypeDef *type; public: byte *data; idScriptObject(); ~idScriptObject(); void Save( idSaveGame *savefile ) const; // archives object for save game file void Restore( idRestoreGame *savefile ); // unarchives object from save game file void Free( void ); bool SetType( const char *typeName ); void ClearObject( void ); bool HasObject( void ) const; idTypeDef *GetTypeDef( void ) const; const char *GetTypeName( void ) const; const function_t *GetConstructor( void ) const; const function_t *GetDestructor( void ) const; const function_t *GetFunction( const char *name ) const; byte *GetVariable( const char *name, etype_t etype ) const; }; /*********************************************************************** idScriptVariable Helper template that handles looking up script variables stored in objects. If the specified variable doesn't exist, or is the wrong data type, idScriptVariable will cause an error. ***********************************************************************/ template<class type, etype_t etype, class returnType> class idScriptVariable { private: type *data; public: idScriptVariable(); bool IsLinked( void ) const; void Unlink( void ); void LinkTo( idScriptObject &obj, const char *name ); idScriptVariable &operator=( const returnType &value ); operator returnType() const; }; template<class type, etype_t etype, class returnType> ID_INLINE idScriptVariable<type, etype, returnType>::idScriptVariable() { data = NULL; } template<class type, etype_t etype, class returnType> ID_INLINE bool idScriptVariable<type, etype, returnType>::IsLinked( void ) const { return ( data != NULL ); } template<class type, etype_t etype, class returnType> ID_INLINE void idScriptVariable<type, etype, returnType>::Unlink( void ) { data = NULL; } template<class type, etype_t etype, class returnType> ID_INLINE void idScriptVariable<type, etype, returnType>::LinkTo( idScriptObject &obj, const char *name ) { data = ( type * )obj.GetVariable( name, etype ); if ( !data ) { gameError( "Missing '%s' field in script object '%s'", name, obj.GetTypeName() ); } } template<class type, etype_t etype, class returnType> ID_INLINE idScriptVariable<type, etype, returnType> &idScriptVariable<type, etype, returnType>::operator=( const returnType &value ) { // check if we attempt to access the object before it's been linked assert( data ); // make sure we don't crash if we don't have a pointer if ( data ) { *data = ( type )value; } return *this; } template<class type, etype_t etype, class returnType> ID_INLINE idScriptVariable<type, etype, returnType>::operator returnType() const { // check if we attempt to access the object before it's been linked assert( data ); // make sure we don't crash if we don't have a pointer if ( data ) { return ( const returnType )*data; } else { // reasonably safe value return ( const returnType )0; } } /*********************************************************************** Script object variable access template instantiations These objects will automatically handle looking up of the current value of a variable in a script object. They can be stored as part of a class for up-to-date values of the variable, or can be used in functions to sample the data for non-dynamic values. ***********************************************************************/ typedef idScriptVariable<int, ev_boolean, int> idScriptBool; typedef idScriptVariable<float, ev_float, float> idScriptFloat; typedef idScriptVariable<float, ev_float, int> idScriptInt; typedef idScriptVariable<idVec3, ev_vector, idVec3> idScriptVector; typedef idScriptVariable<idStr, ev_string, const char *> idScriptString; /*********************************************************************** idCompileError Causes the compiler to exit out of compiling the current function and display an error message with line and file info. ***********************************************************************/ class idCompileError : public idException { public: idCompileError( const char *text ) : idException( text ) {} }; /*********************************************************************** idVarDef Define the name, type, and location of variables, functions, and objects defined in script. ***********************************************************************/ typedef union varEval_s { idScriptObject **objectPtrPtr; char *stringPtr; float *floatPtr; idVec3 *vectorPtr; function_t *functionPtr; int *intPtr; byte *bytePtr; int *entityNumberPtr; int virtualFunction; int jumpOffset; int stackOffset; // offset in stack for local variables int argSize; varEval_s *evalPtr; int ptrOffset; } varEval_t; class idVarDefName; class idVarDef { friend class idVarDefName; public: int num; varEval_t value; idVarDef * scope; // function, namespace, or object the var was defined in int numUsers; // number of users if this is a constant typedef enum { uninitialized, initializedVariable, initializedConstant, stackVariable } initialized_t; initialized_t initialized; public: idVarDef( idTypeDef *typeptr = NULL ); ~idVarDef(); const char * Name( void ) const; const char * GlobalName( void ) const; void SetTypeDef( idTypeDef *_type ) { typeDef = _type; } idTypeDef * TypeDef( void ) const { return typeDef; } etype_t Type( void ) const { return ( typeDef != NULL ) ? typeDef->Type() : ev_void; } int DepthOfScope( const idVarDef *otherScope ) const; void SetFunction( function_t *func ); void SetObject( idScriptObject *object ); void SetValue( const eval_t &value, bool constant ); void SetString( const char *string, bool constant ); idVarDef * Next( void ) const { return next; } // next var def with same name void PrintInfo( idFile *file, int instructionPointer ) const; private: idTypeDef * typeDef; idVarDefName * name; // name of this var idVarDef * next; // next var with the same name }; /*********************************************************************** idVarDefName ***********************************************************************/ class idVarDefName { public: idVarDefName( void ) { defs = NULL; } idVarDefName( const char *n ) { name = n; defs = NULL; } const char * Name( void ) const { return name; } idVarDef * GetDefs( void ) const { return defs; } void AddDef( idVarDef *def ); void RemoveDef( idVarDef *def ); private: idStr name; idVarDef * defs; }; /*********************************************************************** Variable and type defintions ***********************************************************************/ extern idTypeDef type_void; extern idTypeDef type_scriptevent; extern idTypeDef type_namespace; extern idTypeDef type_string; extern idTypeDef type_float; extern idTypeDef type_vector; extern idTypeDef type_entity; extern idTypeDef type_field; extern idTypeDef type_function; extern idTypeDef type_virtualfunction; extern idTypeDef type_pointer; extern idTypeDef type_object; extern idTypeDef type_jumpoffset; // only used for jump opcodes extern idTypeDef type_argsize; // only used for function call and thread opcodes extern idTypeDef type_boolean; extern idVarDef def_void; extern idVarDef def_scriptevent; extern idVarDef def_namespace; extern idVarDef def_string; extern idVarDef def_float; extern idVarDef def_vector; extern idVarDef def_entity; extern idVarDef def_field; extern idVarDef def_function; extern idVarDef def_virtualfunction; extern idVarDef def_pointer; extern idVarDef def_object; extern idVarDef def_jumpoffset; // only used for jump opcodes extern idVarDef def_argsize; // only used for function call and thread opcodes extern idVarDef def_boolean; typedef struct statement_s { unsigned short op; idVarDef *a; idVarDef *b; idVarDef *c; unsigned short linenumber; unsigned short file; } statement_t; /*********************************************************************** idProgram Handles compiling and storage of script data. Multiple idProgram objects would represent seperate programs with no knowledge of each other. Scripts meant to access shared data and functions should all be compiled by a single idProgram. ***********************************************************************/ class idProgram { private: idStrList fileList; idStr filename; int filenum; int numVariables; byte variables[ MAX_GLOBALS ]; idStaticList<byte,MAX_GLOBALS> variableDefaults; idStaticList<function_t,MAX_FUNCS> functions; idStaticList<statement_t,MAX_STATEMENTS> statements; idList<idTypeDef *> types; idList<idVarDefName *> varDefNames; idHashIndex varDefNameHash; idList<idVarDef *> varDefs; idVarDef *sysDef; int top_functions; int top_statements; int top_types; int top_defs; int top_files; void CompileStats( void ); byte *ReserveMem(int size); idVarDef *AllocVarDef(idTypeDef *type, const char *name, idVarDef *scope); public: idVarDef *returnDef; idVarDef *returnStringDef; idProgram(); ~idProgram(); // save games void Save( idSaveGame *savefile ) const; bool Restore( idRestoreGame *savefile ); int CalculateChecksum( void ) const; // Used to insure program code has not // changed between savegames void Startup( const char *defaultScript ); void Restart( void ); bool CompileText( const char *source, const char *text, bool console ); const function_t *CompileFunction( const char *functionName, const char *text ); void CompileFile( const char *filename ); void BeginCompilation( void ); void FinishCompilation( void ); void DisassembleStatement( idFile *file, int instructionPointer ) const; void Disassemble( void ) const; void FreeData( void ); const char *GetFilename( int num ); int GetFilenum( const char *name ); int GetLineNumberForStatement( int index ); const char *GetFilenameForStatement( int index ); idTypeDef *AllocType( idTypeDef &type ); idTypeDef *AllocType( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ); idTypeDef *GetType( idTypeDef &type, bool allocate ); idTypeDef *FindType( const char *name ); idVarDef *AllocDef( idTypeDef *type, const char *name, idVarDef *scope, bool constant ); idVarDef *GetDef( const idTypeDef *type, const char *name, const idVarDef *scope ) const; void FreeDef( idVarDef *d, const idVarDef *scope ); idVarDef *FindFreeResultDef( idTypeDef *type, const char *name, idVarDef *scope, const idVarDef *a, const idVarDef *b ); idVarDef *GetDefList( const char *name ) const; void AddDefToNameList( idVarDef *def, const char *name ); function_t *FindFunction( const char *name ) const; // returns NULL if function not found function_t *FindFunction( const char *name, const idTypeDef *type ) const; // returns NULL if function not found function_t &AllocFunction( idVarDef *def ); function_t *GetFunction( int index ); int GetFunctionIndex( const function_t *func ); void SetEntity( const char *name, idEntity *ent ); statement_t *AllocStatement( void ); statement_t &GetStatement( int index ); int NumStatements( void ) { return statements.Num(); } int GetReturnedInteger( void ); void ReturnFloat( float value ); void ReturnInteger( int value ); void ReturnVector( idVec3 const &vec ); void ReturnString( const char *string ); void ReturnEntity( idEntity *ent ); int NumFilenames( void ) { return fileList.Num( ); } }; /* ================ idProgram::GetStatement ================ */ ID_INLINE statement_t &idProgram::GetStatement( int index ) { return statements[ index ]; } /* ================ idProgram::GetFunction ================ */ ID_INLINE function_t *idProgram::GetFunction( int index ) { return &functions[ index ]; } /* ================ idProgram::GetFunctionIndex ================ */ ID_INLINE int idProgram::GetFunctionIndex( const function_t *func ) { return func - &functions[0]; } /* ================ idProgram::GetReturnedInteger ================ */ ID_INLINE int idProgram::GetReturnedInteger( void ) { return *returnDef->value.intPtr; } /* ================ idProgram::ReturnFloat ================ */ ID_INLINE void idProgram::ReturnFloat( float value ) { *returnDef->value.floatPtr = value; } /* ================ idProgram::ReturnInteger ================ */ ID_INLINE void idProgram::ReturnInteger( int value ) { *returnDef->value.intPtr = value; } /* ================ idProgram::ReturnVector ================ */ ID_INLINE void idProgram::ReturnVector( idVec3 const &vec ) { *returnDef->value.vectorPtr = vec; } /* ================ idProgram::ReturnString ================ */ ID_INLINE void idProgram::ReturnString( const char *string ) { idStr::Copynz( returnStringDef->value.stringPtr, string, MAX_STRING_LEN ); } /* ================ idProgram::GetFilename ================ */ ID_INLINE const char *idProgram::GetFilename( int num ) { return fileList[ num ]; } /* ================ idProgram::GetLineNumberForStatement ================ */ ID_INLINE int idProgram::GetLineNumberForStatement( int index ) { return statements[ index ].linenumber; } /* ================ idProgram::GetFilenameForStatement ================ */ ID_INLINE const char *idProgram::GetFilenameForStatement( int index ) { return GetFilename( statements[ index ].file ); } #endif /* !__SCRIPT_PROGRAM_H__ */
0
0.743385
1
0.743385
game-dev
MEDIA
0.510529
game-dev
0.526385
1
0.526385