CentOS7.5安装Mongodb4.01

官网下载Monogodb安装包,将其上传至服务器。

解压包:
tar -zxf mongodb-linux-x86_64-4.0.1.tgz

Mongodb包不用编译,直接解压就可以用。
将解压出的文件夹移至安装目录,我是放在/usr/local/中:
mv mongodb-linux-x86_64-4.0.1 /usr/local/

为方便,创建软链接:
ln -s /usr/local/mongodb-linux-x86_64-4.0.1/ /usr/local/mongodb

为数据和Log文件创建放置目录,这个可以随意,只要将目录位置写进配置文件中即可。
cd /usr/local/mongodb/
mkdir -p data/db
mkdir logs
touch logs/mongodb.log

创建一个配置文件:
mkdir conf/mongodb.conf

进入编辑它:
vi conf/mongodb.conf

fork=true   ## 允许程序在后台运行

#auth=true  ## 开始认证

logpath=/usr/local/mongodb/logs/mongodb.log

logappend=true      # 写日志的模式:设置为true为追加。默认是覆盖

dbpath=/usr/local/mongodb/data/db    ## 数据存放目录

pidfilepath=/usr/local/mongodb/logs/mongodb.pid    # 进程ID,没有指定则启动时候就没有PID文件。默认缺省。

port=27017

#bind_ip=127.0.0.1 192.168.1.10   # 绑定地址。默认127.0.0.1,只能通过本地连接。192.168.1.10是该主机局网IP

# 设置为true,修改数据目录存储模式,每个数据库的文件存储在DBPATH指定目录的不同的文件夹中。
# 使用此选项,可以配置的MongoDB将数据存储在不同的磁盘设备上,以提高写入吞吐量或磁盘容量。默认为false。
# 如果要启用,初始化时就就配置次选项,如果后面才启用,会冲突。
directoryperdb=true

# 禁止日志
# 对应 journal 启用操作日志,以确保写入持久性和数据的一致性,会在dbpath目录下创建journal目录
nojournal = false

## max connections
# 最大连接数。默认值:取决于系统(即的ulimit和文件描述符)限制。
# MongoDB中不会限制其自身的连接。当设置大于系统的限制,则无效,以系统限制为准。
# 设置该值的高于连接池和总连接数的大小,以防止尖峰时候的连接。
# 注意:不能设置该值大于819。
maxConns=100

将mongodb/bin文件路径加入PATH环境变量中:
vim /etc/profile
在最末尾添加如下:
PATH=$PATH:/usr/local/mongodb/bin
保存退出。
再source /etc/profile

添加开机自启动:

vim /usr/lib/systemd/system/mongod.service

[Unit]
Description=mongodb
After=network.target remote-fs.target nss-lookup.target

[Install]
WantedBy=multi-user.target

[Service]
Type=forking
ExecStart=/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/conf/mongodb.conf
ExecStop=/usr/local/mongodb/bin/mongod --shutdown --config /usr/local/mongodb/conf/mongodb.conf
PrivateTmp=true

保存退出。

开启Mongod服务:
systemctl start mongod

加入自启动功能:
systemctl enable mongod

客户端进入:
mongo

完毕!

 

 

 

UniRx – Unity响应式编程插件[转]

UniRx – Unity响应式编程插件

插件作者Yoshifumi Kawai(neuecc) 
本文译者:郑洪智 – 你的技术探路者

Gitter

UniRx是什么?

UniRx (Unity响应式编程插件) 重写了.Net的响应式扩展。.Net官方的Rx很棒,但是在Unity中无法使用,并且与IOS的IL2CPP有兼容性问题。这个库这些问题并且添加了一些Unity专属的工具类。 支持的平台有:PC/Mac/Android/iOS/WP8/WindowsStore/等等,并且支持Unity4.6之后的所有版本。

UniRx 在 Unity Asset Store 的地址(免费) – http://u3d.as/content/neuecc/uni-rx-reactive-extensions-for-unity/7tT

演讲PPT – http://www.slideshare.net/neuecc/unirx-reactive-extensions-for-unityen

更新博客 – https://medium.com/@neuecc

在Unity论坛中提供支持 – http://forum.unity3d.com/threads/248535-UniRx-Reactive-Extensions-for-Unity

更新日志 UniRx/releases

UniRx 包含 Core Library (Port of Rx) + Platform Adaptor (MainThreadScheduler/FromCoroutine/etc) + Framework (ObservableTriggers/ReactiveProeperty/etc)

为什么用Rx?

一般来说,网络操作需要用到 WWW  Coroutine。但是使用 Coroutine 对于异步操作来说不是一个好的选择,原因如下:

  1. 协程不能有返回值,因为它返回类型必须是IEnumerator
  2. 协程不能处理异常,因为 yield return 语句没办法被 try-catch

会造成代码大面积的强耦合。

Rx就是为了解决异步问题而来的。Rx可以让异步操作更优雅,使用事件驱动编程,使用LINQ操作。

游戏循环 (every Update, OnCollisionEnter, etc), 传感器数据 (Kinect, Leap Motion, VR Input, etc.) 都是事件。Rx将事件转化为响应式的序列,通过LINQ操作可以很简单地组合起来,还支持时间操作。

Unity通常是单线程,但是UniRx可以让多线程更容易。

UniRx 可以简化 uGUI 的编程,所有的UI事件 (clicked, valuechanged, etc) 可以转化为 UniRx 的事件流。

简介

介绍 Rx 的非常棒的文章: The introduction to Reactive Programming you’ve been missing.

下面的代码实现了双击的检测:

var clickStream = Observable.EveryUpdate()
    .Where(_ => Input.GetMouseButtonDown(0));

clickStream.Buffer(clickStream.Throttle(TimeSpan.FromMilliseconds(250)))
    .Where(xs => xs.Count >= 2)
    .Subscribe(xs => Debug.Log("DoubleClick Detected! Count:" + xs.Count));

 

这个例子仅用5行代码,展示出了下面的特性:

  • 将游戏循环为 (Update) 变成事件流
  • 组合事件流
  • 合并自身事件流
  • 基于时间的操作非常简单

网络操作

使用 ObservableWWW 进行异步网络操作。它的 Get/Post 方法返回可订阅(Subscribe)的 IObservables:

ObservableWWW.Get("http://google.co.jp/")
    .Subscribe(
        x => Debug.Log(x.Substring(0, 100)), // onSuccess
        ex => Debug.LogException(ex)); // onError

 

Rx 可以组合和取消。你也可以通过LINQ表达式进行查询:

// composing asynchronous sequence with LINQ query expressions
var query = from google in ObservableWWW.Get("http://google.com/")
            from bing in ObservableWWW.Get("http://bing.com/")
            from unknown in ObservableWWW.Get(google + bing)
            select new { google, bing, unknown };

var cancel = query.Subscribe(x => Debug.Log(x));

// Call Dispose is cancel.
cancel.Dispose();

 

并行请求使用 Observable.WhenAll :

// Observable.WhenAll is for parallel asynchronous operation
// (It's like Observable.Zip but specialized for single async operations like Task.WhenAll)
var parallel = Observable.WhenAll(
    ObservableWWW.Get("http://google.com/"),
    ObservableWWW.Get("http://bing.com/"),
    ObservableWWW.Get("http://unity3d.com/"));

parallel.Subscribe(xs =>
{
    Debug.Log(xs[0].Substring(0, 100)); // google
    Debug.Log(xs[1].Substring(0, 100)); // bing
    Debug.Log(xs[2].Substring(0, 100)); // unity
});

 

也可以获取进度信息:

// notifier for progress use ScheudledNotifier or new Progress<float>(/* action */)
var progressNotifier = new ScheduledNotifier<float>();
progressNotifier.Subscribe(x => Debug.Log(x)); // write www.progress

// pass notifier to WWW.Get/Post
ObservableWWW.Get("http://google.com/", progress: progressNotifier).Subscribe();

 

错误处理:

// If WWW has .error, ObservableWWW throws WWWErrorException to onError pipeline.
// WWWErrorException has RawErrorMessage, HasResponse, StatusCode, ResponseHeaders
ObservableWWW.Get("http://www.google.com/404")
    .CatchIgnore((WWWErrorException ex) =>
    {
        Debug.Log(ex.RawErrorMessage);
        if (ex.HasResponse)
        {
            Debug.Log(ex.StatusCode);
        }
        foreach (var item in ex.ResponseHeaders)
        {
            Debug.Log(item.Key + ":" + item.Value);
        }
    })
    .Subscribe();

 

和 IEnumerators 一起使用(协程)

IEnumerator (协程) 是Unity主要的异步工具。UniRx 集成了协程和 IObservables。 你可以用协程写异步代码,然后用 UniRx 来组织他们。这是控制异步流的最好的方法。

// two coroutines

IEnumerator AsyncA()
{
    Debug.Log("a start");
    yield return new WaitForSeconds(1);
    Debug.Log("a end");
}

IEnumerator AsyncB()
{
    Debug.Log("b start");
    yield return new WaitForEndOfFrame();
    Debug.Log("b end");
}

// main code
// Observable.FromCoroutine converts IEnumerator to Observable<Unit>.
// You can also use the shorthand, AsyncA().ToObservable()

// after AsyncA completes, run AsyncB as a continuous routine.
// UniRx expands SelectMany(IEnumerator) as SelectMany(IEnumerator.ToObservable())
var cancel = Observable.FromCoroutine(AsyncA)
    .SelectMany(AsyncB)
    .Subscribe();

