Wednesday, 12 September 2012

Exporting an image from a DirectX 2D Image in Windows 8 C#/XAML Using SharpDX

PART 2

I’m working on a Windows 8 app which has a drawing element to it. The original WP7 app in Silverlight was fine because a simple drawing rendered in XAML was captured using WritableBitmap.Render and written to a file stream. This feature is missing from the Windows 8 API, so it’s impossible to write a pure C#/XAML app which can export a user created image. To get round this it’s possible to use DirectX/XAML/C++ to create a XAML UI which can draw DirectX images.

DirectX/XAML/C++ offers a number of XAML containers which interface with DirectX and have different behaviours:



I wanted to use a SurfaceImageSource, so I could have my DirectX image in line with other XAML controls and containers.

The big problem is that I don’t want to write a whole app in C++, it would take me a lot longer than C# and it seemed like a sledge hammer to crack a nut using full C++/DirectX for a simple application.

So after much research and stress about what to do, I found SharpDX and thought all my prayers had been answered! SharpDX is a full DirectX to C# interop library which allows DirectX to be brought into C#/XAML apps in the same way as C++/XAML apps.


The major problem was how to save the image you’ve drawn out of the DirectX image? There are a small number of examples of how to do it in C++, so after a lot of cross referencing the SharpDX source and tips from Alexandre Mutel on interfacing with a WICStream, I managed to get it working.

This save method was tested inside the EffectRenderer in the SharpDX lighting effect sample. This is the whole code so you don’t need to paste it back together in sections:

public async void Save()
{
    // Launch file picker
    Windows.Storage.Pickers.FileSavePicker picker = new Windows.Storage.Pickers.FileSavePicker();
    picker.FileTypeChoices.Add("PNG", new List<string>() { ".png" });
    var file = await picker.PickSaveFileAsync();
    if (file == null)
        return;

    // Get stream
    var fStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

    var factory = new ImagingFactory();

    MemoryStream ms = new MemoryStream(100000);
    ms.Position = 0;

    // Create a WIC outputstream
    WICStream stream = new WICStream(factory, ms);

    var size = this._deviceManager.ContextDirect2D.PixelSize;
    var format = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

    // Initialize a Png encoder with this stream
    var wicBitmapEncoder = new SharpDX.WIC.PngBitmapEncoder(factory, BitmapEncoderGuids.Png);
    wicBitmapEncoder.Initialize(stream);

    // Create a Frame encoder
    var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder);
    wicFrameEncoder.Initialize();

    // Create image encoder
    ImageEncoder wicImageEncoder;
    SharpDX.WIC.ImagingFactory2 factory2 = new ImagingFactory2();
    factory2.CreateImageEncoder(this._deviceManager.DeviceDirect2D, out wicImageEncoder);

    var imgParams = new ImageParameters();
    imgParams.PixelFormat = format;
    imgParams.PixelHeight = (int)size.Height;
    imgParams.PixelWidth = (int)size.Width;
    wicImageEncoder.WriteFrame(_effectGraph.Output, wicFrameEncoder, ref imgParams);

    // Commit changes
    wicFrameEncoder.Commit();
    wicBitmapEncoder.Commit();

    byte[] buffer = new byte[ms.Length];
    ms.Position = 0;
    await ms.ReadAsync(buffer, 0, (int)ms.Length);
    var opStream = fStream.AsStreamForWrite();
    await opStream.WriteAsync(buffer, 0, buffer.Length);
    await opStream.FlushAsync();

    // Dispose
    wicFrameEncoder.Dispose();
    wicBitmapEncoder.Dispose();
    stream.Dispose();
    ms.Dispose();
    opStream.Dispose();    
    factory.Dispose();
}

The first section gets a file stream from the user to write the data to once it’s been extracted from the image, then creates an intermediary MemoryStream for the WICStream to interface with (Alexandre pointed out that the Win8 RandomAccessStream will not interface with a WICStream since it needs to perform seek operations) and finally the WICStream itself which WIC will use to write the image to.

The second section creates a Bitmap Encoder, Frame Encoder and Image Encoder and writes the image frame into the stream.

The final section and the bit which caused me a lot of problems, is getting the data from the stream. The encoders all need committing in order, but in many C++ examples the WICStream is also committed which should flush the stream to it’s destination, however it was throwing an exception:

An exception of type 'SharpDX.SharpDXException' occurred in SharpDX.DLL but was not handled in user code

Additional information: HRESULT: [0x88982F50], Module: [Unknown], ApiCode: [Unknown/Unknown], Message: The component cannot be found.

If there is a handler for this exception, the program may be safely continued.

This isn’t particularly helpful, but I was advised that the WIC stream doesn’t need flushing as the underlying stream should take care of this. At this point I could see the memory stream had a size, but when I wrote it to a buffer it was coming out all zeros. This was a simple mistake – the memory stream just needs setting back to the start and it all started magically working!

All I need to do now is work out how to use DirectX to draw my picture! I hope this helps some other people as it’s been causing me a massive headache for a number of days!

