Exemple #1
0
 public MainPage()
 {
     this.InitializeComponent();
     _viewModel  = new DemoModel();
     DataContext = _viewModel;
     tileLayer.LayerConfiguration.TileLoader.PropertyChanged += TileLoaderOnPropertyChanged;
 }
Exemple #2
0
 public Task <TranStatus> AddDemo(DemoModel model)
 {
     using (demoRepository = new DemoRepository())
     {
         return(demoRepository.AddDemo(model));
     }
 }
Exemple #3
0
        public void CreateDefinition()
        {
            ApplicationDefinition application = DemoModel.Create();

            Assert.AreEqual("Demo", application.Name);
            Assert.AreEqual(application.Databases.Count, 1);
        }
Exemple #4
0
        public void LoadDemo(DemoModel d)
        {
            demo           = d;
            TitleText.Text = demo.Title;
            CanvasWrapper.LoadDemo(demo);

            if (demo.Points != null && demo.Points.Count > 0)
            {
                foreach (var v in demo.Points)
                {
                    EventBus.Publish(new InputPointSelected(v.Alternates.DotIndexLeft, v.Alternates.DotIndexTop,
                                                            v.X, v.Y));
                    CanvasWrapper.AddInputPoint(v.Alternates.DotIndexLeft, v.Alternates.DotIndexTop, v.X, v.Y);
                }
            }

            if (demo.Polygons != null && demo.Polygons.Count > 0)
            {
                foreach (var poly in demo.Polygons)
                {
                    foreach (var line in poly.Lines)
                    {
                        CanvasWrapper.AddPolygonLine(
                            line.StartPoint.Alternates.DotIndexLeft, line.StartPoint.Alternates.DotIndexTop,
                            line.EndPoint.Alternates.DotIndexLeft, line.EndPoint.Alternates.DotIndexTop,
                            line.StartPoint.X, line.StartPoint.Y,
                            line.EndPoint.X, line.EndPoint.Y
                            );
                    }
                }
            }
        }
        public async Task <IActionResult> PutDemoModel(int id, DemoModel demoModel)
        {
            if (id != demoModel.Id)
            {
                return(BadRequest());
            }

            _context.Entry(demoModel).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DemoModelExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemple #6
0
 public DemoModel HelloSendModel(DemoModel model)
 {
     model.T1 = model.T1 + 10;
     model.T2 = model.T2 + "11";
     model.T3 = model.T3.AddDays(12);
     return(model);
 }
Exemple #7
0
        internal static void FireAll(DemoModel model, ExtModel extModel)
        {
            model.Boolean_property.Set(false);

            model.Boolean_array.Set(new[] { false, true, false });

            var scalar = new MyScalar(
                false,
                50,
                32000,
                1000000000,
                -2000000000000000000,
                3.14f,
                -123456789.012345678,
                byte.MaxValue - 1,
                ushort.MaxValue - 1,
                uint.MaxValue - 1,
                ulong.MaxValue - 1,
                MyEnum.net,
                Flags.anyFlag | Flags.netFlag,
                MyInitializedEnum.hundred
                );

            // ReSharper disable once UnusedVariable
            // ReSharper disable once InconsistentNaming
            var(_bool, _byte, _short, _int, _long, _float, _double, _unsigned_byte, unsigned_short, _unsigned_int, _unsigned_long, _my_enum, _flags, initializedEnum) = scalar;
            var(first, second) = new ComplicatedPair(new Derived("First"), new Derived("Second"));

            model.Scalar.Set(scalar);

            model.Set.Add(50);

            model.MapLongToString.Add(50, "C#");

            const string valA = "C#";
            const string valB = "protocol";

            model.Interned_string.Set(valA);
            model.Interned_string.Set(valA);
            model.Interned_string.Set(valB);
            model.Interned_string.Set(valB);
            model.Interned_string.Set(valA);

            var derived = new Derived("C# instance");

            model.Polymorphic.Set(derived);

            var openDerived = new OpenDerived("C# instance open derived string", "C# instance open string");

            model.Polymorphic_open.Set(openDerived);

            var openClass = new OpenClass("c# test");

            openClass.String.Set("property");

            model.Enum.Value = MyEnum.net;
            extModel.Checker.Fire();

            model.Struct_with_open_field.Value = new StructWithOpenStructField(new OpenStructInField("", "", 456, "", ""));
        }
        public string AddDemoModel(DemoModel demoModel)
        {
            DemoModelDao.Instance.Add(demoModel);
            var count = DemoModelDao.Instance.SaveChanges();

            return(count > 0 ? "success" : "save error");
        }
        public async Task <ActionResult> AddDemoModel()
        {
            var models = new List <DemoModel>();

            for (int i = 0; i < 100; i++)
            {
                var testModel = new DemoModel()
                {
                    CustomerName     = i + "-Levy" + DateTime.Now.ToString("HH:mm:ss"),
                    IdentityCardType = 1
                };
                models.Add(testModel);
            }
            for (int i = 0; i < 100; i++)
            {
                var testModel = new DemoModel()
                {
                    CustomerName     = i + "-zzzz" + DateTime.Now.ToString("HH:mm:ss"),
                    IdentityCardType = 2
                };
                models.Add(testModel);
            }

            var res = await Task.FromResult(DemoModelBiz.Instance.AddDemoModel(models));

            return(Succeed(res));
        }
Exemple #10
0
        public async Task <DemoModel> PostModel([FromBody] DemoModel model)
        {
            _context.DemoModels.Add(model);
            await _context.SaveChangesAsync();

            return(model);
        }
Exemple #11
0
 private void GlControl_Load(object sender, EventArgs eArgs)
 {
     try
     {
         demo = DemoModelFactory.DemoModelFactory.Create(this);
         //make for valid time source even if no new demo is loaded afterwards (when starting with shader cmd line argument)
         Demo_OnTimeSourceLoaded(null, EventArgs.Empty);
         demo.SetCustomUniforms         += Demo_OnSetCustomUniforms;
         demo.TimeSource.Loaded         += Demo_OnTimeSourceLoaded;
         demo.Uniforms.UniformAdded     += Uniforms_OnAdd;
         demo.Uniforms.UniformRemoved   += Uniforms_OnRemove;
         demo.Uniforms.UniformAdded     += multiGraph.Uniforms_OnAdd;
         demo.Uniforms.UniformRemoved   += multiGraph.Uniforms_OnRemove;
         demo.Uniforms.ChangedKeyframes += multiGraph.Uniforms_OnChange;
         demo.Uniforms.ChangedKeyframes += (s, a) => camera.UpdateFromUniforms(demo.Uniforms, demo.TimeSource.Position);
         demo.Uniforms.ChangedKeyframes += (s, a) => glControl.Invalidate();
         demo.Shaders.Changed           += Shaders_OnChange;
         demo.ShaderKeyframes.Changed   += ShaderKeframes_OnChange;
         demo.Textures.Changed          += Textures_OnChange;
     }
     catch (Exception e)
     {
         log.Append(e.Message);
     }
 }
        public ActionResult Convert(DemoModel model)
        {
            PedamorfResponse response = null;

            try
            {
                using (PedamorfServiceClient client = PedamorfServiceManager.GetClient(model.ServiceHost))
                {
                    if (!string.IsNullOrEmpty(model.UrlButton))
                    {
                        response = client.ConvertUrl(model.Url,
                                                     new HtmlConversionOptions()
                        {
                            Orientation = model.Landscape ? PageOrientation.Landscape : PageOrientation.Portrait
                        });
                    }
                    else if (!string.IsNullOrEmpty(model.HtmlButton))
                    {
                        response = client.ConvertHtml(model.Html);
                    }
                    else if (!string.IsNullOrEmpty(model.DocumentButton) && model.Document1.ContentLength > 0)
                    {
                        response = client.ConvertFiles(model.Document1.InputStream, model.Document1.FileName, model.Document2.InputStream, model.Document2.FileName);
                    }
                    else if (!string.IsNullOrEmpty(model.ImageButton) && model.Image.ContentLength > 0)
                    {
                        ImageConversionOptions options = new ImageConversionOptions();

                        int imageWidth;
                        int imageHeight;
                        if (int.TryParse(model.ImageWidth, out imageWidth))
                        {
                            options.ImageWidthPixelsMin = imageWidth;
                        }

                        if (int.TryParse(model.ImageHeight, out imageHeight))
                        {
                            options.ImageHeightPixelsMin = imageHeight;
                        }

                        response = client.ConvertImage(model.Image.InputStream, model.Image.FileName, options);
                    }
                }
            }
            catch (Exception ex)
            {
                TempData["error"] = ex.Message;
                return(View());
            }

            if (!response.Error)
            {
                return(File(response.ResultPdf, "application/pdf"));
            }
            else
            {
                TempData["error"] = response.ErrorMessage;
                return(View());
            }
        }
        public JsonResult GetDetail(int id)
        {
            DemoModel model = new DemoModel();

            model.AnswersIds     = new List <int>();
            model.Answers        = new List <string>();
            model.ValueAnswer    = new List <string>();
            model.IsCheckDelete  = new List <string>();
            model.TechnologyList = new List <string>();
            // select data by id here display static data;
            var allAnswerByIdQuestion = _answerDal.GetAnswersByQuestionID(id);

            foreach (var answer in allAnswerByIdQuestion)
            {
                model.Answers.Add(answer.Text_Answer);
                model.AnswersIds.Add(answer.Id);
                if (answer.Value == true)
                {
                    model.ValueAnswer.Add("True");
                }
                else
                {
                    model.ValueAnswer.Add("False");
                }
            }
            model.Category       = _technologyDal.GetTechnologyQuestionById(Convert.ToInt32(_questionDal.GetQuestionById(id).QuestionTechnologyID)).TechnologyQuestionText;
            model.Type           = _questionDal.GetQuestionTypeById(id);
            model.Level          = _questionDal.GetQuestionById(id).LevelQuestion;
            model.TechnologyList = _technologyDal.GetAllTechnologyQuestions().Select(r => r.TechnologyQuestionText).ToList();

            return(Json(model));
        }
        // POST (create item)
        public async Task <IHttpActionResult> Post([FromBody] DemoModel model)
        {
            _logger.Info($"adding model with name {model.Name}");

            try
            {
                await _demoModelService.CreateDemoModelAsync(model);

                return(Ok(model));
            }
            catch (DemoServiceException ex)
            {
                if (ex.Error == DemoServiceException.ErrorType.WrongName)
                {
                    _logger.Info($"Wrong model name {model.Name} detected");
                    return(this.BadRequest("Wrong name"));
                }

                throw ex;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Server error occured while trying to add item with name {model.Name}");
                return(this.InternalServerError());
            }
        }
Exemple #15
0
        public DemoPresenter(DemoModel model, Demoview view)
        {
            this.model = model;
            this.view  = view;

            view.Presenter = this;
        }
        public ActionResult Demo(InputDataModel InputData)
        {
            DemoModel result = new DemoModel(InputData);

            ViewBag.Vud    = result.Vud;
            ViewBag.Wud    = result.Wud;
            ViewBag.Ph     = result.Ph;
            ViewBag.Ro_h   = result.Ro_h;
            ViewBag.Lambda = result.Lambda;
            ViewBag.W_g    = result.W_g;
            ViewBag.Ro_g   = result.Ro_g;
            ViewBag.H0     = result.H0;
            ViewBag.D      = result.D;
            ViewBag.Vm     = result.Vm;
            ViewBag.d_dn   = result.d_dn;
            ViewBag.d_g    = result.d_g;
            ViewBag.V      = result.V;
            ViewBag.H_k    = result.H_k;
            ViewBag.H_c    = result.H_c;
            ViewBag.H_v    = result.H_v;
            ViewBag.t_c    = result.t_c;
            ViewBag.t_dn   = result.t_dn;
            ViewBag.t_k    = result.t_k;
            ViewBag.delta  = result.delta;
            ViewBag.D_n    = result.D_n;
            ViewBag.H      = result.H;
            ViewBag.d_otv  = result.d_otv;

            // ! Save input data to Session
            Session["InputData"] = InputData;

            return(View("RezultDemo"));
        }
Exemple #17
0
        private void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            var demo = new DemoModel();

            var cbi = AlgoCombo.SelectedItem as ComboBoxItem;

            demo.AlgorithmId    = Int32.Parse(cbi.Name.Substring(4));
            demo.AlgorithmIndex = AlgoCombo.SelectedIndex;
            demo.Title          = FullName.Text;
            demo.ShortTitle     = ShortName.Text;

            double xmin = Double.Parse(xMinText.Text);
            double xmax = Double.Parse(xMaxText.Text);

            double ymin = Double.Parse(yMinText.Text);
            double ymax = Double.Parse(yMaxText.Text);

            double xstart = Double.Parse(xStartText.Text);
            double ystart = Double.Parse(yStartText.Text);

            int xCount = Int32.Parse(xCountText.Text);
            int yCount = Int32.Parse(yCountText.Text);

            demo.AxisConfig = new AxisModel {
                XMin   = xmin, XMax = xmax, YMin = ymin, YMax = ymax,
                XStart = xstart, YStart = ystart, XCount = xCount, YCount = yCount
            };

            EventBus.Publish <DemoCreated>(new DemoCreated {
                Demo = demo
            });

            Close();
        }