// you can stop a coroutine by calling your subscription's Dispose.
cancel.Dispose();

 

在 Unity 5.3 或更新版本里, 可以使用 ToYieldInstruction 将 Observable 转为 Coroutine。

IEnumerator TestNewCustomYieldInstruction()
{
    // wait Rx Observable.
    yield return Observable.Timer(TimeSpan.FromSeconds(1)).ToYieldInstruction();

    // you can change the scheduler(this is ignore Time.scale)
    yield return Observable.Timer(TimeSpan.FromSeconds(1), Scheduler.MainThreadIgnoreTimeScale).ToYieldInstruction();

    // get return value from ObservableYieldInstruction
    var o = ObservableWWW.Get("http://unity3d.com/").ToYieldInstruction(throwOnError: false);
    yield return o;

    if (o.HasError) { Debug.Log(o.Error.ToString()); }
    if (o.HasResult) { Debug.Log(o.Result); }

    // other sample(wait until transform.position.y >= 100) 
    yield return this.transform.ObserveEveryValueChanged(x => x.position).FirstOrDefault(p => p.y >= 100).ToYieldInstruction();
}

 

通常,协程想要返回一个值需要使用回调callback。Observable.FromCoroutine 可以将协程转为可以取消的 IObservable[T]。

// public method
public static IObservable<string> GetWWW(string url)
{
    // convert coroutine to IObservable
    return Observable.FromCoroutine<string>((observer, cancellationToken) => GetWWWCore(url, observer, cancellationToken));
}

// IObserver is a callback publisher
// Note: IObserver's basic scheme is "OnNext* (OnError | Oncompleted)?" 
static IEnumerator GetWWWCore(string url, IObserver<string> observer, CancellationToken cancellationToken)
{
    var www = new UnityEngine.WWW(url);
    while (!www.isDone && !cancellationToken.IsCancellationRequested)
    {
        yield return null;
    }

    if (cancellationToken.IsCancellationRequested) yield break;

    if (www.error != null)
    {
        observer.OnError(new Exception(www.error));
    }
    else
    {
        observer.OnNext(www.text);
        observer.OnCompleted(); // IObserver needs OnCompleted after OnNext!
    }
}

 

这有一些例子。接下来是一个多OnNext模式。

public static IObservable<float> ToObservable(this UnityEngine.AsyncOperation asyncOperation)
{
    if (asyncOperation == null) throw new ArgumentNullException("asyncOperation");

    return Observable.FromCoroutine<float>((observer, cancellationToken) => RunAsyncOperation(asyncOperation, observer, cancellationToken));
}

static IEnumerator RunAsyncOperation(UnityEngine.AsyncOperation asyncOperation, IObserver<float> observer, CancellationToken cancellationToken)
{
    while (!asyncOperation.isDone && !cancellationToken.IsCancellationRequested)
    {
        observer.OnNext(asyncOperation.progress);
        yield return null;
    }
    if (!cancellationToken.IsCancellationRequested)
    {
        observer.OnNext(asyncOperation.progress); // push 100%
        observer.OnCompleted();
    }
}

// usecase
Application.LoadLevelAsync("testscene")
    .ToObservable()
    .Do(x => Debug.Log(x)) // output progress
    .Last() // last sequence is load completed
    .Subscribe();

 

用于多线程

// Observable.Start is start factory methods on specified scheduler
// default is on ThreadPool
var heavyMethod = Observable.Start(() =>
{
    // heavy method...
    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
    return 10;
});

var heavyMethod2 = Observable.Start(() =>
{
    // heavy method...
    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
    return 10;
});

// Join and await two other thread values
Observable.WhenAll(heavyMethod, heavyMethod2)
    .ObserveOnMainThread() // return to main thread
    .Subscribe(xs =>
    {
        // Unity can't touch GameObject from other thread
        // but use ObserveOnMainThread, you can touch GameObject naturally.
        (GameObject.Find("myGuiText")).guiText.text = xs[0] + ":" + xs[1];
    }); 

 

默认调度器

UniRx 中基于时间的操作(Interval, Timer, Buffer(timeSpan), etc) 使用 Scheduler.MainThread 作为他们的默认调度器。这意味大多数操作符(除了Observable.Start)在单线程上工作,所以 ObserverOn 不是必须的而且不需要处理线程安全。这和标准的 RxNet 不太一样,但是更符合Unity环境。

Scheduler.MainThread 会受 Time.timeScale 的影响。如果你想要忽略time scale,使用 Scheduler.MainThreadIgnoreTimeScale 

MonoBehaviour的触发器

使用 UniRx.Triggers 可以处理Monobehaviour的事件:

using UniRx;
using UniRx.Triggers; // need UniRx.Triggers namespace

public class MyComponent : MonoBehaviour
{
    void Start()
    {
        // Get the plain object
        var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        // Add ObservableXxxTrigger for handle MonoBehaviour's event as Observable
        cube.AddComponent<ObservableUpdateTrigger>()
            .UpdateAsObservable()
            .SampleFrame(30)
            .Subscribe(x => Debug.Log("cube"), () => Debug.Log("destroy"));

        // destroy after 3 second:)
        GameObject.Destroy(cube, 3f);
    }
}

 

支持的触发器列表 UniRx.wiki#UniRx.Triggers.

通过订阅Component/GameObject的扩展方法,控制这些触发器可以更简单。这些方法会自动添加ObservableTrigger到物体上(除了 ObservableEventTrigger and ObservableStateMachineTrigger):

using UniRx;
using UniRx.Triggers; // need UniRx.Triggers namespace for extend gameObejct

public class DragAndDropOnce : MonoBehaviour
{
    void Start()
    {
        // All events can subscribe by ***AsObservable
        this.OnMouseDownAsObservable()
            .SelectMany(_ => this.UpdateAsObservable())
            .TakeUntil(this.OnMouseUpAsObservable())
            .Select(_ => Input.mousePosition)
            .Subscribe(x => Debug.Log(x));
    }
}

 

之前的UniRx提供了 ObservableMonoBehaviour。这是一个不再支持的过时的接口。请使用 UniRx.Triggers 代替。

创建自定义的触发器

处理Unity的事件的最好办法是转成Observable。如果UniRx自带的触发器还不够的话,你也可以自己创建触发器。下面是一个UGUI的长按触发器:

public class ObservableLongPointerDownTrigger : ObservableTriggerBase, IPointerDownHandler, IPointerUpHandler
{
    public float IntervalSecond = 1f;

    Subject<Unit> onLongPointerDown;

    float? raiseTime;

    void Update()
    {
        if (raiseTime != null && raiseTime <= Time.realtimeSinceStartup)
        {
            if (onLongPointerDown != null) onLongPointerDown.OnNext(Unit.Default);
            raiseTime = null;
        }
    }

    void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
    {
        raiseTime = Time.realtimeSinceStartup + IntervalSecond;
    }

    void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
    {
        raiseTime = null;
    }

    public IObservable<Unit> OnLongPointerDownAsObservable()
    {
        return onLongPointerDown ?? (onLongPointerDown = new Subject<Unit>());
    }

    protected override void RaiseOnCompletedOnDestroy()
    {
        if (onLongPointerDown != null)
        {
            onLongPointerDown.OnCompleted();
        }
    }
}

 

使用起来和自带触发器一样简单:

var trigger = button.AddComponent<ObservableLongPointerDownTrigger>();

trigger.OnLongPointerDownAsObservable().Subscribe();

 

Observable 生命周期管理

OnCompleted 什么时候会被调用?使用UniRx的时候Subscription的生命周期管理非常重要。ObservableTriggers 在attached的物体被销毁的时候调用。其他静态的方法 (Observable.Timer, Observable.EveryUpdate, etc…) 不会自动停止,需要手动去管理。

Rx 提供了一些方法, 例如 IDisposable.AddTo 可以让你一次性释放多个subscriptions:

// CompositeDisposable is similar with List<IDisposable>, manage multiple IDisposable
CompositeDisposable disposables = new CompositeDisposable(); // field

void Start()
{
    Observable.EveryUpdate().Subscribe(x => Debug.Log(x)).AddTo(disposables);
}

void OnTriggerEnter(Collider other)
{
    // .Clear() => Dispose is called for all inner disposables, and the list is cleared.
    // .Dispose() => Dispose is called for all inner disposables, and Dispose is called immediately after additional Adds.
    disposables.Clear();
}

 

如果你想在物体销毁时自动释放,可以用AddTo(GameObject/Component):

void Start()
{
    Observable.IntervalFrame(30).Subscribe(x => Debug.Log(x)).AddTo(this);
}

 

AddTo 方法可以带来自动释放。如果你需要一些特殊的 OnCompleted 处理,使用 TakeWhile, TakeUntil, TakeUntilDestroy  TakeUntilDisable 

Observable.IntervalFrame(30).TakeUntilDisable(this)
    .Subscribe(x => Debug.Log(x), () => Debug.Log("completed!"));

 

处理事件时,Repeat 时一个重要但是很危险的方法。可能会造成死循环,一定要小心处理:

using UniRx;
using UniRx.Triggers;