Friday, 17 August 2012

Obelisk Windows 8 & WP7 MVVM Persistence Library V2.2 Release

I've just finished the Obelisk V2.2 release. It's now got support for Windows 8 persistence as well as WP7 persistence. There is a basic MVVM pattern example and an MVVM Light example for WP7 and Windows 8 The MSI only contains source for WP7 because I can't create an MSI in VS2012 yet, so you need to download the source to get the samples:

http://obelisk.codeplex.com/

Tuesday, 7 August 2012

Windows 8 Audio Player Demo

Overview

I need to include a podcast player in the app I'm writing, so I decided to write a prototype app to demo the Windows 8 audio capabilities

Source here: https://bitbucket.org/webbercross/win8audioplayer/


Features

I wanted to include the following:

  • Background capabilities
  • Live tile glyph updates
  • A custom re-templatable control
  • Hardware interaction
  • Fully working demo with all required tasks

Background Audio

I've previously use the Background Audio Agent in WP7 and was expecting something similar. There's no direct equivalent but the MediaElement is Windows 8 provides new features different to Silverlight. The new MediaElement has an 'AudioCategory' attribute which can be set to 'BackgroundCapableMedia' to allow it to continue playing while the page is not active or when the app is suspended, but not closed.

<MediaElement x:Name="mediaElement" AudioCategory="BackgroundCapableMedia" AutoPlay="False"/>

The manifest needs modifying to have a Background declaration with 'Audio' and 'Control channel' properties:


Additionally, a wide tile must be used.

Live Tile Glyph Updates

I wasn't sure at first if this was done automatically by the task, but it's not, it needs doing manually, so I wrote a helper class to do it:

public enum Glyphs
{
  none,
  activity,
  alert,
  available,
  away,
  busy,
  newMessage,
  paused,
  playing,
  unavailable,
  error,
  attention,
}

public class BadgeHelper
{
  public static void UpdateBadge(Glyphs glyph)
  {
    // Get badge xml content
    var content = BadgeUpdateManager.GetTemplateContent(Windows.UI.Notifications.BadgeTemplateType.BadgeGlyph);
    var element = content.GetElementsByTagName("badge")[0];

    // Set new glyph value
    element.Attributes[0].NodeValue = glyph.ToString();

    // Update badge
    var notification = new BadgeNotification(content);
    BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(notification);
  }
}

Normal tile:


Tile with play glyph:



Custom Template

This is the same as Silverlight and WPF, I put in some visual states for play and paused mode. The template is in the default Templates\Generic.xaml location.

Hardware Interaction

The MediaControl object has a number of events which can be subscribed to.

The Demo

[Edit] The demo is now finished, enjoy!



Monday, 6 August 2012

Windows 8 MVVM Animation Control

Overview

As we know Windows 8 Metro apps (or whatever they are called now) don't support trigger or behaviours like Silverlight and WPF apps do, even though they are XAML family. This means that once you have crafted an animation in XAML, you can't actually trigger it without code behind. This article demonstrates how to use an attached property which is toggled by a bool dependency property and controls a pair of animations.


Usage

I have a common settings page which is opened via the charm bar which I was originally showing and hiding using a bool property in the view model and a visibility converter. I wanted to have an animation so that the control would slide in and out but wanted to control it through the view model.


Dependency Property

This dependency property is fairly straight forward, it has 3 dependency properties, the first binds to a boolean property and the other two bind to a pair of opposing animations to control the slide in and out:


/// <summary>
/// This attached property binds to a bool and a pair of StoryboardAnimations
/// When the bool is true, the true animation is started
/// When the bool is false, the fals animation is started
/// </summary>
public class BoolBeginStoryBoardTrigger
{
  #region Bool Property

  public static readonly DependencyProperty BoolProperty =
    DependencyProperty.RegisterAttached("Bool", typeof(bool),   typeof(BoolBeginStoryBoardTrigger), new PropertyMetadata(false, BoolPropertyChanged));

  public static void SetBool(DependencyObject attached, bool value)
  {
    attached.SetValue(BoolProperty, value);
  }

  public static bool GetBool(DependencyObject attached)
  {
    return (bool)attached.GetValue(BoolProperty);
  }

  private static void BoolPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    if (GetBool(d))
      GetTrueStoryboard(d).Begin();
    else
      GetFalseStoryboard(d).Begin();
  }

  #endregion

  #region TrueStoryboard Property

  public static readonly DependencyProperty TrueStoryboardProperty =
    DependencyProperty.RegisterAttached("TrueStoryboard", typeof(Storyboard), typeof(BoolBeginStoryBoardTrigger), null);

  public static void SetTrueStoryboard(DependencyObject attached, Storyboard value)
  {
    attached.SetValue(TrueStoryboardProperty, value);
  }

  public static Storyboard GetTrueStoryboard(DependencyObject attached)
  {
    return (Storyboard)attached.GetValue(TrueStoryboardProperty);
  }

  #endregion

  #region FalseStoryboard Property

  public static readonly DependencyProperty FalseStoryboardProperty =
  DependencyProperty.RegisterAttached("FalseStoryboard", typeof(Storyboard), typeof(BoolBeginStoryBoardTrigger), null);

  public static void SetFalseStoryboard(DependencyObject attached, Storyboard value)
  {
    attached.SetValue(FalseStoryboardProperty, value);
  }

  public static Storyboard GetFalseStoryboard(DependencyObject attached)
  {
    return (Storyboard)attached.GetValue(FalseStoryboardProperty);
  }

  #endregion
}