Exemple #18
0
        public override void Start(string[] args)
        {
            Before(args);

            Queue(() =>
            {
                var demoModel = new DemoModel(ModelLifetime, Protocol);

                var entity = demoModel.Property_with_default;

                int count = 0;

                entity.Advise(ModelLifetime, it =>
                {
                    if (!entity.IsLocalChange() && entity.Value != DemoModel.const_for_default)
                    {
                        Printer.PrintIfRemoteChange(entity, "property_with_default", it);

                        if (++count == 2)
                        {
                            Finished = true;
                        }
                    }
                });

                entity.Set(new string('5', 100_000));
                entity.Set(new string('0', 100_000));
            });

            After();
        }
    public async Task <IActionResult> Save(DemoModel model)
    {
        var controller = typeof(DemoController).Name;

        _logger.LogInformation($"Save method on {controller} started");

        if (model == null)
        {
            _logger.LogWarning($"Save method on {controller} did not find any value in the request");

            return(NoContent());
        }

        await _demoService.Save(new DemoEntity
        {
            Id          = model.Id,
            Description = model.Description,
            Text        = model.Text,
            Date        = DateTime.UtcNow
        });

        _logger.LogInformation($"Save method on {controller} finished successfully");

        return(Ok());
    }
        public IActionResult GetData(string name)
        {
            try
            {
                //获取配置脚本的内容
                ViewData["Before"] = GetOrSetScript(SCRIPT_FILE_NAME_Before);
                ViewData["After"]  = GetOrSetScript(SCRIPT_FILE_NAME_After);

                //测试数据
                var data = DemoModel.GetDemoDatas();

                //执行before脚本,控制传入的字段
                var ss = ExecuteBeforeScript(name);

                //利用before脚本中返回的值过滤Name字段(模拟利用before脚本控制搜索条件)
                if (!string.IsNullOrEmpty(ss))
                {
                    data = data.Where(t => t.Name.Contains(ss)).ToList();
                }

                //执行After脚本(模拟利用After脚本控制返回结果)
                var result = ExecuteAfterScript(data);

                ViewData["AfterData"] = result;
                ViewData["ErrorData"] = "查询成功!";
            }
            catch (Exception ex)
            {
                ViewData["ErrorData"] = ex.ToString();
            }
            return(View());
        }