public class DangerousDragAndDrop : MonoBehaviour
{
    void Start()
    {
        this.gameObject.OnMouseDownAsObservable()
            .SelectMany(_ => this.gameObject.UpdateAsObservable())
            .TakeUntil(this.gameObject.OnMouseUpAsObservable())
            .Select(_ => Input.mousePosition)
            .Repeat() // dangerous!!! Repeat cause infinite repeat subscribe at GameObject was destroyed.(If in UnityEditor, Editor is freezed)
            .Subscribe(x => Debug.Log(x));
    }
}

 

UniRx额外提供了一个安全的Repeat方法。RepeatSafe: 如果”OnComplete”连续调用,Repeat会自动停止。 RepeatUntilDestroy(gameObject/component), RepeatUntilDisable(gameObject/component) 可以在gameobject被销毁时停止Repeat:

this.gameObject.OnMouseDownAsObservable()
    .SelectMany(_ => this.gameObject.UpdateAsObservable())
    .TakeUntil(this.gameObject.OnMouseUpAsObservable())
    .Select(_ => Input.mousePosition)
    .RepeatUntilDestroy(this) // safety way
    .Subscribe(x => Debug.Log(x));            

 

UniRx保证动态observable(FromEvent/Subject/ReactiveProperty/UnityUI.AsObservable…, there are like event) 内有未处理的异常时也能持续工作。什么意思呢?如果在Subscribe内subscribe,里面subscribe的异样不会造成外部的subscribe失效。

button.OnClickAsObservable().Subscribe(_ =>
{
    // If throws error in inner subscribe, but doesn't detached OnClick event.
    ObservableWWW.Get("htttp://error/").Subscribe(x =>
    {
        Debug.Log(x);
    });
});

 

这样在处理用户事件时很有用。

所有类的实例提供了一个 ObserveEveryValueChanged 方法,可以在每帧监听值的变化:

// watch position change
this.transform.ObserveEveryValueChanged(x => x.position).Subscribe(x => Debug.Log(x));

 

这很有用。如果监听的目标是一个GameObject, 会在目标被销毁时停止并调用OnCompleted。如果监听目标是C#的对象,OnCompleted会在GC时调用。

将Unity回调转为IObservable

使用Subject (或AsyncSubject用于异步操作):

public class LogCallback
{
    public string Condition;
    public string StackTrace;
    public UnityEngine.LogType LogType;
}

public static class LogHelper
{
    static Subject<LogCallback> subject;

    public static IObservable<LogCallback> LogCallbackAsObservable()
    {
        if (subject == null)
        {
            subject = new Subject<LogCallback>();

            // Publish to Subject in callback
            UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
            {
                subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type });
            });
        }

        return subject.AsObservable();
    }
}

// method is separatable and composable
LogHelper.LogCallbackAsObservable()
    .Where(x => x.LogType == LogType.Warning)
    .Subscribe();

LogHelper.LogCallbackAsObservable()
    .Where(x => x.LogType == LogType.Error)
    .Subscribe();

 

Unity5中移除了 Application.RegisterLogCallback,并用 Application.logMessageReceived替代。所以可以更简单地用 Observable.FromEvent

public static IObservable<LogCallback> LogCallbackAsObservable()
{
    return Observable.FromEvent<Application.LogCallback, LogCallback>(
        h => (condition, stackTrace, type) => h(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type }),
        h => Application.logMessageReceived += h, h => Application.logMessageReceived -= h);
}

 

流式日志记录器Stream Logger

// using UniRx.Diagnostics;

// logger is threadsafe, define per class with name.
static readonly Logger logger = new Logger("Sample11");

// call once at applicationinit
public static void ApplicationInitialize()
{
    // Log as Stream, UniRx.Diagnostics.ObservableLogger.Listener is IObservable<LogEntry>
    // You can subscribe and output to any place.
    ObservableLogger.Listener.LogToUnityDebug();

    // for example, filter only Exception and upload to web.
    // (make custom sink(IObserver<EventEntry>) is better to use)
    ObservableLogger.Listener
        .Where(x => x.LogType == LogType.Exception)
        .Subscribe(x =>
        {
            // ObservableWWW.Post("", null).Subscribe();
        });
}

// Debug is write only DebugBuild.
logger.Debug("Debug Message");

// or other logging methods
logger.Log("Message");
logger.Exception(new Exception("test exception"));

 

调试Debugging

UniRx.Diagnostics 中的 Debug 操作符可以帮助调试。

// needs Diagnostics using
using UniRx.Diagnostics;

---

// [DebugDump, Normal]OnSubscribe
// [DebugDump, Normal]OnNext(1)
// [DebugDump, Normal]OnNext(10)
// [DebugDump, Normal]OnCompleted()
{
    var subject = new Subject<int>();

    subject.Debug("DebugDump, Normal").Subscribe();

    subject.OnNext(1);
    subject.OnNext(10);
    subject.OnCompleted();
}

// [DebugDump, Cancel]OnSubscribe
// [DebugDump, Cancel]OnNext(1)
// [DebugDump, Cancel]OnCancel
{
    var subject = new Subject<int>();

    var d = subject.Debug("DebugDump, Cancel").Subscribe();

    subject.OnNext(1);
    d.Dispose();
}

// [DebugDump, Error]OnSubscribe
// [DebugDump, Error]OnNext(1)
// [DebugDump, Error]OnError(System.Exception)
{
    var subject = new Subject<int>();

    subject.Debug("DebugDump, Error").Subscribe();

    subject.OnNext(1);
    subject.OnError(new Exception());
}

 

将按事件顺序显示 OnNext, OnError, OnCompleted, OnCancel, OnSubscribe 的调用并通过Debug.Log打印出来。只在 #if DEBUG时生效。

Unity-specific Extra Gems(针对Unity的超酷额外功能)

译者注:SubscribeOnMainThread()经测试现在没有效果,有BUG(2018年1月30日,UniRx版本5.5)

// Unity's singleton UiThread Queue Scheduler
Scheduler.MainThreadScheduler 
ObserveOnMainThread()/SubscribeOnMainThread()

// Global StartCoroutine runner
MainThreadDispatcher.StartCoroutine(enumerator)

// convert Coroutine to IObservable
Observable.FromCoroutine((observer, token) => enumerator(observer, token)); 

// convert IObservable to Coroutine
yield return Observable.Range(1, 10).ToYieldInstruction(); // after Unity 5.3, before can use StartAsCoroutine()

// Lifetime hooks
Observable.EveryApplicationPause();
Observable.EveryApplicationFocus();
Observable.OnceApplicationQuit();

 

Framecount-based time operators(基于帧数的时间操作)

UniRx 提供了一些基于帧数的时间操作:

Method
EveryUpdate
EveryFixedUpdate
EveryEndOfFrame
EveryGameObjectUpdate
EveryLateUpdate
ObserveOnMainThread
NextFrame
IntervalFrame
TimerFrame
DelayFrame
SampleFrame
ThrottleFrame
ThrottleFirstFrame
TimeoutFrame
DelayFrameSubscription
FrameInterval
FrameTimeInterval
BatchFrame

例如,一次延迟调用:

Observable.TimerFrame(100).Subscribe(_ => Debug.Log("after 100 frame"));

 

Every* 方法们的执行顺序是

