Start() public method

public Start ( ) : void
return void
Beispiel #1
0
        public void Run()
        {
            RobustConsole.Write(LogLevel.Warning, "RobustEngine", "Starting Run loop...");

            Timekeeper.Start();
            GameScreen.Run(60);
        }
Beispiel #2
0
 public void CheckTickMethod()
 {
     // after clock start Tick method increment seconds by 1 every second
     _clock.Start();
     Thread.Sleep(1400);             // 400 ms for the test work. In that 400 ms value in clock must be 00:00:01
     Assert.AreEqual(1, _clock.Seconds);
     Assert.AreEqual("00:00:01", _clock.GetCurrentClockValue());
     Thread.Sleep(1400);
     Assert.AreEqual(2, _clock.Seconds);
     Assert.AreEqual("00:00:02", _clock.GetCurrentClockValue());
 }
Beispiel #3
0
        public void SetFrequencyAndStartClock()
        {
            m_Clock.Add(m_Tickable);

            m_Clock.SetFrequency(new TimeSpan(0));
            m_Clock.Start();
            m_Clock.Oscillate();

            m_Tickable.Ticks
            .Should().Be(1);
        }
Beispiel #4
0
 private void Game_OnTurnStart(object sender, OnTurnStartEventArgs e)
 {
     if (this.Equals(e.Player))
     {
         Clock.Start();
     }
 }
Beispiel #5
0
        public static void Mary()
        {
            OutputDevice outputDevice = OutputDevice.InstalledDevices[0];

            outputDevice.Open();
            Console.WriteLine("Playing the first two bars of Mary Had a Little Lamb...");
            Clock clock = new Clock(120);

            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 0));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 1));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.D4, 80, 1));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.D4, 80, 2));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.C4, 80, 2));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.C4, 80, 3));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.D4, 80, 3));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.D4, 80, 4));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 4));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 5));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 5));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 6));
            clock.Schedule(new NoteOnMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 6));
            clock.Schedule(new NoteOffMessage(outputDevice, Channel.Channel1, Pitch.E4, 80, 7));
            clock.Start();
            Thread.Sleep(5000);
            clock.Stop();

            outputDevice.Close();
        }
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            lbTime.Text = "";
            Console.WriteLine("Tamanho do buffer");
            int buffer = int.Parse(txtTamanho.Text);

            Console.WriteLine("Quantidade de pacotes");
            int pacotes = int.Parse(txtQuantidade.Text);

            byte[] msg = new byte[buffer];

            Clock.Start();
            for (int i = 0; i < pacotes; i++)
            {
                socket.Send(msg);
            }
            Clock.Stop();

            var ticks = Clock.Ticks;

            lbTime.Text = ticks + " ms";
            string log = "Tamanho do buffer: " + buffer + " quantidade de pacotes: " + pacotes + " tempo transcorrido: " +
                         ticks + " ms";

            times.Add(log);
            //    MessageBox.Show(ticks.ToString());
        }
Beispiel #7
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (txtPlayer.Text.Length == 0)
            {
                using (FormChangeName changeName = new FormChangeName())
                {
                    if (changeName.ShowDialog() == DialogResult.OK)
                    {
                        txtPlayer.Text = changeName.getInputName();
                    }
                }
            }
            else
            {
                if (isStarted == false)
                {
                    currentRound = 1;

                    // khơi tạo câu hỏi ban đầu
                    RoundPlaying();
                    timeLeft.assign(totalTime);
                    lbMinutes.Text = timeLeft.getStringMinute();
                    lbSeconds.Text = timeLeft.getStringSecond();
                    Clock.Start();

                    isStarted          = true;
                    btnChoose1.Enabled = true;
                    btnChoose2.Enabled = true;
                    btnRestart.Enabled = true;
                    btnStart.Enabled   = false;
                }
            }
        }
Beispiel #8
0
        public static void play(List <MyNote> lista, int t, OutputDevice outputDevice)
        {
            MyComposition newComp = new MyComposition(t);

            foreach (MyNote n in lista)
            {
                newComp.addNote(n);
            }

            int positionStatic      = 0;
            int totalDurationStatic = 0;
            int beatLengthStatic    = 60000 / t;


            Clock clock = new Clock(t);

            foreach (MyNote n in lista)
            {
                totalDurationStatic += n.myDurationInBeats * beatLengthStatic;
                clock.Schedule(n.noteStart(outputDevice, positionStatic));
                positionStatic += n.myDurationInBeats;
                clock.Schedule(n.noteEnd(outputDevice, positionStatic));
            }
            clock.Start();
            Thread.Sleep(totalDurationStatic + 1000); // 1 additional second
            clock.Stop();
        }