Exemple #21
0
        //
        // GET: /Benchmark/

        public ActionResult Index()
        {
            var message        = "\nReduced images sizes:\n\n";
            var lastByteSize   = 0L;
            var demoModel      = new DemoModel();
            var imageGenerator = new ImageGenerator();
            var bitmap         = imageGenerator.GenerateDemoImage(Server.MapPath("~/Images/"), demoModel.IconName, demoModel.ForecastText);

            //un-reduced size
            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                message += string.Format("Unreduced size was {0} bytes.\n\n", ms.Length);
            }

            //calculate the size of each reducers output png image
            foreach (var reducer in demoModel.PngColorReducers)
            {
                IPngColorReducer colorReducer = PngColorReducerFactory.GetReducer(reducer);

                var pngStream = colorReducer.ReduceColorDepth(bitmap);
                lastByteSize = pngStream.Length;

                message += string.Format("{0} size was {1} bytes.\n\n", reducer, lastByteSize);
            }

            bitmap.Dispose();
            ViewData["Message"] = message;
            return(View());
        }
Exemple #22
0
        public ActionResult Details(object id)
        {
            ViewData[EditFlag] = true;
            var item = DemoModel.SingleOrDefault(id);

            return(View(item));
        }
        public async Task <ActionResult <DemoModel> > PostDemoModel(DemoModel demoModel)
        {
            _context.ModelItem.Add(demoModel);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetDemoModel", new { id = demoModel.Id }, demoModel));
        }