EveryGameObjectUpdate(in MainThreadDispatcher's Execution Order) ->
EveryUpdate -> 
EveryLateUpdate -> 
EveryEndOfFrame

 

EveryGameObjectUpdate 在同一帧被调用,从 MainThreadDispatcher.Update 中调用(作者建议 MainThreadDispatcher 脚本比其他脚本先执行(ScriptExecutionOrder 设置为 -32000) 
EveryLateUpdate, EveryEndOfFrame 在同一帧调用。 
然后在下一帧调用EveryGameObjectUpdate,以此类推

MicroCoroutine(微协程)

MicroCoroutine 在内存上更有效率,而且更快。这是基于Unity的这篇博客《10000 UPDATE() CALLS》(http://blogs.unity3d.com/2015/12/23/1k-update-calls/)实现的,可以快上几十倍。MicroCoroutine会自动用于基于帧数的时间操作和ObserveEveryValueChanged。

如果你想要使用MicroCoroutine替代unity内置的协程,使用 MainThreadDispatcher.StartUpdateMicroCoroutine 或者 Observable.FromMicroCoroutine

int counter;

IEnumerator Worker()
{
    while(true)
    {
        counter++;
        yield return null;
    }
}

void Start()
{
    for(var i = 0; i < 10000; i++)
    {
        // fast, memory efficient
        MainThreadDispatcher.StartUpdateMicroCoroutine(Worker());

        // slow...
        // StartCoroutine(Worker());
    }
}

 

image

MicroCoroutine的局限是:仅支持 yield return null 并且调用的时间是根据调用的方法来确定(StartUpdateMicroCoroutine, StartFixedUpdateMicroCoroutine, StartEndOfFrameMicroCoroutine).。

如果和其他IObservable一起用,你可以检查完成属性比如isDone。

IEnumerator MicroCoroutineWithToYieldInstruction()
{
    var www = ObservableWWW.Get("http://aaa").ToYieldInstruction();
    while (!www.IsDone)
    {
        yield return null;
    }

    if (www.HasResult)
    {
        UnityEngine.Debug.Log(www.Result);
    }
}

 

uGUI集成

UniRx处理UnityEvent很简单。使用UnityEvent.AsObservable订阅事件。

public Button MyButton;
// ---
MyButton.onClick.AsObservable().Subscribe(_ => Debug.Log("clicked"));

 

将事件转为Observables,这样就可以用声名式UI编程。

public Toggle MyToggle;
public InputField MyInput;
public Text MyText;
public Slider MySlider;

// On Start, you can write reactive rules for declaretive/reactive ui programming
void Start()
{
    // Toggle, Input etc as Observable (OnValueChangedAsObservable is a helper providing isOn value on subscribe)
    // SubscribeToInteractable is an Extension Method, same as .interactable = x)
    MyToggle.OnValueChangedAsObservable().SubscribeToInteractable(MyButton);

    // Input is displayed after a 1 second delay
    MyInput.OnValueChangedAsObservable()
        .Where(x => x != null)
        .Delay(TimeSpan.FromSeconds(1))
        .SubscribeToText(MyText); // SubscribeToText is helper for subscribe to text

    // Converting for human readability
    MySlider.OnValueChangedAsObservable()
        .SubscribeToText(MyText, x => Math.Round(x, 2).ToString());
}

 

更多的响应式UI编程参见工程中例子Sample12, Sample13以及下面ReactiveProperty部分。

ReactiveProperty, ReactiveCollection

游戏数据变化时通常需要通知别的类。我们应该用属性和事件(回调)么?这通常太繁琐了。UniRx提供了ReactiveProperty类,一个轻量的属性代理。

// Reactive Notification Model
public class Enemy
{
    public ReactiveProperty<long> CurrentHp { get; private set; }

    public ReactiveProperty<bool> IsDead { get; private set; }

    public Enemy(int initialHp)
    {
        // Declarative Property
        CurrentHp = new ReactiveProperty<long>(initialHp);
        IsDead = CurrentHp.Select(x => x <= 0).ToReactiveProperty();
    }
}

// ---
// onclick, HP decrement
MyButton.OnClickAsObservable().Subscribe(_ => enemy.CurrentHp.Value -= 99);
// subscribe from notification model.
enemy.CurrentHp.SubscribeToText(MyText);
enemy.IsDead.Where(isDead => isDead == true)
    .Subscribe(_ =>
    {
        MyButton.interactable = false;
    });

 

你可以用UnityEvent.AsObservable将ReactiveProperties, ReactiveCollections 和 observables 组合起来。 所有UI组件都是observable的。

一般来说ReactiveProperties不是可序列化的或者说在Unity编辑器的Inspector面板中看不到,但是UniRx提供了特殊的子类来实现这个功能。包括Int/LongReactiveProperty, Float/DoubleReactiveProperty, StringReactiveProperty, BoolReactiveProperty,还有更多参见:InspectableReactiveProperty.cs(https://github.com/neuecc/UniRx/blob/master/Assets/Plugins/UniRx/Scripts/UnityEngineBridge/InspectableReactiveProperty.cs))。都可以在Inspector中编辑。对于自定义的枚举ReactiveProperty,写一个可检视的ReactiveProperty[T]也很容易。

如果你需要[Multiline] 或者 [Range] 添加到ReactiveProperty上,你可以使用 MultilineReactivePropertyAttribute RangeReactivePropertyAttribute 替换 Multiline  Range

这些InpsectableReactiveProperties可以在inspector面板显示,并且当他们的值发生变化时发出通知,甚至在编辑器里变化时也可以。

这个功能是实现在 InspectorDisplayDrawer (https://github.com/neuecc/UniRx/blob/master/Assets/Plugins/UniRx/Scripts/UnityEngineBridge/InspectorDisplayDrawer.cs)。你可以通过继承这个类实现你自定义的ReactiveProperties在inspector面板的绘制:

public enum Fruit
{
    Apple, Grape
}

[Serializable]
public class FruitReactiveProperty : ReactiveProperty<Fruit>
{
    public FruitReactiveProperty()
    {
    }

    public FruitReactiveProperty(Fruit initialValue)
        :base(initialValue)
    {
    }
}

[UnityEditor.CustomPropertyDrawer(typeof(FruitReactiveProperty))]
[UnityEditor.CustomPropertyDrawer(typeof(YourSpecializedReactiveProperty2))] // and others...
public class ExtendInspectorDisplayDrawer : InspectorDisplayDrawer
{
}

 

如果ReactiveProperty的值只在stream中更新,你可以用 ReadOnlyReactiveProperty 让这个属性只读。

public class Person
{
    public ReactiveProperty<string> GivenName { get; private set; }
    public ReactiveProperty<string> FamilyName { get; private set; }
    public ReadOnlyReactiveProperty<string> FullName { get; private set; }

    public Person(string givenName, string familyName)
    {
        GivenName = new ReactiveProperty<string>(givenName);
        FamilyName = new ReactiveProperty<string>(familyName);
        // If change the givenName or familyName, notify with fullName!
        FullName = GivenName.CombineLatest(FamilyName, (x, y) => x + " " + y).ToReadOnlyReactiveProperty();
    }
}

 

MVP设计模式 Model-View-(Reactive)Presenter Pattern

用UniRx可以实现MVP(MVRP)设计模式。

为什么应该用MVP模式而不是MVVM模式?Unity没有提供UI绑定机制,创建一个绑定层过于复杂并且会对性能造成影响。 尽管如此,视图还是需要更新。Presenters层知道view的组件并且能更新它们。虽然没有真的绑定,但Observables可以通知订阅者,功能上也差不多。这种模式叫做Reactive Presenter:

// Presenter for scene(canvas) root.
public class ReactivePresenter : MonoBehaviour
{
    // Presenter is aware of its View (binded in the inspector)
    public Button MyButton;
    public Toggle MyToggle;

    // State-Change-Events from Model by ReactiveProperty
    Enemy enemy = new Enemy(1000);

    void Start()
    {
        // Rx supplies user events from Views and Models in a reactive manner 
        MyButton.OnClickAsObservable().Subscribe(_ => enemy.CurrentHp.Value -= 99);
        MyToggle.OnValueChangedAsObservable().SubscribeToInteractable(MyButton);

        // Models notify Presenters via Rx, and Presenters update their views
        enemy.CurrentHp.SubscribeToText(MyText);
        enemy.IsDead.Where(isDead => isDead == true)
            .Subscribe(_ =>
            {
                MyToggle.interactable = MyButton.interactable = false;
            });
    }
}

// The Model. All property notify when their values change
public class Enemy
{
    public ReactiveProperty<long> CurrentHp { get; private set; }

    public ReactiveProperty<bool> IsDead { get; private set; }

    public Enemy(int initialHp)
    {
        // Declarative Property
        CurrentHp = new ReactiveProperty<long>(initialHp);
        IsDead = CurrentHp.Select(x => x <= 0).ToReactiveProperty();
    }
}

 

视图层是一个场景scene,是Unity的hierachy定义的。展示层在Unity初始化时将视图层绑定。XxxAsObservable方法可以很容易的创建事件信号signals,没有任何开销。SubscribeToText and SubscribeToInteractable 都是简洁的类似绑定的辅助函数。虽然这些工具很简单,但是非常有用。在Unity中使用很平滑,性能很好,而且让你的代码更简洁。

V -> RP -> M -> RP -> V 完全用响应式的方式连接。UniRx提供了所有的适配方法和类,不过其他的MVVM(or MV*)框架也可以使用。UniRx/ReactiveProperty只是一个简单的工具包。

GUI编程也可以从ObservableTriggers获益良多。ObservableTriggers将Unity事件转为Observables,所以MV(R)P模式可以用它们来组成。例如 ObservableEventTrigger 将 uGUI 事件转为 Observable:

var eventTrigger = this.gameObject.AddComponent<ObservableEventTrigger>();
eventTrigger.OnBeginDragAsObservable()
    .SelectMany(_ => eventTrigger.OnDragAsObservable(), (start, current) => UniRx.Tuple.Create(start, current))
    .TakeUntil(eventTrigger.OnEndDragAsObservable())
    .RepeatUntilDestroy(this)
    .Subscribe(x => Debug.Log(x));

 

(已过时)PresenterBase

备注: 
PresenterBase有用,不过太复杂了 
你可以仅用 Initialize 方法,在子类中调用父类就足够应付大多数情况了。 
所以不再建议使用 PresenterBase

ReactiveCommand, AsyncReactiveCommand

ReactiveCommand 抽象了按钮的interactable属性。

public class Player
{       
   public ReactiveProperty<int> Hp;     
   public ReactiveCommand Resurrect;        

   public Player()
   {        
        Hp = new ReactiveProperty<int>(1000);       

        // If dead, can not execute.        
        Resurrect = Hp.Select(x => x <= 0).ToReactiveCommand();     
        // Execute when clicked     
        Resurrect.Subscribe(_ =>        
        {       
             Hp.Value = 1000;       
        });         
    }       
}       

public class Presenter : MonoBehaviour      
{       
    public Button resurrectButton;      

    Player player;      

    void Start()
    {       
      player = new Player();        

      // If Hp <= 0, can't press button.        
      player.Resurrect.BindTo(resurrectButton);     
    }       
}       

 

AsyncReactiveCommand是ReactiveCommand的变种,它的 CanExecute (通常绑定到button的interactable) 在异步操作完成后变为false。

public class Presenter : MonoBehaviour      
{       
    public UnityEngine.UI.Button button;        

    void Start()
    {       
        var command = new AsyncReactiveCommand();       

        command.Subscribe(_ =>      
        {       
            // heavy, heavy, heavy method....       
            return Observable.Timer(TimeSpan.FromSeconds(3)).AsUnitObservable();        
        });     

        // after clicked, button shows disable for 3 seconds        
        command.BindTo(button);     

        // Note:shortcut extension, bind aync onclick directly      
        button.BindToOnClick(_ =>       
        {       
            return Observable.Timer(TimeSpan.FromSeconds(3)).AsUnitObservable();        
        });     
    }       
}       

 

AsyncReactiveCommand 有三个构造方法。

  • () – CanExecute is changed to false until async execution finished
  • (IObservable<bool> canExecuteSource) – 当 canExecuteSource 变为 true 并且没有在执行的时候 CanExecute 变为true 。
  • (IReactiveProperty<bool> sharedCanExecute) – 在多个AsyncReactiveCommands之间共享运行状态,如果一个 AsyncReactiveCommand 在执行,那么其他的 AsyncReactiveCommands(拥有相同 sharedCanExecute 属性) 的 CanExecute 变为 false 直到异步操作完成。
public class Presenter : MonoBehaviour
{
    public UnityEngine.UI.Button button1;
    public UnityEngine.UI.Button button2;

    void Start()
    {
        // share canExecute status.
        // when clicked button1, button1 and button2 was disabled for 3 seconds.

        var sharedCanExecute = new ReactiveProperty<bool>();

        button1.BindToOnClick(sharedCanExecute, _ =>
        {
            return Observable.Timer(TimeSpan.FromSeconds(3)).AsUnitObservable();
        });

        button2.BindToOnClick(sharedCanExecute, _ =>
        {
            return Observable.Timer(TimeSpan.FromSeconds(3)).AsUnitObservable();
        });
    }
}

 

MessageBroker, AsyncMessageBroker(消息代理,异步消息代理)

MessageBroker 是基于 Rx 的内存发布订阅(pubsub)系统,基于类型筛选。

public class TestArgs
{
    public int Value { get; set; }
}

---

// Subscribe message on global-scope.
MessageBroker.Default.Receive<TestArgs>().Subscribe(x => UnityEngine.Debug.Log(x));

// Publish message
MessageBroker.Default.Publish(new TestArgs { Value = 1000 });

 

AsyncMessageBroker 是 MessageBroker 的一个变种, 可以处理异步的 Publish 调用。

AsyncMessageBroker.Default.Subscribe<TestArgs>(x =>
{
    // show after 3 seconds.
    return Observable.Timer(TimeSpan.FromSeconds(3))
        .ForEachAsync(_ =>
        {
            UnityEngine.Debug.Log(x);
        });
});

AsyncMessageBroker.Default.PublishAsync(new TestArgs { Value = 3000 })
    .Subscribe(_ =>
    {
        UnityEngine.Debug.Log("called all subscriber completed");
    });

 

UniRx.Toolkit

UniRx.Toolkit 包含了一些Rx风格的工具。目前报错 ObjectPool  AsyncObjectPool。可以 Rent, Return and PreloadAsync (在rent操作之前预加载对象池)。

// sample class
public class Foobar : MonoBehaviour
{
    public IObservable<Unit> ActionAsync()
    {
        // heavy, heavy, action...
        return Observable.Timer(TimeSpan.FromSeconds(3)).AsUnitObservable();
    }
}

public class FoobarPool : ObjectPool<Foobar>
{
    readonly Foobar prefab;
    readonly Transform hierarchyParent;

    public FoobarPool(Foobar prefab, Transform hierarchyParent)
    {
        this.prefab = prefab;
        this.hierarchyParent = hierarchyParent;
    }

    protected override Foobar CreateInstance()
    {
        var foobar = GameObject.Instantiate<Foobar>(prefab);
        foobar.transform.SetParent(hierarchyParent);

        return foobar;
    }

    // You can overload OnBeforeRent, OnBeforeReturn, OnClear for customize action.
    // In default, OnBeforeRent = SetActive(true), OnBeforeReturn = SetActive(false)

    // protected override void OnBeforeRent(Foobar instance)
    // protected override void OnBeforeReturn(Foobar instance)
    // protected override void OnClear(Foobar instance)
}

public class Presenter : MonoBehaviour
{
    FoobarPool pool = null;

    public Foobar prefab;
    public Button rentButton;

    void Start()
    {
        pool = new FoobarPool(prefab, this.transform);

        rentButton.OnClickAsObservable().Subscribe(_ =>
        {
            var foobar = pool.Rent();
            foobar.ActionAsync().Subscribe(__ =>
            {
                // if action completed, return to pool
                pool.Return(foobar);
            });
        });
    }
}

 

Visual Studio 分析器

Visual Studio 2015的用户可以使用一个分析器UniRxAnalyzer。它可以检测没有被subscribed的streams。

ObservableWWW 直到subscribed才会执行,所以分析器会发出警告。分析器可以从NuGet下载。

请在GitHub Issues上提交对分析器的新想法!

例子

参见 UniRx/Examples(https://github.com/neuecc/UniRx/tree/master/Assets/Plugins/UniRx/Examples)

Sample09_EventHandling 展示了如何进行资源管理,包括MainThreadDispatcher和其他一些东西。

Windows Store/Phone App (NETFX_CORE)

一些接口,如 UniRx.IObservable<T> and System.IObservable<T> 在Windows Store App中使用时会造成冲突。 
因此,如果使用 NETFX_CORE,避免使用类似 UniRx.IObservable<T> 的构造器,避免不加命名空间使用UniRx组件。这样可以解决冲突问题。

async/await Support

基于 《Upgraded Mono/.Net in Editor on 5.5.0b4》(https://forum.unity3d.com/threads/upgraded-mono-net-in-editor-on-5-5-0b4.433541/),Unity支持了 .NET 4.6 和 C# 6。UniRx 提供了 UniRxSynchronizationContext 来将多线程的任务返回到主线程。

async Task UniRxSynchronizationContextSolves()
{
    Debug.Log("start delay");

    // UniRxSynchronizationContext is automatically used.
    await Task.Delay(TimeSpan.FromMilliseconds(300));

    Debug.Log("from another thread, but you can touch transform position.");
    Debug.Log(this.transform.position);
}

 

UniRx 也直接支持 await Coroutine。

async Task CoroutineBridge()
{
    Debug.Log("start www await");

    var www = await new WWW("https://unity3d.com");

    Debug.Log(www.text);
}

 

当然了,IObservable可是可以await的。

async Task AwaitObservable()
{
    Debug.Log("start await observable");

    await Observable.NextFrame();   // like yield return null
    await Observable.TimerFrame(5); // await 5 frame

    Debug.Log("end await observable");
}

 

DLL分割

如果你想预编译UniRx,你可以自行编译dll。clone这个project,打开 UniRx.sln, 你可以看到 UniRx, 是一个完全独立的工程。你应该定义一些宏如 UNITY;UNITY_5_4_OR_NEWER;UNITY_5_4_0;UNITY_5_4;UNITY_5; + UNITY_EDITOR, UNITY_IPHONE或这其他平台宏。我们没法提供预编译的dll,因为不同版本Unity的宏是不一样的。

如果你想将UniRx用于.NET 3.5 CLR应用,你可以使用UniRx.Library UniRx.Library 不依赖UnityEngine,编译 UniRx.Library 需要定义 UniRxLibrary 宏。另外预编译的 UniRx.Library 库可以在NuGet获取到。

Install-Package UniRx(https://www.nuget.org/packages/UniRx)

其他参考

UniRx API文档。

The home of ReactiveX. Introduction, All operators are illustrated with graphical marble diagrams, there makes easy to understand. And UniRx is official ReactiveX Languages.

A great online tutorial and eBook.

Many videos, slides and documents for Rx.NET.

Intro slide by @torisoup

Intro slide and sample game by @Xerios

How to integrate with PlayFab API

What game or library is using UniRx?

Games 
– [Farm Away!][(http://www.farmawaygame.com/) 
 Build Away! 
 AdVenture Capitalist 
 AdVenture Communist

Libraries

  • PhotonWire – Typed Asynchronous RPC Layer for Photon Server + Unity.
  • uFrame Game Framework – MVVM/MV* framework designed for the Unity Engine.
  • EcsRx – A simple framework for unity using the ECS paradigm but with unirx for fully reactive systems.
  • ActionStreetMap Demo – ASM is an engine for building real city environment dynamically using OSM data.
  • utymap – UtyMap is library for building real city environment dynamically using various data sources (mostly, OpenStreetMap and Natural Earth).
  • Submarine – A mobile game that is made with Unity3D and RoR, WebSocket server written in Go.

If you use UniRx, please comment to UniRx/issues/152.

Help & Contribute

Support thread on the Unity forum. Ask me any question – http://forum.unity3d.com/threads/248535-UniRx-Reactive-Extensions-for-Unity

We welcome any contributions, be they bug reports, requests or pull request. 
Please consult and submit your reports or requests on GitHub issues. 
Source code is available in Assets/Plugins/UniRx/Scripts. 
This project is using Visual Studio with UnityVS.

Author’s other Unity + LINQ Assets

LINQ to GameObject is a group of GameObject extensions for Unity that allows traversing the hierarchy and appending GameObject to it like LINQ to XML. It’s free and opensource on GitHub.

Author Info

Yoshifumi Kawai(a.k.a. neuecc) is a software developer in Japan. 
He is the Director/CTO at Grani, Inc. 
Grani is a top social game developer in Japan. 
He is awarding Microsoft MVP for Visual C# since 2011. 
He is known as the creator of linq.js(LINQ to Objects for JavaScript)

Blog: https://medium.com/@neuecc (English) 
Blog: http://neue.cc/ (Japanese) 
Twitter: https://twitter.com/neuecc (Japanese)

License

This library is under the MIT License.

Some code is borrowed from Rx.NET and mono/mcs.

c#中@的3种作用[转]

1.忽略转义字符

例如

string fileName = "D:\\文本文件\\text.txt";

使用@后

string fileName = @"D:\文本文件\text.txt";

2.让字符串跨行

例如

string strSQL = "SELECT * FROM HumanResources.Employee AS e"
+ " INNER JOIN Person.Contact AS c"
+ " ON e.ContactID = c.ContactID"
+ " ORDER BY c.LastName";

使用@后

string strSQL = @"SELECT * FROM HumanResources.Employee AS e INNER JOIN Person.Contact AS c ON e.ContactID = c.ContactID ORDER BY c.LastName";

 

3.在标识符中的用法

C#是不允许关键字作为标识符(类名、变量名、方法名、表空间名等)使用的,但如果加上@之后就可以了
例如

public static void @static(int @int)
{
if (@int > 0)
{
System.Console.WriteLine("Positive Integer");
}
else if (@int == 0)
{
System.Console.WriteLine("Zero");
}
else
{
System.Console.WriteLine("Negative Integer");
}
}

 

引用参考:http://www.2cto.com/kf/201009/74766.html

关于C# 中的Attribute 特性[转]

Attribute与Property 的翻译区别

Attribute 一般译作“特性”,Property 仍然译为“属性”。

Attribute 是什么

Attribute 是一种可由用户自由定义的修饰符(Modifier),可以用来修饰各种需要被修饰的目标。

简单的说,Attribute就是一种“附着物” —— 就像牡蛎吸附在船底或礁石上一样。

这些附着物的作用是为它们的附着体追加上一些额外的信息(这些信息就保存在附着物的体内)—— 比如“这个类是我写的”或者“这个函数以前出过问题”等等。

Attribute 的作用

特性Attribute 的作用是添加元数据。
元数据可以被工具支持,比如:编译器用元数据来辅助编译,调试器用元数据来调试程序。

Attribute 与注释的区别

注释是对程序源代码的一种说明,主要目的是给人看的,在程序被编译的时候会被编译器所丢弃,因此,它丝毫不会影响到程序的执行。
而Attribute是程序代码的一部分,不但不会被编译器丢弃,而且还会被编译器编译进程序集(Assembly)的元数据(Metadata)里,在程序运行的时候,你随时可以从元数据里提取出这些附加信息来决策程序的运行。
举例:

在项目中,有一个类由两个程序员(小张和小李)共同维护。这个类起一个“工具包”(Utilities)的作用(就像.NET Framework中的Math类一样),里面含了几十个静态方法。而这些静态方法,一半是小张写的、一半是小李写的;在项目的测试中,有一些静态方法曾经出过bug,后来又被修正。这样,我们就可以把这些方面划分成这样几类:

我们分类的目的主要是在测试的时候可以按不同的类别进行测试、获取不同的效果。比如:统计两个人的工作量或者对曾经出过bug的方法进行回归测试。

如果不使用Attribute,为了区分这四类静态方法,我们只能通过注释来说明,但这种方式会有很多弊端;

如果使用Attribute,区分这四类静态方法将会变得简单多了。示例代码如下:

#define Buged
//C# 的宏定义必须出现在所有代码之前。当前只让 Buged 宏有效。
using System;
using System.Diagnostics; // 注意:这是为了使用包含在此名称空间中的ConditionalAttribute特性
namespace Con_Attribute
{
    class Program
    {
        static void Main(string[] args)
        {
            // 虽然方法都被调用了,但只有符合条件的才会被执行!
            ToolKit.FunA();
            ToolKit.FunB();
            ToolKit.FunC();
            ToolKit.FunD();
        }
    }
    class ToolKit
    {
        [ConditionalAttribute("Li")] // Attribute名称的长记法
        [ConditionalAttribute("Buged")]
        public static void FunA()
        {
            Console.WriteLine("Created By Li, Buged.");
        }
        [Conditional("Li")] // Attribute名称的短记法
        [Conditional("NoBug")]
        public static void FunB()
        {
            Console.WriteLine("Created By Li, NoBug.");
        }
        [ConditionalAttribute("Zhang")]// Attribute名称的长记法
        [ConditionalAttribute("Buged")]
        public static void FunC()
        {
            Console.WriteLine("Created By Zhang, Buged.");
        }
        [Conditional("Zhang")] // Attribute名称的短记法
        [Conditional("NoBug")]
        public static void FunD()
        {
            Console.WriteLine("Created By Zhang, NoBug.");
        }
    }
}

 

运行结果如下:

注意:运行结果是由代码中“#define Buged ”这个宏定义所决定。

分析:

1.  在本例中,我们使用了ConditionalAttribute 这个Attribute,它被包含在 System.Diagnostics 名称空间中。显然,它多半时间是用来做程序调试与诊断的。

2.  与ConditionalAttribute 相关的是一组C# 宏,它们看起来与C语言的宏别无二致,位置必须出现在所有C# 代码之前。顾名思义,ConditionalAttribute 是用来判断条件的,凡被ConditionalAttribute (或Conditional)“附着”了的方法,只有满足了条件才会执行。

3.  Attribute 就像船底上可以附着很多牡蛎一样,一个方法上也可以附着多个ConditionalAttribute 的实例。把Attribute 附着在目标上的书写格式很简单,使用方括号把Attribute 括起来,然后紧接着写Attribute 的附着体就行了。当多个Attribute 附着在同一个目标上时,就把这些Attribute 的方括号一个挨一个地书写(或者在一对方括号中书写多个Attribute),而且不必在乎它们的顺序。

4.  在使用Attribute 的时候,有“长记法”和“短记法”两种,请君自便。

由上面的第3 条和第4 条我们可以推出,以下四种Attribute 的使用方式是完全等价:

// 长记法
[ConditionalAttribute("LI")]
[ConditionalAttribute("NoBug")]
public static void Fun()
{ Console.WriteLine("Created By Li, NoBug."); }
// 短记法
[Conditional("LI")]
[Conditional("NoBug")]
public static void Fun()
{ Console.WriteLine("Created By Li, NoBug."); }
// 换序
[Conditional("NoBug")]
[Conditional("LI")]
public static void Fun()
{ Console.WriteLine("Created By Li, NoBug."); }
Attribute 的本质

从上面的代码中,我们可以看到Attribute 似乎总跟public、static 这些关键字(Keyword)出现在一起。

莫非使用了Attribute 就相当于定义了新的修饰符(Modifier)吗?让我们来一窥究竟!

示例代码如下:

#define XG //C# 的宏定义必须出现在所有代码之前
using System;
using System.Diagnostics; // 注意:这是为了使用包含在此名称空间中的ConditionalAttribute 特性
namespace Con_Attribute
{
    class Program2
    {
        [Conditional("XG")]
        static void Fun()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("http://xugang.cnblogs.com");
        }
        static void Main(

 

使用微软的中间语言反编译器查看 MSIL 中间语言中TargetMethod:void() 方法的代码,截图如下:

可以看出:Attribute 本质上就是一个类,它在所附着的目标对象上最终实例化。

仔细观察中间语言(MSIL)的代码之后,那些被C# 语言所掩盖的事实,在中间语言(MSIL)中就变得赤身裸体了。而Attribute 也变得毫无秘密!

图中红色所指的是Fun 方法及其修饰符,但Attribute 并没有出现在这里。

图中蓝色所指的是在调用mscorlib.dll 程序集中System.Diagnostics 名称空间中ConditionalAttribute 类的构造函数。

可见,Attribute 并不是修饰符,而是一个有着独特实例化形式的类!

Attribute 实例化有什么独特之处呢?

1.  它的实例是使用.custom 声明的。查看中间语言语法,你会发现.custom 是专门用来声明自定义特性的。

2.  声明Attribute 的位置是在函数体内的真正代码(IL_0000  至IL_0014 )之前。

这就从“底层”证明了Attribute不是什么“修饰符”,而是一种实例化方式比较特殊的类。

元数据的作用

MSIL 中间语言中,程序集的元数据(Metadata)记录了这个程序集里有多少个namespace、多少个类、类里有什么成员、成员的访问级别是什么。而且,元数据是以文本(也就是Unicode 字符)形式存在的,使用.NET的反射(Reflection)技术就能把它们读取出来,并形成MSIL 中的树状图、VS 里的Object  Browser 视图,以及自动代码提示功能,这些都是元数据与反射技术结合的产物。一个程序集(.EXE或.DLL)能够使用包含在自己体内的元数据来完整地说明自己,而不必像C/C++ 那样带着一大捆头文件,这就叫作“自包含性”或“自描述性”。

Attribute 的实例化

就像牡蛎天生就要吸附在礁石或船底上一样,Attribute 的实例一构造出来就必需“粘”在一个什么目标上。

Attribute 实例化的语法是相当怪异的,主要体现在以下三点:

1.  不使用new 操作符来产生实例,而是使用在方括号里调用构造函数来产生实例。

2.  方括号必需紧挨着放置在被附着目标的前面。

3.  因为方括号里空间有限,不能像使用new 那样先构造对象,然后再给对象的属性(Property)赋值。

因此,对Attribute 实例的属性赋值也在构造函数的圆括号里。

并且,Attribute 实例化时尤其要注意的是:

1.  构造函数的参数是一定要写。有几个就得写几个,因为你不写的话实例就无法构造出来。

2.  构造函数参数的顺序不能错。调用任何函数都不能改变参数的顺序,除非它有相应的重载(Overload)。因为这个顺序是固定的,有些书里称其为“定位参数”(意即“个数和位置固定的参数”)。

3. 对Attribute 实例的属性的赋值可有可无。反正它会有一个默认值,并且属性赋值的顺序不受限制。有些书里称属性赋值的参数为“具名参数”。

自定义Attribute 实例

在此,我们不使用.NET  Framework 中的各种Attribute 系统特性,而是从头自定义一个全新的Attribute 类。

示例代码如下:

using System;
namespace Con_Attribute
{
    class Program3
    {
        static void Main(string[] args)
        {
            //使用反射读取Attribute
            System.Reflection.MemberInfo info = typeof(Student); //通过反射得到Student类的信息
            Hobby hobbyAttr = (Hobby)Attribute.GetCustomAttribute(info, typeof(Hobby));
            if (hobbyAttr != null)
            {
                Console.WriteLine("类名:{0}", info.Name);
                Console.WriteLine("兴趣类型:{0}", hobbyAttr.Type);
                Console.WriteLine("兴趣指数:{0}", hobbyAttr.Level);
            }
        }
    }
    //注意:"Sports" 是给构造函数的赋值, Level = 5 是给属性的赋值。
    [Hobby("Sports", Level = 5)]
    class Student
    {
        [Hobby("Football")]
        public string profession;
        public string Profession
        {
            get { return profession; }
            set { profession = value; }
        }
    }
    //建议取名:HobbyAttribute
    class Hobby : Attribute // 必须以System.Attribute 类为基类
    {
        // 参数值为null的string 危险,所以必需在构造函数中赋值
        public Hobby(string _type) // 定位参数
        {
            this.type = _type;
        }
        //兴趣类型
        private string type;
        public string Type
        {
            get { return type; }
            set { type = value; }
        }
        //兴趣指数
        private int level;
        public int Level
        {
            get { return level; }
            set { level = value; }
        }
    }
}

为了不让代码太长,上面的示例中Hobby 类的构造函数只有一个参数,所以对“定位参数”体现的还不够淋漓尽致。大家可以为Hobby 类再添加几个属性,并在构造函数里多设置几个参数,体验一下Attribute 实例化时对参数个数及参数位置的敏感性。

能被Attribute 所附着的目标

Attribute 可以将自己的实例附着在什么目标上呢?这个问题的答案隐藏在AttributeTargets 这个枚举类型里。

这个类型的可取值集合为:

All                                         Assembly                      Class                              Constructor
Delegate                           Enum                               Event                              Field
GenericParameter         Interface                         Method                           Module
Parameter                         Property                         ReturnValue                Struct
一共是16 个可取值。上面这张表是按字母顺序排列的,并不代表它们真实值的排列顺序。

使用下面这个小程序可以查看每个枚举值对应的整数值,示例代码如下:

using System;
namespace Con_Attribute
{
    class Program4
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Assembly\t\t\t{0}", Convert.ToInt32(AttributeTargets.Assembly));
            Console.WriteLine("Module\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Module));
            Console.WriteLine("Class\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Class));
            Console.WriteLine("Struct\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Struct));
            Console.WriteLine("Enum\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Enum));
            Console.WriteLine("Constructor\t\t\t{0}", Convert.ToInt32(AttributeTargets.Constructor));
            Console.WriteLine("Method\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Method));
            Console.WriteLine("Property\t\t\t{0}", Convert.ToInt32(AttributeTargets.Property));
            Console.WriteLine("Field\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Field));
            Console.WriteLine("Event\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Event));
            Console.WriteLine("Interface\t\t\t{0}", Convert.ToInt32(AttributeTargets.Interface));
            Console.WriteLine("Parameter\t\t\t{0}", Convert.ToInt32(AttributeTargets.Parameter));
            Console.WriteLine("Delegate\t\t\t{0}", Convert.ToInt32(AttributeTargets.Delegate));
            Console.WriteLine("ReturnValue\t\t\t{0}", Convert.ToInt32(AttributeTargets.ReturnValue));
            Console.WriteLine("GenericParameter\t\t{0}", Convert.ToInt32(AttributeTargets.GenericParameter));
            Console.WriteLine("All\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.All));
            Console.WriteLine("\n");
        }
    }
}

 

结果显示如下:

AttributeTargets 使用了枚举值的另一种用法 —— 标识位。
除了All 的值之外,每个值的二进制形式中只有一位是“1”,其余位全是“0”。
如果我们的Attribute 要求既能附着在类上,又能附着在类的方法上。就可以使用C# 中的操作符“|”(也就是按位求“或”)。有了它,我们只需要将代码书写如下:
AttributeTargets.Class | AttributeTargets.Method
因为这两个枚举值的标识位(也就是那个唯一的“1”)是错开的,所以只需要按位求或就解决问题了。
这样,你就能理解:为什么AttributeTargets.All 的值是32767 了。
默认情况下,当我们声明并定义一个新的Attribute 类时,它的可附着目标是AttributeTargets.All。
大多数情况下,Attribut

[AttributeUsage(AttributeTargets.Class, AttributeTargets.Field)]
class Hobby : Attribute // 必须以System.Attribute 类为基类
{
    // Hobby 类的具体实现
}

这里是使用Attribute的实例(AttributeUsage)附着在Attribute 类(Hobby)上。Attribute 的本质就是类,而AttributeUsage 又说明Hobby 类可以附着在哪些类型上。
附加问题:
1. 如果一个Attribute 类附着在了某个类上,那么这个Attribute 类会不会随着继承关系也附着在派生类上呢?
2. 可不可以像多个牡蛎附着在同一艘船上那样,让一个Attribute 类的多个实例附着在同一个目标上呢?
答案:可以。代码如下:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
class Hobby : System.Attribute
{
    // Hobby 类的具体实现
}

AttributeUsage 这个专门用来修饰Attribute 的Attribute ,除了可以控制修饰目标外,还能决定被它修饰的Attribute 是否可以随宿主“遗传”,以及是否可以使用多个实例来修饰同一个目标!

那修饰ConditionalAttribute 的AttributeUsage 又会是什么样子呢?(答案在MSDN中)

参考来源:

Attribute 在.NET 编程的应用

深入浅出Attribute[上] —— Attribute 初体验

深入浅出Attribute[中] —— Attribute本质论 

示例代码

 

原文地址:https://kb.cnblogs.com/page/87531/

Cg Standard Library Functions

Appendix E. Cg Standard Library Functions

Cg provides a set of built-in functions and predefined structures with binding semantics to simplify GPU programming. These functions are similar in spirit to the C standard library, offering a convenient set of common functions. In many cases, the functions map to a single native GPU instruction, so they are executed very quickly. Of the functions that map to multiple native GPU instructions, you may expect the most useful to become more efficient in the near future.

Although you can write your own versions of specific functions for performance or precision reasons, it is generally wiser to use the Cg Standard Library functions when possible. The Standard Library functions will continue to be optimized for future GPUs; a program written today using these functions will automatically be optimized for the latest architectures at compile time. Additionally, the Standard Library provides a convenient unified interface for both vertex and fragment programs.

This appendix describes the contents of the Cg Standard Library, and is divided into the following five sections:

  • “Mathematical Functions”
  • “Geometric Functions”
  • “Texture Map Functions”
  • “Derivative Functions”
  • “Debugging Function”

Where appropriate, functions are overloaded to support scalar and vector variants when the input and output types are the same.

E.1 Mathematical Functions

Table E-1 lists the mathematical functions that the Cg Standard Library provides. The table includes functions useful for trigonometry, exponentiation, rounding, and vector and matrix manipulations, among others. All functions work on scalars and vectors of all sizes, except where noted.

Table E-1. Mathematical Functions

Function Description
abs( x ) Absolute value of x .
acos( x ) Arccosine of x in range [0, p], x in [–1, 1].
all( x ) Returns true if every component of x is not equal to 0.

Returns false otherwise.

any( x ) Returns true if any component of x is not equal to 0.

Returns false otherwise.

asin( x ) Arcsine of x in range [–p/2, p/2]; x should be in [–1, 1].
atan( x ) Arctangent of x in range [–p/2, p/2].
atan2( y , x ) Arctangent of y / x in range [–p, p].
ceil( x ) Smallest integer not less than x .
clamp( x , a , b ) x clamped to the range [ a , b ] as follows:

  • Returns a if x is less than a .
  • Returns b if x is greater than b .
  • Returns x otherwise.
cos( x ) Cosine of x .
cosh( x ) Hyperbolic cosine of x .
cross( A , B ) Cross product of vectors A and B ;

A and B must be three-component vectors.

degrees( x ) Radian-to-degree conversion.
determinant( M ) Determinant of matrix M .
dot( A , B ) Dot product of vectors A and B .
exp( x ) Exponential function e x .
exp2( x ) Exponential function 2 x .
floor( x ) Largest integer not greater than x .
fmod( x , y ) Remainder of x / y , with the same sign as x .

If y is 0, the result is implementation-defined.

frac( x ) Fractional part of x .
frexp( x , out exp ) Splits x into a normalized fraction in the interval [½, 1), which is returned, and a power of 2, which is stored in exp .

If x is 0, both parts of the result are 0.

isfinite( x ) Returns true if x is finite.
isinf( x ) Returns true if x is infinite.
isnan( x ) Returns true if x is NaN (Not a Number).
ldexp( x , n ) x x 2 n .
lerp( a , b , f ) Linear interpolation:

(1 – f )* a + b * f

where a and b are matching vector or scalar types. f can be either a scalar or a vector of the same type as a and b .

lit( NdotL , NdotH , m ) Computes lighting coefficients for ambient, diffuse, and specular light contributions.

Expects the NdotL parameter to contain N  L and the NdotH parameter to contain N  H .

Returns a four-component vector as follows:

  • The x component of the result vector contains the ambient coefficient, which is always 1.0.
  • The y component contains the diffuse coefficient, which is 0 if ( N  L ) < 0; otherwise ( N  L ).
  • The z component contains the specular coefficient, which is 0 if either ( N  L ) < 0 or ( N  H ) < 0; ( N  H ) m otherwise.
  • The w component is 1.0.

There is no vectorized version of this function.

log( x ) Natural logarithm ln( x ) ; x must be greater than 0.
log2( x ) Base 2 logarithm of x ; x must be greater than 0.
log10( x ) Base 10 logarithm of x ; x must be greater than 0.
max( a , b ) Maximum of a and b .
min( a , b ) Minimum of a and b .
modf( x , out ip ) Splits x into integral and fractional parts, each with the same sign as x .

Stores the integral part in ip and returns the fractional part.

mul( M , N ) Matrix product of matrix M and matrix N , as shown below:

304equ01.jpg

If M has size A x B , and N has size B x C , returns a matrix of size A x C .

mul( M , v ) Product of matrix M and column vector v , as shown below:

305equ01.jpg

If M is an A x B matrix and v is a B x 1 vector, returns an A x 1 vector.

mul( v , M ) Product of row vector v and matrix M , as shown below:

305equ02.jpg

If v is a 1 x A vector and M is an A x B matrix, returns a 1 x B vector.

noise( x ) Either a one-, two-, or three-dimensional noise function, depending on the type of its argument. The returned value is between 0 and 1, and is always the same for a given input value.
pow( x , y ) xy .
radians( x ) Degree-to-radian conversion.
round( x ) Closest integer to x .
rsqrt( x ) Reciprocal square root of x ; x must be greater than 0.
saturate( x ) Clamps x to the [0, 1] range.
sign( x ) 1 if x > 0; –1 if x < 0; 0 otherwise.
sin( x ) Sine of x .
sincos(float x , out s , out c ) s is set to the sine of x , and c is set to the cosine of x .

If both sin( x ) and cos( x ) are needed, this function is more efficient than calculating each individually.

sinh( x ) Hyperbolic sine of x .
smoothstep( min , max , x ) For values of x between min and max , returns a smoothly varying value that ranges from 0 at x = min to 1 at x = max .

x is clamped to the range [ min , max ] and then the interpolation formula is evaluated:

–2*(( x  min )/( max  min ))3 +

3*(( x  min )/( max  min ))2

step( a , x ) 0 if x < a ;

1 if x >= a .

sqrt( x ) Square root of x ;

x must be greater than 0.

tan( x ) Tangent of x .
tanh( x ) Hyperbolic tangent of x .
transpose( M ) Matrix transpose of matrix M .

If M is an A x B matrix, the transpose of M is a B x A matrix whose first column is the first row of M , whose second column is the second row of M , whose third column is the third row of M , and so on.

E.2 Geometric Functions

Table E-2 presents the geometric functions that are provided in the Cg Standard Library.

Table E-2. Geometric Functions

Function Description
distance( pt1 , pt2 ) Euclidean distance between points pt1 and pt2 .
faceforward( N , I , Ng ) N if dot( Ng , I ) < 0; - N otherwise.
length( v ) Euclidean length of a vector.
normalize( v ) Returns a vector of length 1 that points in the same direction as vector v .
reflect( I , N ) Computes reflection vector from entering ray direction I and surface normal N .

Valid only for three-component vectors.

refract( I , N , eta ) Given entering ray direction I , surface normal N , and relative index of refraction eta , computes refraction vector.

If the angle between I and N is too large for a given eta , returns (0, 0, 0).

Valid only for three-component vectors.

E.3 Texture Map Functions

Table E-3 presents the texture map functions that are provided in the Cg Standard Library. Currently, these texture functions are fully supported by the ps_2_0 , ps_2_x , arbfp1 , and fp30 profiles (though only OpenGL profiles support the samplerRECT functions). They will also be supported by all future advanced fragment profiles with texture-mapping capabilities. All of the functions listed in Table E-3 return a float4 value.

Table E-3. Texture Map Functions

Function Description
tex1D(sampler1D tex , float s ) 1D nonprojective texture query
tex1D(sampler1D tex , float s , float dsdx , float dsdy ) 1D nonprojective texture query with derivatives
tex1D(sampler1D tex , float2 sz ) 1D nonprojective depth compare texture query
tex1D(sampler1D tex , float2 sz , float dsdx , float dsdy ) 1D nonprojective depth compare texture query with derivatives
tex1Dproj(sampler1D tex , float2 sq ) 1D projective texture query
tex1Dproj(sampler1D tex , float3 szq ) 1D projective depth compare texture query
tex2D(sampler2D tex , float2 s ) 2D nonprojective texture query
tex2D(sampler2D tex , float2 s , float2 dsdx , float2 dsdy ) 2D nonprojective texture query with derivatives
tex2D(sampler2D tex , float3 sz ) 2D nonprojective depth compare texture query
tex2D(sampler2D tex , float3 sz , float2 dsdx , float2 dsdy ) 2D nonprojective depth compare texture query with derivatives
tex2Dproj(sampler2D tex , float3 sq ) 2D projective texture query
tex2Dproj(sampler2D tex , float4 szq ) 2D projective depth compare texture query
texRECT(samplerRECT tex , float2 s ) 2D nonprojective texture rectangle texture query (OpenGL only)
texRECT(samplerRECT tex , float2 s , float2 dsdx , float2 dsdy ) 2D nonprojective texture rectangle texture query with derivatives (OpenGL only)
texRECT(samplerRECT tex , float3 sz ) 2D nonprojective texture rectangle depth compare texture query (OpenGL only)
texRECT(samplerRECT tex , float3 sz , float2 dsdx , float2 dsdy ) 2D nonprojective depth compare texture query with derivatives (OpenGL only)
texRECTproj(samplerRECT tex , float3 sq ) 2D texture rectangle projective texture query (OpenGL only)
texRECTproj(samplerRECT tex , float3 szq ) 2D texture rectangle projective depth compare texture query (OpenGL only)
tex3D(sampler3D tex , float3 s ) 3D nonprojective texture query
tex3D(sampler3D tex , float3 s , float3 dsdx , float3 dsdy ) 3D nonprojective texture query with derivatives
tex3Dproj(sampler3D tex , float4 sq ) 3D projective texture query
texCUBE(samplerCUBE tex , float3 s ) Cube map nonprojective texture query
texCUBE(samplerCUBE tex , float3 s , float3 dsdx , float3 dsdy ) Cube map nonprojective texture query with derivatives
texCUBEproj(samplerCUBE tex , float4 sq ) Cube map projective texture query (ignores q)

Because of the limited pixel programmability of older hardware, the ps_1_1 , ps_1_2 , ps_1_3 , and fp20 profiles have restrictions on the use of texture-mapping functions. See the documentation for these profiles for more information.

In the table, the name of the second argument to each function indicates how its values are used when performing the texture lookup:

  • s indicates a one-, two-, or three-component texture coordinate.
  • z indicates a depth comparison value for shadow map lookups.
  • q indicates a perspective value, and is used to divide the texture coordinate ( s ) before the texture lookup is performed.

When you use the texture functions that allow specifying a depth comparison value, the associated texture unit must be configured for depth-compare texturing. Otherwise, no depth comparison will actually be performed.

E.4 Derivative Functions

Table E-4 presents the derivative functions that are supported by the Cg Standard Library. Vertex profiles do not support these functions.

Table E-4. Derivative Functions

Function Description
ddx( a ) Approximate partial derivative of a with respect to screen-space x coordinate
ddy( a ) Approximate partial derivative of a with respect to screen-space y coordinate

E.5 Debugging Function

Table E-5 presents the debugging function that is supported by the Cg Standard Library. Vertex profiles are not required to support this function.

Table E-5. Debugging Function

Function Description
void debug(float4 x ) If the compiler’s DEBUG option is enabled, calling this function causes the value x to be copied to the COLOR output of the program, and execution of the program is terminated.

If the compiler’s DEBUG option is not enabled, this function does nothing.

The intent of the debug function is to allow a program to be compiled twice—once with the DEBUG option and once without. By executing both programs, it is possible to obtain one frame buffer containing the final output of the program and another frame buffer containing an intermediate value to be examined for debugging purposes.