Beispiel #9
0
        private void EventThreadProc()
        {
            while (!StoppingThread)
            {
                BadgeEvent.WaitOne();
                if (CancelOps)
                {
                    return;
                }
                Clock.Stop();

                WaitDoor = true;
                OpenDoor();
                Clock.Start();
                CptDoor = 10;
                DoorEventNormal.Reset();

                if (DoorEventNormal.WaitOne(10000, false))
                {
                    continue;                                        // next loop iteration
                }
                WaitDoor     = false;
                WaitDoor     = false;
                DisplayBadge = false;
                CloseDoor();
                CurrenRfidReader.NotifyRelock();
                Clock.Start();
            }
            if (ThreadEvent != null)
            {
                ThreadEvent.Set();
            }
        }
        public void Logging()
        {
            var clock = new Clock();

            clock.Start();

            var logger = new FileLogger(true, path, clock, LogType.All) as ILogger;

            if (logger.Log(LogType.Trace))
            {
                logger.Trace("Test Trace.");
            }
            if (logger.Log(LogType.Debug))
            {
                logger.Debug("Test Debug.");
            }
            if (logger.Log(LogType.Info))
            {
                logger.Info("Test Info.");
            }
            if (logger.Log(LogType.Warning))
            {
                logger.Warning("Test Warning.");
            }
            if (logger.Log(LogType.Error))
            {
                logger.Error("Test Error.");
            }
            if (logger.Log(LogType.Fatal))
            {
                logger.Error("Test Fatal.");
            }

            logger.Level = LogType.Info;
            if (logger.Log(LogType.Info))
            {
                logger.Info("Test Info Equality.");
            }

            logger.Level = LogType.Off;
            if (logger.Log(LogType.Error))
            {
                logger.Error("Test Off.");
            }

            logger.Close();

            var files = Directory.GetFiles(path);
            var lines = File.ReadAllLines(files[0]);

            Assert.AreEqual(9, lines.Length);
            Assert.IsTrue(lines[0].Contains("Info") && lines[0].Contains("Started file logger stream."));
            Assert.IsTrue(lines[1].Contains("Trace") && lines[1].Contains("Test Trace."));
            Assert.IsTrue(lines[2].Contains("Debug") && lines[2].Contains("Test Debug."));
            Assert.IsTrue(lines[3].Contains("Info") && lines[3].Contains("Test Info."));
            Assert.IsTrue(lines[4].Contains("Warning") && lines[4].Contains("Test Warning."));
            Assert.IsTrue(lines[5].Contains("Error") && lines[5].Contains("Test Error."));
            Assert.IsTrue(lines[6].Contains("Fatal") && lines[6].Contains("Test Fatal."));
            Assert.IsTrue(lines[7].Contains("Info") && lines[7].Contains("Test Info Equality."));
        }
 public void StopAll()
 {
     clock.Stop();
     clock.Reset();
     outputDevice.SilenceAllNotes();
     clock.Start();
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("first test");

            // starts the clock
            Clock.SetSpeed(10);
            Clock.Start();

            // creates the zoo
            Classes.Zoo zoo = new Classes.Zoo(8 * Clock.hour, 20 * Clock.hour);
            // addes workers
            zoo.AddWorker(new Worker(ref zoo));
            zoo.AddWorker(new Worker(ref zoo));
            // addes pens
            zoo.AddAnimalPen(new SimplePen(6 * 12, 4 * Clock.min, AnimalEnum.Giraffe, 1));
            zoo.AddAnimalPen(new SimplePen(15 * 6, 6 * Clock.min, AnimalEnum.Elefant, 2));
            zoo.AddAnimalPen(new CanidaePen(4 * 20, 2 * Clock.min, AnimalEnum.Wolf, 3));
            zoo.AddAnimalPen(new CanidaePen(4 * 20, 2 * Clock.min, AnimalEnum.Fox, 4));
            zoo.AddAnimalPen(new RabbitPen(48 * 50, 10 * Clock.min, AnimalEnum.Rabbit, 5));

            Console.ReadLine();
            // stops the zoo
            zoo.Stop();
            Clock.Stop();
        }
        public MedicalCabinet(RfidReader currenRfidReader, string strPortBadgeAndLCD, bool isSchroff = false)
            : base(currenRfidReader, strPortBadgeAndLCD)
        {
            EventThread = new Thread(EventThreadProc)
            {
                Name = "SmartCabinet event", IsBackground = true
            };
            EventThread.Start();

            if (currenRfidReader.HardwareVersion.StartsWith("13"))
            {
                this._isSchroff = true;
                Rs232Display    = new Rs232Module("COM2");
                InitLCD();
                HideCursor();

                if (YAPI.RegisterHub("usb", ref errmsg) == YAPI.SUCCESS)
                {
                    bTempReady = true;
                }
                else
                {
                    ErrorMessage.ExceptionMessageBox.Show("error init YAPI", null);
                }
            }

            Clock.Interval = 1000;
            Clock.Elapsed += Timer_Tick;
            Clock.Start();
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            Clock  clock  = new Clock();
            Logger logger = new Logger();

            while (true)
            {
                Console.WriteLine("1. Start the Clock\n2. Stop the Clock\n3. Log messages to file\nPress 'q' to quit");
                switch (Console.ReadLine())
                {
                case "1":
                    clock.Start(OutputToFile);
                    break;

                case "2":
                    clock.Stop();
                    break;

                case "3":
                    clock.Logger += logger.LogToFile;
                    break;

                case "q":
                    Environment.Exit(0);
                    break;

                default:
                    break;
                }

                Console.Clear();
            }
        }