The XAML

The attached property can be put anywhere after where the animations are defined. The 3 properties are set like this:

<Grid Style="{StaticResource LayoutRootStyle}"
        cmd:BoolBeginStoryBoardTrigger.Bool="{Binding IsSettingsVisible}"
        cmd:BoolBeginStoryBoardTrigger.FalseStoryboard="{StaticResource SettingsSlideIn}"
        cmd:BoolBeginStoryBoardTrigger.TrueStoryboard="{StaticResource             SettingsSlideOut}">

If you don't want to bind it to a View Model, it can easily bound to a toggle button in the view like this:


<Grid x:Name="settingsPanel"
          local:BoolBeginStoryBoardTrigger.Bool="{Binding ElementName=toggleButton, Path=IsChecked}"
          local:BoolBeginStoryBoardTrigger.FalseStoryboard="{StaticResource SettingsSlideIn}"
          local:BoolBeginStoryBoardTrigger.TrueStoryboard="{StaticResource SettingsSlideOut}"

Complete Settings Panel XAML

This is bound to the Settings view model which controls the IsSettingsVisible property.

<UserControl
    x:Class="WebberCross.Win8.Demo.View.SettingsPanel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WebberCross.Win8.Demo.Settings"
    xmlns:cmd="using:WebberCross.Win8.Demo.Commanding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Width="346" HorizontalAlignment="Right"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="346"   
    x:Name="ThisControl" Visibility="Collapsed"
    DataContext="{Binding Settings, Source={StaticResource Locator}}">
   
    <UserControl.RenderTransform>
        <TranslateTransform x:Name="settingsTranslateX" X="346" />
    </UserControl.RenderTransform>

    <UserControl.Resources>
        <Storyboard x:Key="SettingsSlideOut">
            <DoubleAnimationUsingKeyFrames
                Storyboard.TargetProperty="X"
                Storyboard.TargetName="settingsTranslateX">
                <EasingDoubleKeyFrame KeyTime="0:0:0" Value="346" />
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0" >
                    <EasingDoubleKeyFrame.EasingFunction>
                        <PowerEase EasingMode="EaseOut"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames
                Storyboard.TargetProperty="Visibility"
                Storyboard.TargetName="ThisControl">
                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="Visible" />                  
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>

        <Storyboard x:Key="SettingsSlideIn">
            <DoubleAnimationUsingKeyFrames
        Storyboard.TargetProperty="X"
        Storyboard.TargetName="settingsTranslateX">
                <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0" />
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="346" >
                    <EasingDoubleKeyFrame.EasingFunction>
                        <PowerEase EasingMode="EaseIn"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>

    <Grid Style="{StaticResource LayoutRootStyle}"
        cmd:BoolBeginStoryBoardTrigger.Bool="{Binding IsSettingsVisible}"
        cmd:BoolBeginStoryBoardTrigger.FalseStoryboard="{StaticResource SettingsSlideIn}"
        cmd:BoolBeginStoryBoardTrigger.TrueStoryboard="{StaticResource SettingsSlideOut}">
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <ToggleButton  Style="{StaticResource BackToggleButtonStyle}"
                           IsChecked="{Binding IsSettingsVisible, Mode=TwoWay}"/>
            <TextBlock x:Name="pageTitle" Text="{Binding SettingsTitle}" Style="{StaticResource PageSubheaderTextStyle}" Grid.Column="1"/>
        </Grid>

        <Grid Grid.Row="1" Margin="40,0,20,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="20" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <TextBlock Text="{Binding PushNotificationsText, Mode=OneWay}" VerticalAlignment="Center"
                       Style="{StaticResource TitleTextStyle}" />
            <ToggleSwitch Grid.Column="1" IsOn="{Binding IsPushEnabled, Mode=TwoWay}" />

            <TextBlock Grid.Row="2" Text="{Binding FontSizeText, Mode=OneWay}" Style="{StaticResource TitleTextStyle}" />
            <ComboBox Grid.Row="2" Grid.Column="1" ItemsSource="{Binding FontSizes}" DisplayMemberPath="Key"
                                SelectedItem="{Binding SelectedFontSize, Mode=TwoWay}" 
                                Grid.ColumnSpan="2"  >
            </ComboBox>
        </Grid>
    </Grid>
</UserControl>


Settings Service

The next article discusses how to implement the settings service.

http://geoffwebbercross.blogspot.co.uk/2012/08/windows-8-mvvm-settings-service.html