Exemple #24
0
        public override async Task AfterValidation(AddDemoCommand request)
        {
            var registered = await _demoRepository
                             .ExistsByExpressionAsync(x => x.Description == request.Description);

            if (registered)
            {
                NotifyError("O registro já existe");
                return;
            }

            var newRecord = new DemoModel
            {
                Id          = Guid.NewGuid(),
                Description = request.Description
            };

            await _demoRepository.InsertOrUpdateAsync(newRecord);

            if (!HasNotification() && _unitOfWork.CommitAsync().Result)
            {
                await _mediator.RaiseEvent(new AddedDemoEvent(newRecord));
            }
            else
            {
                NotifyError("Commit", "Tivemos um problema ao tentar salvar seus dados.");
            }
        }
        public ActionResult Index()
        {
            //Session
            Session["check"] = "test";
            System.Web.HttpContext.Current.Session["check2"] = "test2";
            var data = (string)System.Web.HttpContext.Current.Session["check2"];
            HttpSessionStateBase datas = new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session);

            datas.Add("check3", "test3");

            //Hiddenfield
            var model = new DemoModel {
                Property1 = 10,
                Property2 = 20
            };

            //Cookies

            //ViewData
            ViewData.Add(new KeyValuePair <string, object>("", "10"));

            //ViewBag

            //TempData
            //TempData.Add("Count",10);
            return(View(model));
        }
Exemple #26
0
        public DemoModelDto CreateOrEditDemoModel(DemoModelInput demoModelInput)
        {
            DemoModel demoModelEntity = null;

            if (demoModelInput.Id == 0)
            {
                // Insert
                demoModelEntity = ObjectMapper.Map <DemoModel>(demoModelInput);
                SetAuditInsert(demoModelEntity);
                demoModelRepository.Insert(demoModelEntity);
                CurrentUnitOfWork.SaveChanges();
            }
            else
            {
                // Update
                demoModelEntity = demoModelRepository.GetAll().Where(x => x.IsDelete == false).SingleOrDefault(x => x.Id == demoModelInput.Id);
                if (demoModelEntity == null)
                {
                    return(null);
                }
                ObjectMapper.Map(demoModelInput, demoModelEntity);
                SetAuditEdit(demoModelEntity);
                demoModelRepository.Update(demoModelEntity);
                CurrentUnitOfWork.SaveChanges();
            }

            return(ObjectMapper.Map <DemoModelDto>(demoModelEntity));
        }