Beispiel #15
0
        public void Render(object Sender, FrameEventArgs E)
        {
            Timekeeper.Start();

            GL.Clear(ClearBufferMask.ColorBufferBit);

            // PlayerView.Setup(800, 800);
            // PlayerView.Update();
            //Spritebatch.Begin();
            Texture.Bind();
            //    GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            CurrentShader.Enable();
            Sprite.mov(mov);
            Sprite.Draw();
            CurrentShader.Disable();

            //  GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
            GameScreen.SwapBuffers();



            frames++;
            if (Timekeeper.GetElapsed().Seconds == 1)
            {
                RobustConsole.Write(LogLevel.Debug, "RobustEngine", "Render() FPS " + frames);
                Timekeeper.Reset();
                frames = 0;
            }
            // RobustConsole.Write(LogLevel.Debug, "RobustEngine", "Render() MS " + Timekeeper.GetTime().Milliseconds.ToString());
        }
Beispiel #16
0
 public void Start()
 {
     if (state != LinkStates.ready)
     {
         return;
     }
     try {
         if (!Listening)
         {
             tcp.Start();
         }
         state = LinkStates.listening;
         clock.Start();
         Listening = true;
         debugInstances.Add(this);
     } catch (Exception ex) {
         if (state == LinkStates.listening)
         {
             tcp.Stop();
         }
         state = LinkStates.ready;
         clock.Stop();
         Listening = false;
     }
     listening?.Invoke(Listening);
 }
Beispiel #17
0
        private void btnChoose2_Click(object sender, EventArgs e)
        {
            Clock.Stop();
            if (posTrue == 2)
            {
                double percent = Convert.ToDouble(timeLeft.ToSecond()) / totalTime.ToSecond();
                int    mark    = Convert.ToInt32(System.Math.Floor(markPerSecond * percent));
                int    oldMark = Convert.ToInt32(txtScore.Text);
                txtScore.Text = (oldMark + mark).ToString();
            }
            if (currentRound < totalRound)
            {
                currentRound++;
                RoundPlaying();
                timeLeft.assign(totalTime);
                lbMinutes.Text = timeLeft.getStringMinute();
                lbSeconds.Text = timeLeft.getStringSecond();
                Clock.Start();
            }
            else
            {
                // end match
                isStarted = false;

                btnChoose1.Enabled   = false;
                btnChoose2.Enabled   = false;
                lb_notification.Text = "Ván chơi kết thúc !";
            }
        }
