Exemplo n.º 1
0
 public void SaveAsJpeg(Stream stream, int width, int height)
 {
     // Get the Texture2D pixels
     byte[] data = new byte[Width * Height * GetFormatSize(Format)];
     GetData(data);
     FNAPlatform.SaveJPG(
         stream,
         width,
         height,
         Width,
         Height,
         data
         );
 }
Exemplo n.º 2
0
 internal void OnWaveBankDestroyed()
 {
     IsDisposed = true;
     if (bankData != IntPtr.Zero)
     {
         if (bankDataLen != IntPtr.Zero)
         {
             FNAPlatform.FreeFilePointer(bankData);
             bankDataLen = IntPtr.Zero;
         }
         else
         {
             FAudio.FAudio_close(bankData);
         }
         bankData = IntPtr.Zero;
     }
     handle        = IntPtr.Zero;
     selfReference = null;
 }
        public static void Initialize()
        {
            // We should only have one of these!
            if (ALDevice != null)
            {
                FNALoggerEXT.LogWarn("ALDevice already exists, overwriting!");
            }

            bool disableSound = Environment.GetEnvironmentVariable(
                "FNA_AUDIO_DISABLE_SOUND"
                ) == "1";

            if (disableSound)
            {
                ALDevice = new NullALDevice();
            }
            else
            {
                ALDevice = FNAPlatform.CreateALDevice();
            }

            // Populate device info
            if (ALDevice != null)
            {
                ALDevice.SetMasterVolume(MasterVolume);
                ALDevice.SetDopplerScale(DopplerScale);
                ALDevice.SetSpeedOfSound(SpeedOfSound);

                Renderers      = ALDevice.GetDevices();
                Microphone.All = ALDevice.GetCaptureDevices();

                InstancePool        = new List <SoundEffectInstance>();
                DynamicInstancePool = new List <DynamicSoundEffectInstance>();
                ActiveMics          = new List <Microphone>();
                AppDomain.CurrentDomain.ProcessExit += Dispose;
            }
            else
            {
                Renderers      = new ReadOnlyCollection <RendererDetail>(new List <RendererDetail>());
                Microphone.All = new ReadOnlyCollection <Microphone>(new List <Microphone>());
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Loads image data from a given stream.
 /// </summary>
 /// <remarks>
 /// This is an extension of XNA 4 and is not compatible with XNA. It exists to help with dynamically reloading
 /// textures while games are running. Games can use this method to read a stream into memory and then call
 /// SetData on a texture with that data, rather than having to dispose the texture and recreate it entirely.
 /// </remarks>
 /// <param name="stream">The stream from which to read the image data.</param>
 /// <param name="width">Outputs the width of the image.</param>
 /// <param name="height">Outputs the height of the image.</param>
 /// <param name="pixels">Outputs the pixel data of the image, in non-premultiplied RGBA format.</param>
 /// <param name="requestedWidth">Preferred width of the resulting image data</param>
 /// <param name="requestedHeight">Preferred height of the resulting image data</param>
 /// <param name="zoom">false to maintain aspect ratio, true to crop image</param>
 public static void TextureDataFromStreamEXT(
     Stream stream,
     out int width,
     out int height,
     out byte[] pixels,
     int requestedWidth  = -1,
     int requestedHeight = -1,
     bool zoom           = false
     )
 {
     FNAPlatform.TextureDataFromStream(
         stream,
         out width,
         out height,
         out pixels,
         requestedWidth,
         requestedHeight,
         zoom
         );
 }
Exemplo n.º 5
0
        /// <summary>
        /// Gets mouse state information that includes position and button
        /// presses for the provided window
        /// </summary>
        /// <returns>Current state of the mouse.</returns>
        public static MouseState GetState()
        {
            int         x, y;
            ButtonState left, middle, right, x1, x2;

            FNAPlatform.GetMouseState(
                WindowHandle,
                out x,
                out y,
                out left,
                out middle,
                out right,
                out x1,
                out x2
                );

            // If we warped the mouse, we've already done this in SetPosition.
            if (INTERNAL_IsWarped)
            {
                x = INTERNAL_warpX;
                y = INTERNAL_warpY;
            }
            else
            {
                // Scale the mouse coordinates for the faux-backbuffer
                x = (int)((double)x * INTERNAL_BackBufferWidth / INTERNAL_WindowWidth);
                y = (int)((double)y * INTERNAL_BackBufferHeight / INTERNAL_WindowHeight);
            }

            return(new MouseState(
                       x,
                       y,
                       INTERNAL_MouseWheel,
                       left,
                       middle,
                       right,
                       x1,
                       x2
                       ));
        }
Exemplo n.º 6
0
        public static Texture2D FromStream(
            GraphicsDevice graphicsDevice,
            Stream stream,
            int width,
            int height,
            bool zoom
            )
        {
            // Read the image data from the stream
            int    realWidth, realHeight, len;
            IntPtr pixels;

            FNAPlatform.TextureDataFromStreamPtr(
                stream,
                out realWidth,
                out realHeight,
                out pixels,
                out len,
                width,
                height,
                zoom
                );

            // Create the Texture2D from the raw pixel data
            Texture2D result = new Texture2D(
                graphicsDevice,
                realWidth,
                realHeight
                );

            result.SetDataPointerEXT(
                0,
                null,
                pixels,
                len
                );
            Marshal.FreeHGlobal(pixels);
            return(result);
        }
Exemplo n.º 7
0
        public int GetData(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentException("buffer is null!");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentException("offset");
            }
            if (count <= 0 || (offset + count) > buffer.Length)
            {
                throw new ArgumentException("count");
            }

            return(FNAPlatform.GetMicrophoneSamples(
                       handle,
                       buffer,
                       offset,
                       count
                       ));
        }
Exemplo n.º 8
0
        public SoundBank(AudioEngine audioEngine, string filename)
        {
            if (audioEngine == null)
            {
                throw new ArgumentNullException("audioEngine");
            }
            if (String.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("filename");
            }

            IntPtr bufferLen;
            IntPtr buffer = TitleContainer.ReadToPointer(filename, out bufferLen);

            FAudio.FACTAudioEngine_CreateSoundBank(
                audioEngine.handle,
                buffer,
                (uint)bufferLen,
                0,
                0,
                out handle
                );

            FNAPlatform.FreeFilePointer(buffer);

            engine        = audioEngine;
            selfReference = new WeakReference(this, true);
            dspSettings   = new FAudio.F3DAUDIO_DSP_SETTINGS();
            dspSettings.SrcChannelCount     = 1;
            dspSettings.DstChannelCount     = engine.channels;
            dspSettings.pMatrixCoefficients = Marshal.AllocHGlobal(
                4 *
                (int)dspSettings.SrcChannelCount *
                (int)dspSettings.DstChannelCount
                );
            engine.RegisterPointer(handle, selfReference);
            IsDisposed = false;
        }
Exemplo n.º 9
0
        public static void Initialize()
        {
            // We should only have one of these!
            if (ALDevice != null)
            {
                FNAPlatform.Log("ALDevice already exists, overwriting!");
            }

            bool disableSound = Environment.GetEnvironmentVariable(
                "FNA_AUDIO_DISABLE_SOUND"
                ) == "1";

            if (disableSound)
            {
                ALDevice = new NullDevice();
            }
            else
            {
                ALDevice = FNAPlatform.CreateALDevice();
            }

            // Populate device list
            if (ALDevice != null)
            {
                Renderers      = ALDevice.GetDevices();
                Microphone.All = ALDevice.GetCaptureDevices();

                InstancePool        = new List <SoundEffectInstance>();
                DynamicInstancePool = new List <DynamicSoundEffectInstance>();
                ActiveMics          = new List <Microphone>();
            }
            else
            {
                Renderers      = new ReadOnlyCollection <RendererDetail>(new List <RendererDetail>());
                Microphone.All = new ReadOnlyCollection <Microphone>(new List <Microphone>());
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsDevice" /> class.
        /// </summary>
        /// <param name="adapter">The graphics adapter.</param>
        /// <param name="graphicsProfile">The graphics profile.</param>
        /// <param name="presentationParameters">The presentation options.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="presentationParameters"/> is <see langword="null"/>.
        /// </exception>
        public GraphicsDevice(
            GraphicsAdapter adapter,
            GraphicsProfile graphicsProfile,
            PresentationParameters presentationParameters
            )
        {
            if (presentationParameters == null)
            {
                throw new ArgumentNullException("presentationParameters");
            }

            // Set the properties from the constructor parameters.
            Adapter = adapter;
            PresentationParameters = presentationParameters;
            GraphicsProfile        = graphicsProfile;
            PresentationParameters.MultiSampleCount = MathHelper.ClosestMSAAPower(
                PresentationParameters.MultiSampleCount
                );

            // Set up the IGLDevice
            GLDevice = FNAPlatform.CreateGLDevice(PresentationParameters, adapter);

            // The mouse needs to know this for faux-backbuffer mouse scaling.
            Input.Mouse.INTERNAL_BackBufferWidth  = PresentationParameters.BackBufferWidth;
            Input.Mouse.INTERNAL_BackBufferHeight = PresentationParameters.BackBufferHeight;

            // The Touch Panel needs this too, for the same reason.
            Input.Touch.TouchPanel.DisplayWidth  = PresentationParameters.BackBufferWidth;
            Input.Touch.TouchPanel.DisplayHeight = PresentationParameters.BackBufferHeight;

            // Force set the default render states.
            BlendState        = BlendState.Opaque;
            DepthStencilState = DepthStencilState.Default;
            RasterizerState   = RasterizerState.CullCounterClockwise;

            // Initialize the Texture/Sampler state containers
            int maxTextures       = Math.Min(GLDevice.MaxTextureSlots, MAX_TEXTURE_SAMPLERS);
            int maxVertexTextures = MathHelper.Clamp(
                GLDevice.MaxTextureSlots - MAX_TEXTURE_SAMPLERS,
                0,
                MAX_VERTEXTEXTURE_SAMPLERS
                );

            vertexSamplerStart = GLDevice.MaxTextureSlots - maxVertexTextures;
            Textures           = new TextureCollection(
                maxTextures,
                modifiedSamplers
                );
            SamplerStates = new SamplerStateCollection(
                maxTextures,
                modifiedSamplers
                );
            VertexTextures = new TextureCollection(
                maxVertexTextures,
                modifiedVertexSamplers
                );
            VertexSamplerStates = new SamplerStateCollection(
                maxVertexTextures,
                modifiedVertexSamplers
                );

            // Set the default viewport and scissor rect.
            Viewport         = new Viewport(PresentationParameters.Bounds);
            ScissorRectangle = Viewport.Bounds;

            // Allocate the pipeline cache to be used by Effects
            PipelineCache = new PipelineCache(this);
#if WIIU_GAMEPAD
            wiiuStream = DRC.drc_new_streamer();
            if (wiiuStream == IntPtr.Zero)
            {
                FNALoggerEXT.LogError("Failed to alloc GamePad stream!");
                return;
            }
            if (DRC.drc_start_streamer(wiiuStream) < 1)             // ???
            {
                FNALoggerEXT.LogError("Failed to start GamePad stream!");
                DRC.drc_delete_streamer(wiiuStream);
                wiiuStream = IntPtr.Zero;
                return;
            }
            DRC.drc_enable_system_input_feeder(wiiuStream);
            wiiuPixelData = new byte[
                PresentationParameters.BackBufferWidth *
                PresentationParameters.BackBufferHeight *
                4
                            ];
#endif
        }
Exemplo n.º 11
0
        internal static void OnReleased(int fingerId, Vector2 touchPosition)
        {
            fingerIds.Remove(fingerId);

            // Handle release events seperately for Pinch gestures
            if (state == GestureState.PINCHING)
            {
                OnReleased_Pinch(fingerId, touchPosition);
                return;
            }

            // Did the user lift the active finger?
            if (fingerId == activeFingerId)
            {
                activeFingerId = TouchPanel.NO_FINGER;
            }

            // We're only interested in the very last finger to leave
            if (FNAPlatform.GetNumTouchFingers() > 0)
            {
                return;
            }

            #region Tap Detection

            if (state == GestureState.HOLDING)
            {
                // Which Tap gestures are enabled?
                bool tapEnabled  = IsGestureEnabled(GestureType.Tap);
                bool dtapEnabled = IsGestureEnabled(GestureType.DoubleTap);

                if (tapEnabled || dtapEnabled)
                {
                    // How long did the user hold the touch?
                    TimeSpan timeHeld = DateTime.Now - eventTimestamp;
                    if (timeHeld < TimeSpan.FromSeconds(1))
                    {
                        // Don't register a Tap immediately after a Double Tap
                        if (!justDoubleTapped)
                        {
                            if (tapEnabled)
                            {
                                // Tap!
                                TouchPanel.EnqueueGesture(new GestureSample(
                                                              GestureType.Tap,
                                                              GetGestureTimestamp(),
                                                              touchPosition,
                                                              Vector2.Zero,
                                                              Vector2.Zero,
                                                              Vector2.Zero,
                                                              fingerId,
                                                              TouchPanel.NO_FINGER
                                                              ));
                            }

                            /* Even if Tap isn't enabled, we still
                             * need this for Double Tap detection.
                             */
                            state = GestureState.JUST_TAPPED;
                        }
                    }
                }
            }

            // Reset this flag so we can catch Taps in the future
            justDoubleTapped = false;

            #endregion

            #region Flick Detection

            if (IsGestureEnabled(GestureType.Flick))
            {
                // Only flick if the finger is outside the threshold and moving fast
                float distanceFromPress = (touchPosition - pressPosition).Length();
                if (distanceFromPress > MOVE_THRESHOLD &&
                    velocity.Length() >= MIN_FLICK_VELOCITY)
                {
                    // Flick!
                    TouchPanel.EnqueueGesture(new GestureSample(
                                                  GestureType.Flick,
                                                  GetGestureTimestamp(),
                                                  Vector2.Zero,
                                                  Vector2.Zero,
                                                  velocity,
                                                  Vector2.Zero,
                                                  fingerId,
                                                  TouchPanel.NO_FINGER
                                                  ));
                }

                // Reset velocity calculation variables
                velocity           = Vector2.Zero;
                lastUpdatePosition = Vector2.Zero;
                updateTimestamp    = DateTime.MinValue;
            }

            #endregion

            #region Drag Complete Detection

            if (IsGestureEnabled(GestureType.DragComplete))
            {
                bool wasDragging = (state == GestureState.DRAGGING_H ||
                                    state == GestureState.DRAGGING_V ||
                                    state == GestureState.DRAGGING_FREE);
                if (wasDragging)
                {
                    // Drag Complete!
                    TouchPanel.EnqueueGesture(new GestureSample(
                                                  GestureType.DragComplete,
                                                  GetGestureTimestamp(),
                                                  Vector2.Zero,
                                                  Vector2.Zero,
                                                  Vector2.Zero,
                                                  Vector2.Zero,
                                                  fingerId,
                                                  TouchPanel.NO_FINGER
                                                  ));
                }
            }

            #endregion

            #region Belated Pinch Complete Detection

            if (callBelatedPinchComplete && IsGestureEnabled(GestureType.PinchComplete))
            {
                TouchPanel.EnqueueGesture(new GestureSample(
                                              GestureType.PinchComplete,
                                              GetGestureTimestamp(),
                                              Vector2.Zero,
                                              Vector2.Zero,
                                              Vector2.Zero,
                                              Vector2.Zero,
                                              TouchPanel.NO_FINGER,
                                              TouchPanel.NO_FINGER
                                              ));
            }
            callBelatedPinchComplete = false;

            #endregion

            // Reset the state if we're not anticipating a Double Tap
            if (state != GestureState.JUST_TAPPED)
            {
                state = GestureState.NONE;
            }

            eventTimestamp = DateTime.Now;
        }
Exemplo n.º 12
0
 /// <summary>
 /// Sets the location within the game window where the text input is located.
 /// This is used to set the location of the IME suggestions
 /// </summary>
 /// <param name="rectangle">Text input location relative to GameWindow.ClientBounds</param>
 public static void SetInputRectangle(Rectangle rectangle)
 {
     FNAPlatform.SetTextInputRectangle(rectangle);
 }
Exemplo n.º 13
0
 public void Stop()
 {
     FNAPlatform.StopMicrophone(handle);
     State = MicrophoneState.Stopped;
 }
Exemplo n.º 14
0
 public static Keys GetKeyFromScancodeEXT(Keys scancode)
 {
     return(FNAPlatform.GetKeyFromScancode(scancode));
 }
Exemplo n.º 15
0
 public void Start()
 {
     FNAPlatform.StartMicrophone(handle);
     State = MicrophoneState.Started;
 }
Exemplo n.º 16
0
        public void Play(Video video)
        {
            checkDisposed();

            // We need to assign this regardless of what happens next.
            Video = video;
            video.AttachedToPlayer = true;

            // FIXME: This is a part of the Duration hack!
            Video.Duration = TimeSpan.MaxValue;

            // Check the player state before attempting anything.
            if (State != MediaState.Stopped)
            {
                return;
            }

            // Update the player state now, for the thread we're about to make.
            State = MediaState.Playing;

            // Start the video if it hasn't been yet.
            if (Video.IsDisposed)
            {
                video.Initialize();
            }

            // Grab the first bit of audio. We're trying to start the decoding ASAP.
            if (TheoraPlay.THEORAPLAY_hasAudioStream(Video.theoraDecoder) != 0)
            {
                InitAudioStream();
            }

            // Grab the first bit of video, set up the texture.
            if (TheoraPlay.THEORAPLAY_hasVideoStream(Video.theoraDecoder) != 0)
            {
                currentVideo  = TheoraPlay.getVideoFrame(Video.videoStream);
                previousFrame = Video.videoStream;
                do
                {
                    // The decoder miiight not be ready yet.
                    Video.videoStream = TheoraPlay.THEORAPLAY_getVideo(Video.theoraDecoder);
                } while (Video.videoStream == IntPtr.Zero);
                nextVideo = TheoraPlay.getVideoFrame(Video.videoStream);

                // The VideoPlayer will use the GraphicsDevice that is set now.
                if (currentDevice != Video.GraphicsDevice)
                {
                    GL_dispose();
                    currentDevice = Video.GraphicsDevice;
                    GL_initialize();
                }

                RenderTargetBinding overlap = videoTexture[0];
                videoTexture[0] = new RenderTargetBinding(
                    new RenderTarget2D(
                        currentDevice,
                        (int)currentVideo.width,
                        (int)currentVideo.height,
                        false,
                        SurfaceFormat.Color,
                        DepthFormat.None,
                        0,
                        RenderTargetUsage.PreserveContents
                        )
                    );
                if (overlap.RenderTarget != null)
                {
                    overlap.RenderTarget.Dispose();
                }
                GL_setupTextures(
                    (int)currentVideo.width,
                    (int)currentVideo.height
                    );
            }

            // Initialize the thread!
            FNAPlatform.Log("Starting Theora player...");
            timer.Start();
            if (audioStream != null)
            {
                audioStream.Play();
            }
            FNAPlatform.Log("Started!");
        }
Exemplo n.º 17
0
 public static GamePadCapabilities GetCapabilities(PlayerIndex playerIndex)
 {
     return(FNAPlatform.GetGamePadCapabilities((int)playerIndex));
 }
Exemplo n.º 18
0
 public static TouchPanelCapabilities GetCapabilities()
 {
     return(FNAPlatform.GetTouchCapabilities());
 }
Exemplo n.º 19
0
 public static void SetLightBarEXT(PlayerIndex playerIndex, Color color)
 {
     FNAPlatform.SetGamePadLightBar((int)playerIndex, color);
 }
Exemplo n.º 20
0
 public static string GetGUIDEXT(PlayerIndex playerIndex)
 {
     return(FNAPlatform.GetGamePadGUID((int)playerIndex));
 }
Exemplo n.º 21
0
 public static void StopTextInput()
 {
     FNAPlatform.StopTextInput();
 }
Exemplo n.º 22
0
        internal void Play(bool isManaged)
        {
            if (State != SoundState.Stopped)
            {
                return;                 // No-op if we're already playing.
            }

            if (INTERNAL_alSource != null)
            {
                // The sound has stopped, but hasn't cleaned up yet...
                AudioDevice.ALDevice.StopAndDisposeSource(INTERNAL_alSource);
                INTERNAL_alSource = null;
            }
            while (queuedBuffers.Count > 0)
            {
                availableBuffers.Enqueue(queuedBuffers.Dequeue());
                PendingBufferCount -= 1;
            }

            INTERNAL_alSource = AudioDevice.ALDevice.GenSource();
            if (INTERNAL_alSource == null)
            {
                FNAPlatform.Log("WARNING: AL SOURCE WAS NOT AVAILABLE. SKIPPING.");
                return;
            }

            // Queue the buffers to this source
            while (buffersToQueue.Count > 0)
            {
                IALBuffer nextBuf = buffersToQueue.Dequeue();
                queuedBuffers.Enqueue(nextBuf);
                AudioDevice.ALDevice.QueueSourceBuffer(INTERNAL_alSource, nextBuf);
            }

            // Apply Pan/Position
            if (INTERNAL_positionalAudio)
            {
                INTERNAL_positionalAudio = false;
                AudioDevice.ALDevice.SetSourcePosition(
                    INTERNAL_alSource,
                    position
                    );
            }
            else
            {
                Pan = Pan;
            }

            // Reassign Properties, in case the AL properties need to be applied.
            Volume = Volume;
            Pitch  = Pitch;

            // ... but wait! What if we need moar buffers?
            for (
                int i = MINIMUM_BUFFER_CHECK - PendingBufferCount;
                (i > 0) && BufferNeeded != null;
                i -= 1
                )
            {
                BufferNeeded(this, null);
            }

            // Finally.
            AudioDevice.ALDevice.PlaySource(INTERNAL_alSource);
            if (isManaged)
            {
                AudioDevice.DynamicInstancePool.Add(this);
            }
        }