Exemple #27
0
        public static string Insert(DemoModel _demoModel)
        {
            DbCommand command = Catalog_Access.CreateCommand();

            //Have to wite the stored procedure
            command.CommandText = "sp_insert_Demo";

            DbParameter param;

            param = command.CreateParameter();
            param.ParameterName = "@Name";
            param.Value         = _demoModel.Name;
            param.DbType        = DbType.String;
            command.Parameters.Add(param);

            param = command.CreateParameter();
            param.ParameterName = "@CreatedBy";
            param.Value         = _demoModel.CreatedBy;
            param.DbType        = DbType.String;
            command.Parameters.Add(param);

            param = command.CreateParameter();
            param.ParameterName = "@Return";
            param.DbType        = DbType.String;
            param.Size          = 2;
            param.Direction     = ParameterDirection.Output;
            command.Parameters.Add(param);

            Catalog_Access.ExecuteNonQuery(command);

            string Return = command.Parameters["@Return"].Value.ToString();

            return(Return);
        }
        // Demonstrate the mapping of JObject to a POCO or DTO
        private async Task <bool> JObjectMappingDemo()
        {
            // Returns a JObject from the root object 'demo'
            var data = await _demoApiClient.GetData("Demo/Get200/1", "demo");

            // Map using Newtonsoft.Json's JsonSerializer via the PopulateObject extension method
            // This works if the property names match, differences in case don't matter
            // Refer to Extensions/JsonExtensions.cs
            DemoModel demoModel = new DemoModel();

            data.PopulateObject <DemoModel>(demoModel);
            // Note: For mapping non matching property names we could use a Custom JsonConverter

            // If you like Automapper
            // Map using Automapper (actually uses JsonSerializer in the config)
            // Must use an existing object for this mapping config
            // Refer to MappingProfile.cs for the Mapping config
            DemoModel demoModel2 = new DemoModel();

            _mapper.Map(data, demoModel2);

            // Use Automapper to Map to an object where the property names don't match
            // Refer to MappingProfile.cs for the Mapping config
            // Because we are using a specific mapping for ExampleModel we can let automapper create the object
            // For the reason why, refer to the MappingProfile.cs
            ExampleModel exampleModel = _mapper.Map <ExampleModel>(data);

            return(true);
        }
Exemple #29
0
        public IActionResult Index()
        {
            List <DemoModel> demoList         = new List <DemoModel>();
            string           connectionString = Configuration.GetConnectionString("con");

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string     sql     = "SELECT * from [Demo].[dbo].[Users]";
                SqlCommand command = new SqlCommand(sql, connection);
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        DemoModel demo = new DemoModel();
                        demo.id   = Convert.ToInt32(dataReader["id"]);
                        demo.Name = Convert.ToString(dataReader["Name"]);
                        demoList.Add(demo);
                    }
                }
                connection.Close();
                ViewBag.id   = demoList[0].id;
                ViewBag.Name = demoList[0].Name;
            }
            return(View());
        }
Exemple #30
0
        static void Invoke(IDemo demo, UserInfo userInfo, DemoModel data)
        {
            try
            {
                userInfo.UserName += "_c";
                demo.Create(data, userInfo);
            }
            catch (ActionForbiddenException e)
            {
                Console.WriteLine($"创建执行失败:{(e.InnerException ?? e).Message}");
            }

            try
            {
                userInfo.UserName += "_e";
                data.Message       = "修改调用验证";
                demo.Modified(data, userInfo);
            }
            catch (ActionForbiddenException e)
            {
                Console.WriteLine($"修改执行失败:{(e.InnerException ?? e).Message}");
            }

            try
            {
                userInfo.UserName += "_d";
                demo.Delete(data.PrimaryKey, userInfo);
            }
            catch (ActionForbiddenException e)
            {
                Console.WriteLine($"删除执行失败:{(e.InnerException ?? e).Message}");
            }
        }
Exemple #31
0
            /// 使用するデータのセット
            public void Start( DemoModel.BasicModel useModel, DemoModel.TexContainer useTexCnr, DemoModel.ShaderContainer useShaderCnr )
            {
                this.useModel        = useModel;
                this.useTexCnr       = useTexCnr;
                this.useShaderCnr    = useShaderCnr;

                this.useModel.BindTextures( this.useTexCnr );
            }
 /// <summary>
 /// Persists a new demo in the data store.
 /// </summary>
 /// <param name="demo">The <see cref="DemoModel"/> instance to persist</param>
 public void Persist(DemoModel demo)
 {
     collection.Insert(demo);
 }