Beispiel #18
0
        /// <summary>
        /// Start function of the routine
        /// </summary>
        /// <param name="core">A reference to the Core</param>
        public void Start(Core core)
        {
            Clock = new Clock();

            Clock.Start();
            Log.Info(Log.F("\n\t\t{0} initialized to {1} ms\n", GetType().Name, Interval));
        }
Beispiel #19
0
        private void Clock_Tick(object sender, EventArgs e)
        {
            if (timeLeft.ToSecond() > 0)
            {
                timeLeft--;
                lbMinutes.Text = timeLeft.getStringMinute();
                lbSeconds.Text = timeLeft.getStringSecond();
            }
            else
            {
                if (currentRound < totalRound)
                {
                    currentRound++;
                    RoundPlaying();
                    timeLeft.assign(totalTime);
                    lbMinutes.Text = timeLeft.getStringMinute();
                    lbSeconds.Text = timeLeft.getStringSecond();
                    Clock.Start();
                }
                else
                {
                    // end match
                    isStarted = false;

                    btnChoose1.Enabled   = false;
                    btnChoose2.Enabled   = false;
                    lb_notification.Text = "Ván chơi kết thúc !";
                }
            }
        }
Beispiel #20
0
        public void Record()
        {
            if (IsRecording)
            {
                return;
            }
            if (IsPlaying)
            {
                Stop();
            }

            // Clear current sequence if any
            Clear();

            // Start recording
            try
            {
                Clock.Start();
                _midiInput.StartRecording();
                _midiInput.MessageReceived += HandleChannelMessageReceived;

                IsRecording = true;
                CanPlay     = true;
                CanRecord   = false;
                CanStop     = true;
            }
            catch (Exception ex)
            {
                Exceptions.ErrHandler(ex);
            }
        }
Beispiel #21
0
        ///<inheritdoc/>
        public void PlayAsync <TNote>(Tune <TNote> tune) where TNote : INote
        {
            Device.Open();
            try {
                Device.SendPitchBend(Channel, 8192);        // 8192 = Centred

                var tempo = 120F;
                _clock = new Clock(tempo);
                new ProgramChangeMessage(Device, Channel, Instrument, 0).SendNow();

                float time = 0.100F;
                foreach (INote note in tune)
                {
                    var ni = new NoteInfo(note);
                    if (note is IAwareNote)
                    {
                        _clock.Schedule(new HighlightMessage(OnNextNote, time, (IAwareNote)note));
                    }
                    if (note.PianoKey != 0)
                    {
                        _clock.Schedule(new NoteOnOffMessage(Device, Channel, ni.Pitch, ni.Velocity,
                                                             time, _clock, ni.Duration));
                    }
                    time += ni.Length;
                }
                _clock.Schedule(new CallbackMessage(PlayCompletedCallback, time));
                _clock.Start();
            } catch (Exception) {
                Device.Close();
                throw;
            }
        }
Beispiel #22
0
        public Measurement RunIteration(IterationData data)
        {
            // Initialization
            long invokeCount     = data.InvokeCount;
            int  unrollFactor    = data.UnrollFactor;
            long totalOperations = invokeCount * OperationsPerInvoke;
            var  action          = data.IterationMode.IsIdle() ? IdleAction : MainAction;

            GcCollect();

            // Measure
            var clock = Clock.Start();

            action(invokeCount / unrollFactor);
            var clockSpan = clock.Stop();

            GcCollect();

            // Results
            var measurement = new Measurement(0, data.IterationMode, data.Index, totalOperations, clockSpan.GetNanoseconds());

            if (!IsDiagnoserAttached)
            {
                WriteLine(measurement.ToOutputLine());
            }

            return(measurement);
        }
Beispiel #23
0
 private void Start_Game()
 {
     game_state             = true;
     Start_Button.Text      = "Pause";
     Start_Button.BackColor = Color.Red;
     Clock.Start();
     Clock_Tick();
 }
Beispiel #24
0
 private void qrcode()
 {
     finalframe           = new VideoCaptureDevice(capturedev[0].MonikerString);
     finalframe.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
     finalframe.Start();
     Clock.Enabled = true;
     Clock.Start();
 }
Beispiel #25
0
        public override void BeforeStart()
        {
            Clock.Start();

            timepoll       = new Timer();
            timepoll.Tick += timepoll_Tick;
            timepoll.Start();
        }
Beispiel #26
0
        private void SetClockFunctions()
        {
            Clock.Interval = TimeSpan.FromMilliseconds(150f / simulation.runSpeed);
            Clock.Tick    += StandardFBUpdate;

            InitializeComponent();
            Clock.Start();
            MinClock.Start();
        }
 protected virtual void OnBtnClearClicked(object sender, System.EventArgs e)
 {
     CCalendar.Date = DateTime.Now;
     TxtHour.Value  = DateTime.Now.Hour;
     TxtMin.Value   = DateTime.Now.Minute;
     TxtSec.Value   = DateTime.Now.Second;
     RefreshClock();
     Clock.Start();
 }
Beispiel #28
0
 /// <summary>
 /// Do a server frame, updating every modules
 /// </summary>
 public void Update()
 {
     DeltaTime = Clock.Stop();
     Clock.Start();
     foreach (IModule module in Modules)
     {
         module.Update(this);
     }
 }
Beispiel #29
0
        public Measurement RunIteration(IterationData data)
        {
            // Initialization
            long invokeCount     = data.InvokeCount;
            int  unrollFactor    = data.UnrollFactor;
            long totalOperations = invokeCount * OperationsPerInvoke;
            bool isOverhead      = data.IterationMode == IterationMode.Overhead;
            bool randomizeMemory = !isOverhead && MemoryRandomization;
            var  action          = isOverhead ? OverheadAction : WorkloadAction;

            if (!isOverhead)
            {
                IterationSetupAction();
            }

            GcCollect();

            if (EngineEventSource.Log.IsEnabled())
            {
                EngineEventSource.Log.IterationStart(data.IterationMode, data.IterationStage, totalOperations);
            }

            Span <byte> stackMemory = randomizeMemory ? stackalloc byte[random.Next(32)] : Span <byte> .Empty;

            // Measure
            var clock = Clock.Start();

            action(invokeCount / unrollFactor);
            var clockSpan = clock.GetElapsed();

            if (EngineEventSource.Log.IsEnabled())
            {
                EngineEventSource.Log.IterationStop(data.IterationMode, data.IterationStage, totalOperations);
            }

            if (!isOverhead)
            {
                IterationCleanupAction();
            }

            if (randomizeMemory)
            {
                RandomizeManagedHeapMemory();
            }

            GcCollect();

            // Results
            var measurement = new Measurement(0, data.IterationMode, data.IterationStage, data.Index, totalOperations, clockSpan.GetNanoseconds());

            WriteLine(measurement.ToString());

            Consume(stackMemory);

            return(measurement);
        }
Beispiel #30
0
        public ClockK95Form()
        {
            InitializeComponent();

            _corsairRgb = new CorsairRgb();
            _clock = new Clock(_corsairRgb.GetCorsairKeyboard());
            _clock.Start();

            this.WindowState = FormWindowState.Minimized;
            Form1();
        }
        public HelperContainer()
        {
            m_UnityStatic = new UnityStatic();

            m_Clock      = new Clock();
            m_ClockProxy = new Clock.Proxy(m_Clock);
            m_Clock.Start();

            m_MemoryStats      = new MemoryStats();
            m_MemoryStatsProxy = new MemoryStats.Proxy(m_MemoryStats);
        }
Beispiel #32
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.None);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_cubes", "fs_cubes");

        // start the frame clock
        var clock = new Clock();
        clock.Start();

        int cubeDim = 15;
        float lastUpdate = 0.0f;
        int frameCount = 0;

        // main loop
        while (sample.ProcessEvents(ResetFlags.None)) {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // tick the clock
            var elapsed = clock.Frame();
            var time = clock.TotalTime();
            if (elapsed > 10)
                elapsed = 0;

            frameCount++;
            lastUpdate += elapsed;
            if (lastUpdate > 1.0f) {
                var avgFrameTime = frameCount / lastUpdate;
                if (avgFrameTime > HighThreshold)
                    cubeDim = Math.Min(cubeDim + 2, 40);
                else if (avgFrameTime < LowThreshold)
                    cubeDim = Math.Max(cubeDim - 1, 2);

                frameCount = 0;
                lastUpdate = 0;
            }

            var initial = new Vector3(
                -Step * cubeDim / 2.0f,
                -Step * cubeDim / 2.0f,
                -15.0f
            );

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "Description: CPU/driver stress test, maximizing draw calls.");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Draw Calls: {0}", cubeDim * cubeDim * cubeDim);
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame:      {0:F3} ms", elapsed * 1000);

            for (int z = 0; z < cubeDim; z++) {
                for (int y = 0; y < cubeDim; y++) {
                    for (int x = 0; x < cubeDim; x++) {
                        // model matrix
                        var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, time + y * 0.13f);
                        transform = Matrix4x4.CreateScale(Scale) * transform;
                        transform.M41 = initial.X + x * Step;
                        transform.M42 = initial.Y + y * Step;
                        transform.M43 = initial.Z + z * Step;
                        Bgfx.SetTransform(&transform.M11);

                        // set pipeline states
                        Bgfx.SetVertexBuffer(vbh);
                        Bgfx.SetIndexBuffer(ibh);
                        Bgfx.SetRenderState(RenderState.Default);

                        // submit primitives
                        Bgfx.Submit(0, program);
                    }
                }
            }

            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