Exemple #33
0
		protected void InitWithDefaultFBO(int defaultFBOName)
		{
			Console.WriteLine(string.Format("{0} {1}", GL.GetString(StringName.Renderer), GL.GetString(StringName.Version)));
			
			////////////////////////////////////////////////////
			// Build all of our and setup initial state here  //
			// Don't wait until our real time run loop begins //
			////////////////////////////////////////////////////
			m_defaultFBOName = defaultFBOName;
			
			m_viewWidth = 100;
			m_viewHeight = 100;
			
			m_characterAngle = 0;
#if USE_VERTEX_BUFFER_OBJECTS
			m_useVBOs = true;
#else
			m_useVBOs = false;
#endif
			
			var filePathName = string.Empty;
			
			//////////////////////////////
			// Load our character model //
			//////////////////////////////
			
			filePathName = NSBundle.MainBundle.PathForResource("GLData/demon", "model");
			m_characterModel = DemoModel.LoadModel(filePathName);
			
			// Build Vertex uffer Objects (VBOs) and Vertex Array Objects (VAOs) with our model data
			m_characterVAOName = BuildVAO(m_characterModel);
			
			// Cache the number of element and primtType to use later in our GL.DrawElements calls
			m_characterNumElements = m_characterModel.NumElements;
			m_characterPrimType = m_characterModel.PrimType;
			m_characterElementType = m_characterModel.ElementType;
			
			if(m_useVBOs)
			{
				//If we're using VBOs we can destroy all this memory since buffers are
				// loaded into GL and we've saved anything else we need
				m_characterModel = null;
			}
			
			
			////////////////////////////////////
			// Load texture for our character //
			////////////////////////////////////
			
			filePathName = NSBundle.MainBundle.PathForResource("GLData/demon", "png");
			var image = DemoImage.LoadImage(filePathName, false);
			
			// Build a texture object with our image data
			m_characterTexName = BuildTexture(image);
			
			////////////////////////////////////////////////////
			// Load and Setup shaders for character rendering //
			////////////////////////////////////////////////////

			DemoSource vtxSource = null;
			DemoSource frgSource = null;
			
			filePathName = NSBundle.MainBundle.PathForResource("Shaders/character", "vsh");
			vtxSource = DemoSource.LoadSource(filePathName);
			
			filePathName = NSBundle.MainBundle.PathForResource("Shaders/character", "fsh");
			frgSource = DemoSource.LoadSource(filePathName);
			
			// Build program
			m_characterPrgName = BuildProgramWithVertexSource(vtxSource, frgSource, false, true);
			
			m_characterMvpUniformIdx = GL.GetUniformLocation(m_characterPrgName, "modelViewProjectionMatrix");
			
			if(m_characterMvpUniformIdx < 0)
				Console.WriteLine("No modelViewProjectionMatrix in character shader");
			
#if RENDER_REFLECTION
			
			m_reflectWidth = 512;
			m_reflectHeight = 512;
			
			////////////////////////////////////////////////
			// Load a model for a quad for the reflection //
			////////////////////////////////////////////////
			
			m_quadModel = DemoModel.LoadQuadModel();
			
			// build Vertex Buffer Objects (VBOs) and Vertex Array Object (VAOs) with our model data
			m_reflectVAOName = BuildVAO(m_quadModel);
			
			// Cache the number of element and prim type to use later in our GL.DrawElements calls
			m_quadNumElements = m_quadModel.NumElements;
			m_quadPrimType = m_quadModel.PrimType;
			m_quadElementType = m_quadModel.ElementType;
			
			if(m_useVBOs)
			{
				// Release quad Model;
				m_quadModel = null;
			}
			
			/////////////////////////////////////////////////////
			// Create texture and FBO for reflection rendering //
			/////////////////////////////////////////////////////
			
			m_reflectFBOName = BuildFBOWithWidth(m_reflectWidth, m_reflectHeight);
			
			// Get the texture we created in buildReflectFBO by binding the
			// reflection FBO and getting the buffer attached to color 0
			GL.BindFramebuffer(FramebufferTarget.Framebuffer, m_reflectFBOName);
			
			int iReflectTexName = 0;
			
			GL.GetFramebufferAttachmentParameter(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, FramebufferParameterName.FramebufferAttachmentObjectName, out iReflectTexName);
			
			m_reflectTexName = iReflectTexName;
			
			/////////////////////////////////////////////////////
			// Load and setup shaders for reflection rendering //
			/////////////////////////////////////////////////////
			
			filePathName = NSBundle.MainBundle.PathForResource("Shaders/reflect", "vsh");
			vtxSource = DemoSource.LoadSource(filePathName);
			
			filePathName = NSBundle.MainBundle.PathForResource("Shaders/reflect", "fsh");
			frgSource = DemoSource.LoadSource (filePathName);
			
			// Build Program
			m_reflectPrgName = BuildProgramWithVertexSource(vtxSource, frgSource, true, false);
			
			m_reflectModelViewUniformIdx = GL.GetUniformLocation(m_reflectPrgName, "modelViewMatrix");
			
			if(m_reflectModelViewUniformIdx < 0)
				Console.WriteLine("No modelViewMatrix in reflection shader");
			
			m_reflectProjectionuniformIdx = GL.GetUniformLocation(m_reflectPrgName, "modelViewProjectionMatrix");
			
			if(m_reflectProjectionuniformIdx < 0)
				Console.WriteLine("No modelViewProjectionMatrix in reflection shader");
			
			m_reflectNormalMatrixUniformIdx = GL.GetUniformLocation(m_reflectPrgName, "normalMatrix");
			
			if(m_reflectNormalMatrixUniformIdx <0)
				Console.WriteLine("No normalMatrix in reflection shader");

#endif // RENDER_REFLECTION
			
			////////////////////////////////////////////////
			// Set up OpenGL state that will never change //
			////////////////////////////////////////////////
			
			// Depth test will always be enabled
			GL.Enable(EnableCap.DepthTest);
			
			// We will always cull back faces for better performance
			GL.Enable(EnableCap.CullFace);
			
			// Always use this clear color
			GL.ClearColor(.5f, .4f, .5f, 1.0f);
			
			// Draw our scene once without presenting the rendered image.
			// This is done in order to pre-warm OpenGL
			// We don't need to present the buffer since we don't actually want the
			// user to see this, we're only drawing as a pre-warm stage
			Render();
			
			// Reset the m_characterAngle which is incremented in render
			m_characterAngle = 0;
			
			// Check for errors to make sure all of our setup went ok
			GetGLError();
		}
Exemple #34
0
		unsafe int BuildVAO(DemoModel model)
		{
			int vaoName = 0;
			
			// Create a vertex array object (VAO) to cache model parameters
			GL.Oes.GenVertexArrays(1, out vaoName);
			GL.Oes.BindVertexArray(vaoName);
	
			if(m_useVBOs)
			{
				int posBufferName = 0;
				
				// Creat a vertex buffer object (VBO) to store positions
				GL.GenBuffers(1, out posBufferName);
				
				// Allocate and load position data into the VBO
				//int size = (int) model.PositionArraySize;
				//fixed (void *ptr = &size) {
				//	GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr (ptr), model.Positions, BufferUsage.StaticDraw);
				//}
				GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)model.PositionArraySize, model.Positions, BufferUsage.StaticDraw);
				
				// Enable the position attribute for this VAO
				GL.EnableVertexAttribArray(POS_ATTRIB_IDX);
				
				// Get the size of the position type so we can set the stride properly
				var posTypeSize = GetGLTypeSize(model.PositionType);
				
				// Setup parameters for position attribute in the VAO including,
				// size, type, stride, and offset in the currently bound VAO
				// This also attaches the position VBO to the VAO
				GL.VertexAttribPointer(POS_ATTRIB_IDX, 		// What attribute index will this array feed in the vertex shader (see BuildProgram)
				                       model.PositionSize,	// How many element are there per position?
				                       model.PositionType,  // What is the type of this data?
				                       false,				// Do we want to normalize this data (0-1 range for fixed-point types)
				                       model.PositionSize * posTypeSize, // What is the stride (i.e. bytes between position)?
				                       new int[0]);
				
				if(model.Normals != null)
				{
					int normalBufferName = 0;
					
					// Create a vertex buffer object (VBO) to store positions
					GL.GenBuffers(1, out normalBufferName);
					GL.BindBuffer(BufferTarget.ArrayBuffer, normalBufferName);
					
					// Allocate and load normal data into the VBO
					GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)model.NormalArraySize, model.Normals, BufferUsage.StaticDraw);
					
					// Enable the normal attribute for this VAO
					GL.EnableVertexAttribArray(NORMAL_ATTRIB_IDX);
					
					// Get the size of the normal type so we can set the stride properly
					var normalTypeSize = GetGLTypeSize(model.NormalType);
					
					// Set up parameters for position attribute in the VAO including,
					// size, type, stride, and offset in the currently bound VAO
					// This also attaches the position VBO to the VAO
					GL.VertexAttribPointer(NORMAL_ATTRIB_IDX, // What attribue index will this array feed in the vertex shader
					                       model.NormalSize,  // How many elements are there per normal?
					                       model.NormalType,  // What is the type of this data?
					                       false,			  // Do we want to normalize this data (0-1 range for fixed-point types)
					                       model.NormalSize * normalTypeSize, // What is the stride.
					                       new int[0]);
				}
				
				if(model.TexCoords != null)
				{
					int texcoordBufferName = 0;
					
					// Create a VBO to store texcoords
					GL.GenBuffers(1, out texcoordBufferName);
					GL.BindBuffer(BufferTarget.ArrayBuffer, texcoordBufferName);
					
					// Allocate and load texcoord data into the VBO
					GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)model.TexCoordArraySize, model.TexCoords, BufferUsage.StaticDraw);
					
					// Enable the texcoord attribute for this VAO
					GL.EnableVertexAttribArray(TEXCOORD_ATTRIB_IDX);
					
					// Get the size of the texcoord type so we can set the stride properly
					var texcoordTypeSize = GetGLTypeSize(model.TexCoordType);
					
					// Set up parameters for texcoord attribute in the VAO including,
					// size, type, stride, and oofset in the currently bound VAO
					// This also attaches the texcoord VBO to VAO
					GL.VertexAttribPointer(TEXCOORD_ATTRIB_IDX, // What attribute index will this array feed in the vertex shader
					                       model.TexCoordsSize, // How many elements are there per texture coord?
					                       model.TexCoordType,  // What is the type of this data in the array?
					                       true,				// Do we want to normalize this data
					                       model.TexCoordsSize * texcoordTypeSize, // What is the stride
					                       new int[0]);
				}
				
				int elementBufferName = 0;
				
				// Create a VBO to vertex array elements
				// This also attaches the element array buffer to the VAO
				GL.GenBuffers(1, out elementBufferName);
				GL.BindBuffer(BufferTarget.ArrayBuffer, elementBufferName);
				
				// Allocate and load vertex array element data into VBO
				GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)model.ElementArraySize, model.Elements, BufferUsage.StaticDraw);
			}
			else{
				
				// Enable the position attribute for this VAO
				GL.EnableVertexAttribArray(POS_ATTRIB_IDX);
				
				// Get the size of the position type so we can set the stride propertly
				var posTypeSize = GetGLTypeSize(model.PositionType);
				
				// Set up parameters for position attribute in the VAO including,
				// size, type, stride, and offset in the currently bound VAO
				// This also attaches the position VBO to the VAO
				GL.VertexAttribPointer(POS_ATTRIB_IDX,  // What attibute index will this array feed in the vertex shader? (also see buildProgram)
							 		 model.PositionSize,  // How many elements are there per position?
									 model.PositionType,  // What is the type of this data
							  		 false,				// Do we want to normalize this data (0-1 range for fixed-pont types)
							     	 model.PositionSize*posTypeSize, // What is the stride (i.e. bytes between positions)?
							  		 model.Positions);    // Where is the position data in memory?
				
				if(model.Normals != null)
				{			
					// Enable the normal attribute for this VAO
					GL.EnableVertexAttribArray(NORMAL_ATTRIB_IDX);
					
					// Get the size of the normal type so we can set the stride properly
					var normalTypeSize = GetGLTypeSize(model.NormalType);
					
					// Set up parmeters for position attribute in the VAO including, 
					//   size, type, stride, and offset in the currenly bound VAO
					// This also attaches the position VBO to the VAO
					GL.VertexAttribPointer(NORMAL_ATTRIB_IDX,	// What attibute index will this array feed in the vertex shader (see buildProgram)
										  model.NormalSize,	// How many elements are there per normal?
										  model.NormalType,	// What is the type of this data?
										  false,				// Do we want to normalize this data (0-1 range for fixed-pont types)
										  model.NormalSize * normalTypeSize, // What is the stride (i.e. bytes between normals)?
										  model.Normals);	    // Where is normal data in memory?
				}
				
				if(model.TexCoords != null)
				{
					// Enable the texcoord attribute for this VAO
					GL.EnableVertexAttribArray(TEXCOORD_ATTRIB_IDX);
					
					// Get the size of the texcoord type so we can set the stride properly
					var texcoordTypeSize = GetGLTypeSize(model.TexCoordType);
					
					// Set up parmeters for texcoord attribute in the VAO including, 
					//   size, type, stride, and offset in the currenly bound VAO
					// This also attaches the texcoord array in memory to the VAO	
					GL.VertexAttribPointer(TEXCOORD_ATTRIB_IDX,	// What attibute index will this array feed in the vertex shader (see buildProgram)
										  model.TexCoordsSize,	// How many elements are there per texture coord?
										  model.TexCoordType,	// What is the type of this data in the array?
										  false,				// Do we want to normalize this data (0-1 range for fixed-point types)
										  model.TexCoordsSize * texcoordTypeSize,  // What is the stride (i.e. bytes between texcoords)?
										  model.TexCoords);	// Where is the texcood data in memory?
				}

			}			
			
			GetGLError();
			
			return vaoName;
		}