Beispiel #33
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_cubes", "fs_cubes");

        // start the frame clock
        var clock = new Clock();
        clock.Start();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync)) {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // tick the clock
            var elapsed = clock.Frame();
            var time = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/01-Cubes");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Rendering simple static mesh.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // submit 11x11 cubes
            for (int y = 0; y < 11; y++) {
                for (int x = 0; x < 11; x++) {
                    // model matrix
                    var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, 0.0f);
                    transform.M41 = -15.0f + x * 3.0f;
                    transform.M42 = -15.0f + y * 3.0f;
                    transform.M43 = 0.0f;
                    Bgfx.SetTransform(&transform.M11);

                    // set pipeline states
                    Bgfx.SetVertexBuffer(vbh);
                    Bgfx.SetIndexBuffer(ibh);
                    Bgfx.SetRenderState(RenderState.Default);

                    // submit primitives
                    Bgfx.Submit(0, program);
                }
            }

            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
Beispiel #34
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init(RendererBackend.Direct3D11);
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // load shaders
        var programTextureLighting = ResourceLoader.LoadProgram("vs_stencil_texture_lighting", "fs_stencil_texture_lighting");
        var programColorLighting = ResourceLoader.LoadProgram("vs_stencil_color_lighting", "fs_stencil_color_lighting");
        var programColorTexture = ResourceLoader.LoadProgram("vs_stencil_color_texture", "fs_stencil_color_texture");
        var programColorBlack = ResourceLoader.LoadProgram("vs_stencil_color", "fs_stencil_color_black");
        var programTexture = ResourceLoader.LoadProgram("vs_stencil_texture", "fs_stencil_texture");

        // load meshes
        var bunnyMesh = ResourceLoader.LoadMesh("bunny.bin");
        var columnMesh = ResourceLoader.LoadMesh("column.bin");
        var hplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.HorizontalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);
        var vplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.VerticalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);

        // load textures
        var figureTex = ResourceLoader.LoadTexture("figure-rgba.dds");
        var flareTex = ResourceLoader.LoadTexture("flare.dds");
        var fieldstoneTex = ResourceLoader.LoadTexture("fieldstone-rgba.dds");

        // create uniforms
        var colorTextureHandle = new Uniform("u_texColor", UniformType.Int1);
        var uniforms = new Uniforms();
        uniforms.SubmitConstUniforms();

        // light colors
        uniforms.LightColor = new[] {
            new Vector4(1.0f, 0.7f, 0.2f, 0.0f), // yellow
            new Vector4(0.7f, 0.2f, 1.0f, 0.0f), // purple
            new Vector4(0.2f, 1.0f, 0.7f, 0.0f), // cyan
            new Vector4(1.0f, 0.4f, 0.2f, 0.0f)  // orange
        };

        // camera
        var camera = new Camera(60.0f, sample.WindowWidth, sample.WindowHeight, 0.1f, 100.0f);
        camera.Position = new Vector3(0.0f, 18.0f, -40.0f);

        // start the frame clock
        var clock = new Clock();
        clock.Start();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync)) {
            // tick the clock
            var elapsed = clock.Frame();
            var time = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/13-Stencil");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Stencil reflections.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // clear the background
            Bgfx.SetViewClear(BaseId, ClearTargets.Color | ClearTargets.Depth | ClearTargets.Stencil, 0x30303000);
            Bgfx.SetViewRect(BaseId, 0, 0, sample.WindowWidth, sample.WindowHeight);
            Bgfx.Touch(BaseId);

            // set view params for each pass
            var viewMtx = camera.GetViewMatrix();
            var projMtx = camera.GetProjectionMatrix();
            for (byte i = PassId0; i <= PassId4; i++) {
                Bgfx.SetViewRect(i, 0, 0, sample.WindowWidth, sample.WindowHeight);
                Bgfx.SetViewTransform(i, (float*)&viewMtx, (float*)&projMtx);
            }

            // first pass - draw ground plane
            var floorMtx = FloorTransform;
            hplaneMesh.Submit(PassId0, programColorBlack, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionCraftStencil], uniforms);

            // second pass - reflected objects
            Bgfx.SetViewClear(PassId1, ClearTargets.Depth, 0);
            uniforms.AmbientPass = true;
            uniforms.LightingPass = true;
            uniforms.Color = new Vector4(0.70f, 0.65f, 0.60f, 0.8f);
            uniforms.LightCount = LightCount;

            // light positions
            var lightPositions = new Vector4[LightCount];
            var reflectedLights = new Vector4[LightCount];
            for (int i = 0; i < lightPositions.Length; i++) {
                var v3 = new Vector3(
                    (float)Math.Sin(time * 1.1 + i * 0.03 + i * 1.07 * Math.PI / 2) * 20.0f,
                    8.0f + (1.0f - (float)Math.Cos(time * 1.5 + i * 0.29 + 1.49f * Math.PI / 2)) * 4.0f,
                    (float)Math.Cos(time * 1.3 + i * 0.13 + i * 1.79 * Math.PI / 2) * 20.0f
                );

                lightPositions[i] = new Vector4(v3, 15.0f);
                reflectedLights[i] = new Vector4(Vector3.Transform(v3, ReflectionTransform), 15.0f);
            }

            uniforms.LightPosRadius = reflectedLights;
            var bunnyMtx =
                Matrix4x4.CreateScale(5) *
                Matrix4x4.CreateRotationY(time - 1.56f) *
                Matrix4x4.CreateTranslation(0.0f, 2.0f, 0.0f);
            var reflectedBunnyMtx = bunnyMtx * ReflectionTransform;
            bunnyMesh.Submit(PassId1, programColorLighting, &reflectedBunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);

            for (int i = 0; i < 4; i++) {
                var mtx = ColumnTransforms[i] * ReflectionTransform;
                columnMesh.Submit(PassId1, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);
            }

            // third pass - blend the plane and reflections
            uniforms.LightPosRadius = lightPositions;
            hplaneMesh.Submit(PassId2, programTextureLighting, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionBlendPlane], uniforms, fieldstoneTex, colorTextureHandle);

            // fourth pass - draw the solid objects
            bunnyMesh.Submit(PassId3, programColorLighting, &bunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            for (int i = 0; i < 4; i++) {
                var mtx = ColumnTransforms[i];
                columnMesh.Submit(PassId3, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            }

            // fifth pass - draw the lights as objects
            for (int i = 0; i < LightCount; i++) {
                var c = uniforms.LightColor[i];
                uniforms.Color = new Vector4(c.X, c.Y, c.Z, 0.8f);

                var p = lightPositions[i];
                var mtx = Matrix4x4.CreateScale(1.5f) * Matrix4x4.CreateBillboard(new Vector3(p.X, p.Y, p.Z), camera.Position, Vector3.UnitY, -Vector3.UnitZ);
                vplaneMesh.Submit(PassId4, programColorTexture, &mtx, StateGroups[PrebuiltRenderState.CustomBlendLightTexture], uniforms, flareTex, colorTextureHandle);
            }

            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        bunnyMesh.Dispose();
        columnMesh.Dispose();
        hplaneMesh.Dispose();
        vplaneMesh.Dispose();

        figureTex.Dispose();
        fieldstoneTex.Dispose();
        flareTex.Dispose();

        programTextureLighting.Dispose();
        programColorLighting.Dispose();
        programColorTexture.Dispose();
        programColorBlack.Dispose();
        programTexture.Dispose();

        colorTextureHandle.Dispose();
        uniforms.Dispose();

        Bgfx.Shutdown();
    }