/// <summary> /// News up an empty entity /// </summary> public Inanimate() { //IDatas need parameterless constructors Contents = new EntityContainer<IInanimate>(); Pathways = new EntityContainer<IPathway>(); MobilesInside = new EntityContainer<IMobile>(); }
/// <summary> /// News up an entity with its backing data and where to spawn it into /// </summary> /// <param name="backingStore">the backing data</param> /// <param name="spawnTo">where to spawn this into</param> public Inanimate(IInanimateData backingStore, IContains spawnTo) { Contents = new EntityContainer<IInanimate>(backingStore.InanimateContainers); Pathways = new EntityContainer<IPathway>(); MobilesInside = new EntityContainer<IMobile>(backingStore.MobileContainers); DataTemplateId = backingStore.ID; SpawnNewInWorld(spawnTo); }
public Inanimate(DimensionalModel model) { Model = model; //IDatas need parameterless constructors Contents = new EntityContainer<IInanimate>(); Pathways = new EntityContainer<IPathway>(); MobilesInside = new EntityContainer<IMobile>(); }
/// <summary> /// Returns the entity container in CSpace or SSpace /// </summary> /// <param name="name"> </param> /// <param name="ignoreCase"> </param> /// <param name="entityContainer"> </param> /// <returns> </returns> internal override bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer) { if (!base.TryGetEntityContainer(name, ignoreCase, out entityContainer)) { return _modelPerspective.TryGetEntityContainer(name, ignoreCase, out entityContainer); } return true; }
public App() { UnhandledException += Application_UnhandledException; InitializeComponent(); InitializePhoneApplication(); if (System.Diagnostics.Debugger.IsAttached) Current.Host.Settings.EnableFrameRateCounter = true; Persons = new EntityContainer<Person>(); }
internal FunctionImportElement(EntityContainer container) : base(container.Schema) { if (Schema.DataModel == SchemaDataModelOption.EntityDataModel) OtherContent.Add(Schema.SchemaSource); _container = container; // By default function imports are non-composable. _isComposable = false; }
private Dictionary<EntitySetBase, GeneratedView> SerializedGetGeneratedViews(EntityContainer container) { Debug.Assert(container != null); // Note that extentMappingViews will contain both query and update views. Dictionary<EntitySetBase, GeneratedView> extentMappingViews; // Get the mapping that has the entity container mapped. var entityContainerMap = MappingMetadataHelper.GetEntityContainerMap(m_storageMappingItemCollection, container); // We get here because memoizer didn't find an entry for the container. // It might happen that the entry with generated views already exists for the counterpart container, so check it first. var counterpartContainer = container.DataSpace == DataSpace.CSpace ? entityContainerMap.StorageEntityContainer : entityContainerMap.EdmEntityContainer; if (m_generatedViewsMemoizer.TryGetValue(counterpartContainer, out extentMappingViews)) { return extentMappingViews; } extentMappingViews = new Dictionary<EntitySetBase, GeneratedView>(); if (!entityContainerMap.HasViews) { return extentMappingViews; } // If we are in generated views mode. if (m_generatedViewsMode) { if (ObjectItemCollection.ViewGenerationAssemblies != null && ObjectItemCollection.ViewGenerationAssemblies.Count > 0) { SerializedCollectViewsFromObjectCollection(m_storageMappingItemCollection.Workspace, extentMappingViews); } else { SerializedCollectViewsFromReferencedAssemblies(m_storageMappingItemCollection.Workspace, extentMappingViews); } } if (extentMappingViews.Count == 0) { // We should change the mode to runtime generation of views. m_generatedViewsMode = false; SerializedGenerateViews(entityContainerMap, extentMappingViews); } Debug.Assert(extentMappingViews.Count > 0, "view should be generated at this point"); return extentMappingViews; }
/// <summary> /// /// </summary> /// <param name="metadataWorkspace"></param> /// <param name="entityContainer">Code first or DB first entityContainer</param> protected MapperBase(MetadataWorkspace metadataWorkspace, EntityContainer entityContainer) { MetadataWorkspace = metadataWorkspace; EntityContainer = entityContainer; var relations = MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<AssociationType>(); foreach (var associationType in relations) { foreach (var referentialConstraint in associationType.ReferentialConstraints) { for (int i = 0; i < referentialConstraint.ToProperties.Count; ++i) { _fks[referentialConstraint.ToProperties[i]] = referentialConstraint.FromProperties[i]; } } } }
///<summary> /// Animates movement of Block ///</summary> ///<param name = "StartBoardCoords"> Animation starting coords </param> ///<param name = "EndBoardCoords"> Animation ending coords </param> ///<param name = "block"> Block that will be visualized </param> ///<param name = "FillContainer"> If true, at the end of animation, EntityContainer corresponding to EndBoardCoords will change its Visual Reprezentation from background to Block</param> public IEnumerator AnimateBlockMovement(Vector2 StartBoardCoords, Vector2 EndBoardCoords, Block block, bool FillContainer) { Vector2 startBoardCoords = StartBoardCoords; Vector2 startRealCoords = entityCointainersTop[(int)startBoardCoords.x, (int)startBoardCoords.y].GetPosition(); Vector2 endRealCoords = entityCointainersTop[(int)EndBoardCoords.x, (int)EndBoardCoords.y].GetPosition(); GameObject Block = (GameObject)Instantiate(blockPrefab); Block.transform.SetParent(entityCointainersTopParent, false); EntityContainer container = Block.GetComponent <BlockContainer>(); container.Entity = block; container.SetPosition(startRealCoords); Vector2 dir = (endRealCoords - startRealCoords).normalized; while (Vector2.Distance(container.GetPosition(), endRealCoords) >= 10) { container.SetPosition(container.GetPosition() + dir * blockMoveSpeed * Time.deltaTime); yield return(new WaitForEndOfFrame()); } if (FillContainer) { FillContainerWithEntity(EndBoardCoords, block); } else { AudioManager.PlayIfNotAlreadyPlayed("block_out"); } Destroy(Block); yield break; }
public Attempt <OperationStatus <EntityContainer, OperationStatusType> > CreateContainer(int parentId, string name, int userId = 0) { var evtMsgs = EventMessagesFactory.Get(); using (var uow = UowProvider.GetUnitOfWork()) { var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid); try { var container = new EntityContainer(Constants.ObjectTypes.DataTypeGuid) { Name = name, ParentId = parentId, CreatorId = userId }; if (uow.Events.DispatchCancelable(SavingContainer, this, new SaveEventArgs <EntityContainer>(container, evtMsgs))) { uow.Commit(); return(Attempt.Fail(new OperationStatus <EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs))); } repo.AddOrUpdate(container); uow.Commit(); uow.Events.Dispatch(SavedContainer, this, new SaveEventArgs <EntityContainer>(container, evtMsgs)); //TODO: Audit trail ? return(Attempt.Succeed(new OperationStatus <EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs))); } catch (Exception ex) { return(Attempt.Fail(new OperationStatus <EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex)); } } }
public void Can_Delete_Container_Containing_Media_Types() { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); EntityContainer container; IMediaType contentType; using (var containerRepository = CreateContainerRepository(unitOfWork, Constants.ObjectTypes.MediaTypeContainerGuid)) using (var repository = CreateMediaTypeRepository(unitOfWork)) { container = new EntityContainer(Constants.ObjectTypes.MediaTypeGuid) { Name = "blah" }; containerRepository.AddOrUpdate(container); unitOfWork.Commit(); contentType = MockedContentTypes.CreateSimpleMediaType("test", "Test", propertyGroupName: "testGroup"); contentType.ParentId = container.Id; repository.AddOrUpdate(contentType); unitOfWork.Commit(); } using (var containerRepository = CreateContainerRepository(unitOfWork, Constants.ObjectTypes.MediaTypeContainerGuid)) using (var repository = CreateMediaTypeRepository(unitOfWork)) { // Act containerRepository.Delete(container); unitOfWork.Commit(); var found = containerRepository.Get(container.Id); Assert.IsNull(found); contentType = repository.Get(contentType.Id); Assert.IsNotNull(contentType); Assert.AreEqual(-1, contentType.ParentId); } }
/// <summary> /// 获取管理员列表(分页) /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public JsonRsp<BankAccountViewModel> GetPageList(int pageIndex, int pageSize,bool limit=true) { JsonRsp<BankAccountViewModel> rsp = new JsonRsp<BankAccountViewModel>(); BankAccountModel ba = new BankAccountModel(); BankModel b = new BankModel(); OQL joinQ = OQL.From(ba) .Join(b).On(ba.BankId, b.ID) .Select() .OrderBy(ba.Sort, "desc") .END; //分页 if (limit) { joinQ.Limit(pageSize, pageIndex, true); } PWMIS.DataProvider.Data.AdoHelper db = PWMIS.DataProvider.Adapter.MyDB.GetDBHelper(); EntityContainer ec = new EntityContainer(joinQ, db); rsp.data = (List<BankAccountViewModel>)ec.MapToList<BankAccountViewModel>(() => new BankAccountViewModel() { ID = ba.ID, BankAccountName = ba.BankAccountName, BankName=b.BankName, BankId = ba.BankId, BankAccountCode=ba.BankAccountCode, CreateBy = ba.CreateUser, CreateIP = ba.CreateIP, CreateTime = ba.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), Sort = ba.Sort, Status = ba.Status, }) ; rsp.success = true; rsp.code = 0; rsp.count = joinQ.PageWithAllRecordCount; return rsp; }
public override bool TryParse(string path, ref RangeInt cursor, out IWatchContext ctx) { var c = cursor; if (ParserUtils.TryParseScopeSequenceRange(path, ref c, ParserUtils.DelemiterSquareBracket, out var seqIn, out var seqOut)) { if (ParserUtils.TryParseIntAt(path, ref seqIn, out var index)) { var es = World.EntityManager.GetAllEntities(); for (int i = 0; i != es.Length; ++i) { if (es[i].Index == index) { cursor = c; var ctnr = new EntityContainer(World.EntityManager, es[i]); ctx = new PropertyPathContext <EntityContainer, EntityContainer>(this, this, $"[{es[i].Index}]", ctnr, null, ContextFieldInfo.MakeOperator($"[{es[i].Index}]")); return(true); } } } } ctx = null; return(false); }
public void Can_Delete_Container() { var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { var containerRepository = CreateContainerRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); Assert.That(container.Id, Is.GreaterThan(0)); // Act containerRepository.Delete(container); var found = containerRepository.Get(container.Id); Assert.IsNull(found); } }
public void Load(ContentManager content) { _blockWorldEffect = content.Load <Effect>("blockWorld"); _modelEffect = content.Load <Effect>("modelEffect"); _blockAtlas = content.Load <Texture2D>("IsomitesAtlas"); EntitySchematics.Init(content, _modelEffect); SM = new SegmentManager(Device); _editor = new WorldEditor(SM); _editor.LoadContent(content, _modelEffect); EC = new EntityContainer(this); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(0, 4, 0))); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(2, 4, 0))); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(4, 4, 0))); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(6, 4, 0))); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(8, 4, 0))); EC.AddEntityExternal(new BaseEntity(this, EntitySchematics.Tree, new Vector3(10, 4, 0))); _man = new BaseEntityAi(this, EntitySchematics.Man, new Vector3(10, 4, 10)); JM.AddJob(new EntityJob(EntitySchematics.Tree)); }
public void Can_Create_Container_Containing_Data_Types() { var provider = TestObjects.GetScopeProvider(Logger); var accessor = (IScopeAccessor)provider; using (provider.CreateScope()) { var containerRepository = CreateContainerRepository(accessor); var repository = CreateRepository(); var container = new EntityContainer(Constants.ObjectTypes.DataType) { Name = "blah" }; containerRepository.Save(container); var dataTypeDefinition = new DataType(new RadioButtonsPropertyEditor(Logger, ServiceContext.TextService), container.Id) { Name = "test" }; repository.Save(dataTypeDefinition); Assert.AreEqual(container.Id, dataTypeDefinition.ParentId); } }
public void Can_Create_Container_Containing_Media_Types() { var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { var containerRepository = CreateContainerRepository(provider); var repository = CreateRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); var contentType = MockedContentTypes.CreateVideoMediaType(); contentType.ParentId = container.Id; repository.Save(contentType); Assert.AreEqual(container.Id, contentType.ParentId); } }
public static bool ExistsMappingTypeName(Type dotNetEntityType, ObjectContext defaultContext) { // dotNetEntityType can be a POCO object with no ObjectContext. We are getting proxy for the POCO // object which will have the context needed for LINQ stuff Type objectType = ObjectContext.GetObjectType(dotNetEntityType); ObjectContext context = TypesToContexts.GetOrDefault(objectType.FullName, defaultContext); EntityContainer entityContainer = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace); EntitySetBase entitySet = entityContainer.BaseEntitySets.FirstOrDefault(es => es.ElementType.Name == objectType.Name); if (entitySet != null) { _typeNamesMapping.GetOrAdd(objectType.FullName, () => { return(entitySet.ElementType.FullName); }); return(true); } else { return(false); } }
public Game() { win = new Window("Mad man", 500, 500); gameTimer = new GameTimer(60, 60); score = new Score(new Vec2F(0.05f, 0.8f), new Vec2F(0.2f, 0.2f)); gameState = GameState.GamePlaying; GameOverDisPlay = new GameOverDisPlay(); player = new Player( new DynamicShape(new Vec2F(0.45f, 0.1f), new Vec2F(0.1f, 0.1f)), new Image(System.IO.Path.Combine("Assets", "Images", "Player.png")), this); enemyStrides = ImageStride.CreateStrides(4, System.IO.Path.Combine("Assets", "Images", "BlueMonster.png")); enemies = new EntityContainer <Enemy>(); AddEnemies(new Squadron.Formation(6)); currentMoveStrategy = new MovementStrategies.NoMove(); playerShots = new EntityContainer <PlayerShot>(); explosionStrides = ImageStride.CreateStrides(8, System.IO.Path.Combine("Assets", "Images", "Explosion.png")); explosions = new AnimationContainer(8); eventBus = new GameEventBus <object>(); eventBus.InitializeEventBus(new List <GameEventType>() { GameEventType.InputEvent, GameEventType.WindowEvent, GameEventType.PlayerEvent, }); win.RegisterEventBus(eventBus); eventBus.Subscribe(GameEventType.InputEvent, this); eventBus.Subscribe(GameEventType.WindowEvent, this); eventBus.Subscribe(GameEventType.PlayerEvent, player); }
public SqliteAssociationType(AssociationType associationType, EntityContainer container) { FromRoleEntitySetName = associationType.Constraint.FromRole.Name; ToRoleEntitySetName = associationType.Constraint.ToRole.Name; string fromTable = container.GetEntitySetByName(FromRoleEntitySetName, true).Table; string toTable; if (IsSelfReferencing(associationType)) { toTable = fromTable; ToRoleEntitySetName = FromRoleEntitySetName; } else { toTable = container.GetEntitySetByName(ToRoleEntitySetName, true).Table; } FromTableName = TableNameCreator.CreateTableName(fromTable); ToTableName = TableNameCreator.CreateTableName(toTable); ForeignKey = associationType.Constraint.ToProperties.Select(x => x.Name); ForeignPrimaryKey = associationType.Constraint.FromProperties.Select(x => x.Name); CascadeDelete = associationType.Constraint.FromRole.DeleteBehavior == OperationAction.Cascade; }
public Game() { win = new Window("Galaga", 500, AspectRatio.R16X9); player = new Player(); enemies = new EntityContainer(); projtIteratorMethod = ProjectileIterator; destoryIterator = DestoryIterator; enemyStrides = new ImageStride(80, ImageStride.CreateStrides(4, Path.Combine("Assets", "Images", "BlueMonster.png"))); explosionStrides = ImageStride.CreateStrides(8, Path.Combine("Assets", "Images", "Explosion.png")); explosions = new AnimationContainer(10); AddEnemies(); eventBus = new GameEventBus <object>(); eventBus.InitializeEventBus(new List <GameEventType>() { GameEventType.InputEvent, // key press / key release GameEventType.WindowEvent, // messages to the window GameEventType.PlayerEvent // commands issued to the player object, }); // e.g. move, destroy, receive health, etc. win.RegisterEventBus(eventBus); eventBus.Subscribe(GameEventType.InputEvent, this); eventBus.Subscribe(GameEventType.WindowEvent, this); eventBus.Subscribe(GameEventType.PlayerEvent, player); gameTimer = new GameTimer(60, 60); }
private bool TryResolveEntityContainerMemberAccess( EntityContainer entityContainer, string name, out ExpressionResolution resolution) { EntitySetBase entitySetBase; EdmFunction functionImport; if (TypeResolver.Perspective.TryGetExtent( entityContainer, name, _parserOptions.NameComparisonCaseInsensitive /*ignoreCase*/, out entitySetBase)) { resolution = new ValueExpression(entitySetBase.Scan()); return(true); } else if (TypeResolver.Perspective.TryGetFunctionImport( entityContainer, name, _parserOptions.NameComparisonCaseInsensitive /*ignoreCase*/, out functionImport)) { resolution = new MetadataFunctionGroup(functionImport.FullName, new[] { functionImport }); return(true); } else { resolution = null; return(false); } }
public Game() { gameTimer = new GameTimer(60, 60); win = new Window("Galaca", 500, AspectRatio.R1X1); backGround = new Image(Path.Combine("Assets", "Images", "SpaceBackground.png")); player = new Player(); enemies = new EntityContainer <Enemy>(); enemyStrides = ImageStride.CreateStrides(4, Path.Combine("Assets", "Images", "BlueMonster.png")); var sqr = new Squadron2(); sqr.CreateEnemies(enemyStrides); enemies = sqr.Enemies; movementStrategy = new ZigZagDown(); playerShots = new EntityContainer(); shotStride = new Image(Path.Combine("Assets", "Images", "BulletRed2.png")); explosionStrides = ImageStride.CreateStrides(8, Path.Combine("Assets", "Images", "Explosion.png")); explosions = new AnimationContainer(4); eventBus = new GameEventBus <object>(); eventBus.InitializeEventBus(new List <GameEventType>() { GameEventType.InputEvent, GameEventType.WindowEvent, GameEventType.PlayerEvent }); win.RegisterEventBus(eventBus); eventBus.Subscribe(GameEventType.InputEvent, this); eventBus.Subscribe(GameEventType.WindowEvent, this); }
public CodeFirstMapper(MetadataWorkspace metadataWorkspace, EntityContainer entityContainer) : base(metadataWorkspace, entityContainer) { }
public IncentiveRepository(DataSource ds) { this.ds = ds; employeeRepository = EntityContainer.GetType <IEmployeeRepository>(); companyRepository = EntityContainer.GetType <ICompanyRepository>(); }
public void MoveEnemies(EntityContainer <Enemy> enemies) { enemies.Iterate(MoveEnemy); }
public void MoveEnemies(EntityContainer <Enemy> enemies) { }
/// <summary> /// Generates a single query view for a given Extent and type. It is used to generate OfType and OfTypeOnly views. /// </summary> /// <param name="includeSubtypes"> Whether the view should include extents that are subtypes of the given entity </param> private bool TryGenerateQueryViewOfType( EntityContainer entityContainer, EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView) { Debug.Assert(entityContainer != null); Debug.Assert(entity != null); Debug.Assert(type != null); if (type.Abstract) { generatedView = null; return false; } //Get the mapping that has the entity container mapped. var entityContainerMap = MappingMetadataHelper.GetEntityContainerMap(m_storageMappingItemCollection, entityContainer); Debug.Assert(!entityContainerMap.IsEmpty, "There are no entity set maps"); bool success; var viewGenResults = ViewgenGatekeeper.GenerateTypeSpecificQueryView( entityContainerMap, _config, entity, type, includeSubtypes, out success); if (!success) { generatedView = null; return false; //could not generate view } var extentMappingViews = viewGenResults.Views; if (viewGenResults.HasErrors) { throw new MappingException(Helper.CombineErrorMessage(viewGenResults.Errors)); } Debug.Assert(extentMappingViews.AllValues.Count() == 1, "Viewgen should have produced only one view"); generatedView = extentMappingViews.AllValues.First(); return true; }
/// <summary> /// Constructs an EntityContainerAssociationSet /// </summary> /// <param name="parentElement">Reference to the schema element.</param> public EntityContainerAssociationSet(EntityContainer parentElement) : base(parentElement) { }
/// <summary> /// Converts an association set from SOM to metadata /// </summary> /// <param name="relationshipSet">The SOM element to process</param> /// <param name="providerManifest">The provider manifest to be used for conversion</param> /// <param name="convertedItemCache">The item collection for currently existing metadata objects</param> /// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param> /// <param name="container"></param> /// <returns>The association set object resulting from the convert</returns> private static AssociationSet ConvertToAssociationSet( Som.EntityContainerRelationshipSet relationshipSet, DbProviderManifest providerManifest, ConversionCache convertedItemCache, EntityContainer container, Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems) { Debug.Assert(relationshipSet.Relationship.RelationshipKind == RelationshipKind.Association); var associationType = (AssociationType)LoadSchemaElement( (Som.SchemaType)relationshipSet.Relationship, providerManifest, convertedItemCache, newGlobalItems); var associationSet = new AssociationSet(relationshipSet.Name, associationType); foreach (var end in relationshipSet.Ends) { //-- need the EntityType for the end var endEntityType = (EntityType)LoadSchemaElement( end.EntitySet.EntityType, providerManifest, convertedItemCache, newGlobalItems); //-- need to get the end member var endMember = (AssociationEndMember)associationType.Members[end.Name]; //-- create the end var associationSetEnd = new AssociationSetEnd( GetEntitySet(end.EntitySet, container), associationSet, endMember); AddOtherContent(end, associationSetEnd); associationSet.AddAssociationSetEnd(associationSetEnd); // Extract optional Documentation from the end element if (end.Documentation != null) { associationSetEnd.Documentation = ConvertToDocumentation(end.Documentation); } } // Extract the optional Documentation if (relationshipSet.Documentation != null) { associationSet.Documentation = ConvertToDocumentation(relationshipSet.Documentation); } AddOtherContent(relationshipSet, associationSet); return associationSet; }
public XRootNamespace(EntityContainer root) { _doc = new XDocument(root.Untyped); _rootObject = root; }
/// <summary> /// Handler for the EntityContainer element /// </summary> /// <param name="reader">xml reader currently positioned at EntityContainer element</param> private void HandleEntityContainerTypeElement(XmlReader reader) { Debug.Assert(reader != null); EntityContainer type = new EntityContainer(this); type.Parse(reader); TryAddContainer(type, true/*doNotAddErrorForEmptyName*/); }
public void OnEntityDestroyed(EntityContainer container) { // if we don't have a snapshot, then we don't care that the entity was destroyed if (Snapshot == null) { return; } IEntity entity = container.Entity; GameSnapshotEntityRemoveResult removeResult = Snapshot.RemoveEntity(entity); switch (removeResult) { case GameSnapshotEntityRemoveResult.Destroyed: break; case GameSnapshotEntityRemoveResult.IntoRemoved: EntityContainer.CreateEntityContainer(entity, RemovedChild); break; case GameSnapshotEntityRemoveResult.Failed: Debug.LogError("You cannot remove entity " + entity + " (recreating it)"); GameObject parent = container.Parent; EntityContainer.CreateEntityContainer(entity, parent); break; default: throw new InvalidOperationException("Unknown remove result " + removeResult); } }
/// <summary> /// Gets the entity set. /// </summary> /// <param name="container">The entity container.</param> /// <param name="entityType">Type of the entity.</param> /// <returns></returns> private static EntitySetBase GetEntitySet(EntityContainer container, EntityType entityType) { var baseType = entityType; while (baseType != null && baseType.BaseType != null) { baseType = baseType.BaseType as EntityType; } return container.BaseEntitySets.First(set => set.ElementType == baseType); }
/// <summary> /// Generates mappings. /// </summary> /// <param name="entityResources">The entity resources.</param> /// <param name="enumResources">The enum resources.</param> /// <param name="itemCollection">The item collection.</param> /// <param name="container">The entity container.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">itemCollection</exception> /// <exception cref="System.Exception">Unknown data type: + p.TypeUsage.EdmType.Name</exception> private static Metadata Mapping(IEnumerable<EntityResource> entityResources, IEnumerable<EnumResource> enumResources, IEnumerable<GlobalItem> itemCollection, EntityContainer container) { if (itemCollection == null) throw new ArgumentNullException("itemCollection"); var globalItems = itemCollection as IList<GlobalItem> ?? itemCollection.ToList(); var retVal = new Metadata(container.Name); // entity types foreach (var er in entityResources) { var fullName = string.Format("{0}, {1}", er.ClrType.FullName, er.ClrType.Assembly.GetName().Name); var et = new Meta.EntityType(fullName, er.Name) {TableName = er.TableName}; // entity informations if (er.Entity != null) { et.QueryName = er.EntitySet.Name; if (er.EntitySet.ElementType.Name != er.Name) et.QueryType = er.EntitySet.ElementType.Name; et.Keys.AddRange(er.Entity.KeyMembers.Select(k => k.Name)); // if entity has base type, set the base type's name if (er.Entity.BaseType != null) et.BaseTypeName = er.Entity.BaseType.Name; if (er.ClrType != null) et.ClrType = er.ClrType; // navigation properties if (er.NavigationProperties != null) { foreach (var p in er.NavigationProperties) { var ass = globalItems.OfType<AssociationType>().First(a => a.Name == p.RelationshipType.Name); Func<string> displayNameGetter = null; if (er.ClrType != null) { var propertyInfo = er.ClrType.GetMember(p.Name).FirstOrDefault(); if (propertyInfo != null) displayNameGetter = Helper.GetDisplayNameGetter(propertyInfo); } var np = new Meta.NavigationProperty(p.Name, displayNameGetter); np.EntityTypeName = (((RefType)p.ToEndMember.TypeUsage.EdmType).ElementType).Name; var isScalar = p.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many; if (isScalar) { np.IsScalar = true; np.ForeignKeys.AddRange(ass.ReferentialConstraints.SelectMany(rc => rc.ToProperties.Select(tp => tp.Name))); } if (p.FromEndMember.DeleteBehavior == OperationAction.Cascade) np.DoCascadeDelete = true; if (er.ClrType != null) Helper.PopulateNavigationPropertyValidations(er.ClrType, np); np.AssociationName = p.RelationshipType.Name; et.NavigationProperties.Add(np); } } // complex properties if (er.ComplexProperties != null) { foreach (var p in er.ComplexProperties) { Func<string> displayNameGetter = null; if (er.ClrType != null) { var propertyInfo = er.ClrType.GetMember(p.Key.Name).FirstOrDefault(); if (propertyInfo != null) displayNameGetter = Helper.GetDisplayNameGetter(propertyInfo); } var cp = new ComplexProperty(p.Key.Name, displayNameGetter) { TypeName = p.Key.TypeUsage.EdmType.Name, Mappings = p.Value }; et.ComplexProperties.Add(cp); } } } else et.IsComplexType = true; // this is a complex type // data properties foreach (var sp in er.SimpleProperties) { var p = sp.Value; var clrType = UnderlyingClrType(p.TypeUsage.EdmType); Func<string> displayNameGetter = null; if (er.ClrType != null) { var propertyInfo = clrType.GetMember(p.Name).FirstOrDefault(); if (propertyInfo != null) displayNameGetter = Helper.GetDisplayNameGetter(propertyInfo); } var dp = new DataProperty(p.Name, displayNameGetter) { ColumnName = sp.Key }; var jsType = DataType.Binary; var enumType = p.TypeUsage.EdmType as EnumType; if (enumType != null) { dp.IsEnum = true; dp.EnumType = enumType.Name; } else { // convert CLR type to javascript type if (clrType == typeof(string)) jsType = DataType.String; else if (clrType == typeof(Guid)) jsType = DataType.Guid; else if (clrType == typeof(DateTime)) jsType = DataType.Date; else if (clrType == typeof(DateTimeOffset)) jsType = DataType.DateTimeOffset; else if (clrType == typeof(TimeSpan)) jsType = DataType.Time; else if (clrType == typeof(bool)) jsType = DataType.Boolean; else if (clrType == typeof(Int16) || clrType == typeof(Int64) || clrType == typeof(Int32)) jsType = DataType.Int; else if (clrType == typeof(Single) || clrType == typeof(double) || clrType == typeof(decimal)) jsType = DataType.Number; else if (clrType == typeof(byte)) jsType = DataType.Byte; else if (clrType == typeof(DbGeography)) jsType = DataType.Geography; else if (clrType == typeof(DbGeometry)) jsType = DataType.Geometry; else if (clrType == typeof(byte[])) jsType = DataType.Binary; else throw new BeetleException(Resources.UnknownDataType + p.TypeUsage.EdmType.Name); } dp.DataType = jsType; var generated = p.MetadataProperties.FirstOrDefault(m => m.Name == StoreGeneratedPatternAttributeName); if (generated == null) dp.GenerationPattern = GenerationPattern.None; else if (generated.Value.ToString().StartsWith("I")) dp.GenerationPattern = GenerationPattern.Identity; else dp.GenerationPattern = GenerationPattern.Computed; dp.UseForConcurrency = IsConcurrencyProperty(p); if (p.Nullable) dp.IsNullable = true; if (jsType == DataType.Number) { var precision = GetPrecision(p); var scale = GetScale(p); if (precision.HasValue) dp.Precision = precision; if (scale.HasValue) dp.Scale = scale; } if (er.ClrType != null) Helper.PopulateDataPropertyValidations(er.ClrType, dp, GetMaxStringLength(p)); if (p.DefaultValue != null) dp.DefaultValue = p.DefaultValue; et.DataProperties.Add(dp); } retVal.Entities.Add(et); } // enum types foreach (var enumResource in enumResources) { var enumType = enumResource.EnumType; //var enumClrType = enumResource.ClrType; var et = new Meta.EnumType(enumType.Name); foreach (var member in enumType.Members) { //todo: enum member için display var em = new Meta.EnumMember(member.Name, null) {Value = member.Value}; et.Members.Add(em); } retVal.Enums.Add(et); } retVal.FixReferences(); return retVal; }
/// <summary> /// Converts an entity container from SOM to metadata /// </summary> /// <param name="element">The SOM element to process</param> /// <param name="providerManifest">The provider manifest to be used for conversion</param> /// <param name="convertedItemCache">The item collection for currently existing metadata objects</param> /// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param> /// <returns>The entity container object resulting from the convert</returns> private static EntityContainer ConvertToEntityContainer( Som.EntityContainer element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems) { // Creating a new entity container object and populate with converted entity set objects var entityContainer = new EntityContainer(element.Name, GetDataSpace(providerManifest)); newGlobalItems.Add(element, entityContainer); foreach (var entitySet in element.EntitySets) { entityContainer.AddEntitySetBase( ConvertToEntitySet( entitySet, providerManifest, convertedItemCache, newGlobalItems)); } // Populate with converted relationship set objects foreach (var relationshipSet in element.RelationshipSets) { Debug.Assert( relationshipSet.Relationship.RelationshipKind == RelationshipKind.Association, "We do not support containment set"); entityContainer.AddEntitySetBase( ConvertToAssociationSet( relationshipSet, providerManifest, convertedItemCache, entityContainer, newGlobalItems)); } // Populate with converted function imports foreach (var functionImport in element.FunctionImports) { entityContainer.AddFunctionImport( ConvertToFunction( functionImport, providerManifest, convertedItemCache, entityContainer, newGlobalItems)); } // Extract the optional Documentation if (element.Documentation != null) { entityContainer.Documentation = ConvertToDocumentation(element.Documentation); } AddOtherContent(element, entityContainer); return entityContainer; }
/// <summary> /// Converts an entity set from SOM to metadata /// </summary> /// <param name="set">The SOM element to process</param> /// <param name="container"></param> /// <returns>The entity set object resulting from the convert</returns> private static EntitySet GetEntitySet(Som.EntityContainerEntitySet set, EntityContainer container) { return container.GetEntitySetByName(set.Name, false); }
public void SerializationPerformanceThreaded() { const int kCount = 10000; // Create kCount entities and assign some arbitrary component data for (var i = 0; i < kCount; ++i) { var entity = m_Manager.CreateEntity(typeof(TestComponent), typeof(TestComponent2), typeof(MathComponent), typeof(BlitComponent)); var comp = m_Manager.GetComponentData <BlitComponent>(entity); comp.blit.x = 123f; comp.blit.y = 456.789; comp.blit.z = -12; comp.flt = 0.01f; m_Manager.SetComponentData(entity, comp); } using (var entities = m_Manager.GetAllEntities()) { // Since we are testing raw serialization performance we rre warm the property type bag // This builds a property tree for each type // This is done on demand for newly discovered types // @NOTE This json string will also be used to debug the size for a single entity var container = new EntityContainer(m_Manager, entities[0]); Measure.Method(() => { var numThreads = Math.Max(1, Environment.ProcessorCount - 1); var threadCount = numThreads; var countPerThread = entities.Length / threadCount + 1; var threads = new Thread[threadCount]; // Split the workload 'evenly' across numThreads (IJobParallelForBatch) for (int begin = 0, index = 0; begin < entities.Length; begin += countPerThread, index++) { var context = new WorkerThreadContext { Entities = entities, StartIndex = begin, EndIndex = Mathf.Min(begin + countPerThread, entities.Length) }; var thread = new Thread(obj => { var buffer = new StringBuffer(4096); var visitor = new JsonVisitor { StringBuffer = buffer }; var c = (WorkerThreadContext)obj; for (int p = c.StartIndex, end = c.EndIndex; p < end; p++) { var entity = c.Entities[p]; container = new EntityContainer(m_Manager, entity); JsonSerializer.Serialize(ref container, visitor); // @NOTE at this point we can call Write(buffer.Buffer, 0, buffer.Length) buffer.Clear(); } }) { IsBackground = true }; thread.Start(context); threads[index] = thread; } foreach (var thread in threads) { thread.Join(); } }) .Run(); } }
private static EdmFunction ConvertToFunction( Som.Function somFunction, DbProviderManifest providerManifest, ConversionCache convertedItemCache, EntityContainer functionImportEntityContainer, Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems) { // If we already have it, don't bother converting GlobalItem globalItem = null; // if we are converted the function import, we need not check the global items collection, // since the function imports are local to the entity container if (!somFunction.IsFunctionImport && newGlobalItems.TryGetValue(somFunction, out globalItem)) { return (EdmFunction)globalItem; } var areConvertingForProviderManifest = somFunction.Schema.DataModel == Som.SchemaDataModelOption.ProviderManifestModel; var returnParameters = new List<FunctionParameter>(); if (somFunction.ReturnTypeList != null) { var i = 0; foreach (var somReturnType in somFunction.ReturnTypeList) { var returnType = GetFunctionTypeUsage( somFunction is Som.ModelFunction, somFunction, somReturnType, providerManifest, areConvertingForProviderManifest, somReturnType.Type, somReturnType.CollectionKind, somReturnType.IsRefType /*isRefType*/, convertedItemCache, newGlobalItems); if (null != returnType) { // Create the return parameter object, need to set the declaring type explicitly on the return parameter // because we aren't adding it to the members collection var modifier = i == 0 ? string.Empty : i.ToString(CultureInfo.InvariantCulture); i++; var returnParameter = new FunctionParameter( EdmConstants.ReturnType + modifier, returnType, ParameterMode.ReturnValue); AddOtherContent(somReturnType, returnParameter); returnParameters.Add(returnParameter); } else { return null; } } } // this case must be second to avoid calling somFunction.Type when returnTypeList has more than one element. else if (somFunction.Type != null) { var returnType = GetFunctionTypeUsage( somFunction is Som.ModelFunction, somFunction, null, providerManifest, areConvertingForProviderManifest, somFunction.Type, somFunction.CollectionKind, somFunction.IsReturnAttributeReftype /*isRefType*/, convertedItemCache, newGlobalItems); if (null != returnType) { // Create the return parameter object, need to set the declaring type explicitly on the return parameter // because we aren't adding it to the members collection returnParameters.Add(new FunctionParameter(EdmConstants.ReturnType, returnType, ParameterMode.ReturnValue)); } else { //Return type was specified but we could not find a type usage return null; } } string functionNamespace; EntitySet[] entitySets = null; if (somFunction.IsFunctionImport) { var somFunctionImport = (Som.FunctionImportElement)somFunction; functionNamespace = somFunctionImport.Container.Name; if (null != somFunctionImport.EntitySet) { EntityContainer entityContainer; Debug.Assert( somFunctionImport.ReturnTypeList == null || somFunctionImport.ReturnTypeList.Count == 1, "EntitySet cannot be specified on a FunctionImport if there are multiple ReturnType children"); Debug.Assert( functionImportEntityContainer != null, "functionImportEntityContainer must be specified during function import conversion"); entityContainer = functionImportEntityContainer; entitySets = new[] { GetEntitySet(somFunctionImport.EntitySet, entityContainer) }; } else if (null != somFunctionImport.ReturnTypeList) { Debug.Assert( functionImportEntityContainer != null, "functionImportEntityContainer must be specified during function import conversion"); var entityContainer = functionImportEntityContainer; entitySets = somFunctionImport.ReturnTypeList .Select( returnType => null != returnType.EntitySet ? GetEntitySet(returnType.EntitySet, functionImportEntityContainer) : null) .ToArray(); } } else { functionNamespace = somFunction.Namespace; } var parameters = new List<FunctionParameter>(); foreach (var somParameter in somFunction.Parameters) { var parameterType = GetFunctionTypeUsage( somFunction is Som.ModelFunction, somFunction, somParameter, providerManifest, areConvertingForProviderManifest, somParameter.Type, somParameter.CollectionKind, somParameter.IsRefType, convertedItemCache, newGlobalItems); if (parameterType == null) { return null; } var parameter = new FunctionParameter( somParameter.Name, parameterType, GetParameterMode(somParameter.ParameterDirection)); AddOtherContent(somParameter, parameter); if (somParameter.Documentation != null) { parameter.Documentation = ConvertToDocumentation(somParameter.Documentation); } parameters.Add(parameter); } var function = new EdmFunction( somFunction.Name, functionNamespace, GetDataSpace(providerManifest), new EdmFunctionPayload { Schema = somFunction.DbSchema, StoreFunctionName = somFunction.StoreFunctionName, CommandText = somFunction.CommandText, EntitySets = entitySets, IsAggregate = somFunction.IsAggregate, IsBuiltIn = somFunction.IsBuiltIn, IsNiladic = somFunction.IsNiladicFunction, IsComposable = somFunction.IsComposable, IsFromProviderManifest = areConvertingForProviderManifest, IsFunctionImport = somFunction.IsFunctionImport, ReturnParameters = returnParameters.ToArray(), Parameters = parameters.ToArray(), ParameterTypeSemantics = somFunction.ParameterTypeSemantics, }); // Add this function to new global items, only if it is not a function import if (!somFunction.IsFunctionImport) { newGlobalItems.Add(somFunction, function); } //Check if we already converted functions since we are loading it from //ssdl we could see functions many times. GlobalItem returnFunction = null; Debug.Assert( !convertedItemCache.ItemCollection.TryGetValue(function.Identity, false, out returnFunction), "Function duplicates must be checked by som"); // Extract the optional Documentation if (somFunction.Documentation != null) { function.Documentation = ConvertToDocumentation(somFunction.Documentation); } AddOtherContent(somFunction, function); return function; }
public TEST(EntityContainer entityContainer) { _entityContainer = entityContainer; }
public RenderGameSystem(EntityContainer entityContainer) : base(entityContainer) { }
/// <summary> /// 获取商品销售单视图 /// </summary> /// <returns></returns> public IEnumerable<GoodsSellNoteVM> GetGoodsSellNote() { GoodsSellNote note = new GoodsSellNote(); Employee emp = new Employee(); CustomerContactInfo cst=new CustomerContactInfo (); OQL joinQ = OQL.From(note) .InnerJoin(emp).On(note.SalesmanID, emp.WorkNumber) .InnerJoin(cst).On(note.CustomerID, cst.CustomerID) .Select(note.NoteID, cst.CustomerName, note.ManchinesNumber, emp.EmployeeName, note.SalesType, note.SellDate) .OrderBy(note.NoteID, "desc") .END; PWMIS.DataProvider.Data.AdoHelper db = PWMIS.DataProvider.Adapter.MyDB.GetDBHelper(); EntityContainer ec = new EntityContainer(joinQ, db); ec.Execute(); //可以使用下面的方式获得各个成员元素列表 //var noteList = ec.Map<GoodsSellNote>().ToList(); //var empList = ec.Map<Employee>().ToList(); //var cstList = ec.Map<CustomerContactInfo>().ToList(); //直接使用下面的方式获得新的视图对象 var result = ec.Map<GoodsSellNoteVM>(e => { e.NoteID = ec.GetItemValue<int>(0); e.CustomerName = ec.GetItemValue<string>(1); e.ManchinesNumber = ec.GetItemValue<string>(2); e.EmployeeName = ec.GetItemValue<string>(3); e.SalesType = ec.GetItemValue<string>(4); e.SellDate = ec.GetItemValue<DateTime>(5); return e; } ); return result; }
/// <summary> /// /// </summary> /// <param name="generator"></param> /// <param name="entityContainer"></param> public EntityContainerEmitter(ClientApiGenerator generator, EntityContainer entityContainer) : base(generator, entityContainer) { }
/// <summary> /// 获取商品销售价格信息 /// </summary> /// <returns></returns> public IEnumerable<GoodsSaleInfoVM> GetGoodsSaleInfo() { GoodsBaseInfo bInfo = new GoodsBaseInfo(); GoodsStock stock = new GoodsStock(); OQL joinQ = OQL.From(bInfo) .Join(stock).On(bInfo.SerialNumber, stock.SerialNumber) .Select(bInfo.GoodsName, bInfo.Manufacturer, bInfo.SerialNumber, stock.GoodsPrice, stock.MakeOnDate, bInfo.CanUserMonth, stock.Stocks, stock.GoodsID) .OrderBy(bInfo.GoodsName, "asc") .END; PWMIS.DataProvider.Data.AdoHelper db = PWMIS.DataProvider.Adapter.MyDB.GetDBHelper(); EntityContainer ec = new EntityContainer(joinQ, db); ec.Execute(); var result = ec.Map<GoodsSaleInfoVM>(e => { e.GoodsName = ec.GetItemValue<string>(0); e.Manufacturer = ec.GetItemValue<string>(1); e.SerialNumber = ec.GetItemValue<string>(2); e.GoodsPrice = ec.GetItemValue<decimal>(3); e.MakeOnDate = ec.GetItemValue<DateTime>(4); e.CanUserMonth = ec.GetItemValue<int>(5); e.Stocks = ec.GetItemValue<int>(6); e.GoodsID = ec.GetItemValue<int>(7); return e; } ); return result; }
public DbFirstMapper(MetadataWorkspace metadataWorkspace, EntityContainer entityContainer) : base(metadataWorkspace, entityContainer) { }
// <summary> // Handler for the EntityContainer element // </summary> // <param name="reader"> xml reader currently positioned at EntityContainer element </param> private void HandleEntityContainerTypeElement(XmlReader reader) { DebugCheck.NotNull(reader); var type = new EntityContainer(this); type.Parse(reader); TryAddContainer(type, true /*doNotAddErrorForEmptyName*/); }
public Row(Game game) { this.game = game; MaxEnemies = 8; Enemies = new EntityContainer<Enemy>(); }
/// <summary> /// Resolves the names to element references. /// </summary> internal override void ResolveTopLevelNames() { if (!_isAlreadyResolved) { base.ResolveTopLevelNames(); SchemaType extendingEntityContainer; // If this entity container extends some other entity container, we should validate the entity container name. if (!String.IsNullOrEmpty(_unresolvedExtendedEntityContainerName)) { if (_unresolvedExtendedEntityContainerName == this.Name) { AddError(ErrorCode.EntityContainerCannotExtendItself, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.EntityContainerCannotExtendItself(this.Name)); } else if (!Schema.SchemaManager.TryResolveType(null, _unresolvedExtendedEntityContainerName, out extendingEntityContainer)) { AddError(ErrorCode.InvalidEntityContainerNameInExtends, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.InvalidEntityContainerNameInExtends(_unresolvedExtendedEntityContainerName)); } else { _entityContainerGettingExtended = (EntityContainer)extendingEntityContainer; // Once you have successfully resolved the entity container, then you should call ResolveNames on the // extending entity containers as well. This is because we will need to look up the chain for resolving // entity set names, since there might be association sets/ function imports that refer to entity sets // belonging in extended entity containers _entityContainerGettingExtended.ResolveTopLevelNames(); } } foreach (SchemaElement element in Members) { element.ResolveTopLevelNames(); } _isAlreadyResolved = true; } }
/// <summary> /// Imports the specified world into the SabreCSG model. /// </summary> /// <param name="model">The model to import into.</param> /// <param name="world">The world to be imported.</param> /// <param name="scale">The scale modifier.</param> public static void Import(Transform rootTransform, MapWorld world) { _conversionScale = 1.0f / _Scale; // create a material searcher to associate materials automatically. MaterialSearcher materialSearcher = new MaterialSearcher(); var mapTransform = CreateGameObjectWithUniqueName(world.mapName, rootTransform); mapTransform.position = Vector3.zero; // Index of entities by trenchbroom id var entitiesById = new Dictionary <int, EntityContainer>(); var layers = new List <EntityContainer>(); for (int e = 0; e < world.Entities.Count; e++) { var entity = world.Entities[e]; //EntityContainer eContainer = null; if (entity.tbId >= 0) { var name = String.IsNullOrEmpty(entity.tbName) ? "Unnamed" : entity.tbName; var t = CreateGameObjectWithUniqueName(name, mapTransform); var eContainer = new EntityContainer(t, entity); entitiesById.Add(entity.tbId, eContainer); if (entity.tbType == "_tb_layer") { layers.Add(eContainer); eContainer.transform.SetParent(null); // unparent until layers are sorted by sort index } } } var defaultLayer = CreateGameObjectWithUniqueName("Default Layer", mapTransform); layers = layers.OrderBy(l => l.entity.tbLayerSortIndex).ToList(); // sort layers by layer sort index foreach (var l in layers) { l.transform.SetParent(mapTransform); // parent layers to map in order } bool valveFormat = world.valveFormat; // iterate through all entities. for (int e = 0; e < world.Entities.Count; e++) { #if UNITY_EDITOR UnityEditor.EditorUtility.DisplayProgressBar("Importing Quake 1 Map", "Converting Quake 1 Entities To Brushes (" + (e + 1) + " / " + world.Entities.Count + ")...", e / (float)world.Entities.Count); #endif MapEntity entity = world.Entities[e]; Transform brushParent = mapTransform; bool isLayer = false; bool isTrigger = false; if (entity.ClassName == "worldspawn") { brushParent = defaultLayer; } else if (entity.tbType == "_tb_layer") { isLayer = true; if (entitiesById.TryGetValue(entity.tbId, out EntityContainer eContainer)) { brushParent = eContainer.transform; } } else if (entity.tbType == "_tb_group") { if (entitiesById.TryGetValue(entity.tbId, out EntityContainer eContainer)) { brushParent = eContainer.transform; } } else { if (entity.ClassName.Contains("trigger")) { isTrigger = true; } brushParent = CreateGameObjectWithUniqueName(entity.ClassName, mapTransform); } if (brushParent != mapTransform && brushParent != defaultLayer) { if (entity.tbGroup > 0) { if (entitiesById.TryGetValue(entity.tbGroup, out EntityContainer eContainer)) { brushParent.SetParent(eContainer.transform); } } else if (entity.tbLayer > 0) { if (entitiesById.TryGetValue(entity.tbLayer, out EntityContainer eContainer)) { brushParent.SetParent(eContainer.transform); } } else if (!isLayer) { brushParent.SetParent(defaultLayer); } } //if(entity.) if (entity.Brushes.Count == 0) { continue; } var model = ChiselModelManager.CreateNewModel(brushParent); // var model = OperationsUtility.CreateModelInstanceInScene(brushParent); var parent = model.transform; if (isTrigger) { //model.Settings = (model.Settings | ModelSettingsFlags.IsTrigger | ModelSettingsFlags.SetColliderConvex | ModelSettingsFlags.DoNotRender); } // iterate through all entity brushes. for (int i = 0; i < entity.Brushes.Count; i++) { MapBrush brush = entity.Brushes[i]; // build a very large cube brush. ChiselBrush go = ChiselComponentFactory.Create <ChiselBrush>(model); go.definition.surfaceDefinition = new ChiselSurfaceDefinition(); go.definition.surfaceDefinition.EnsureSize(6); BrushMesh brushMesh = new BrushMesh(); go.definition.brushOutline = brushMesh; BrushMeshFactory.CreateBox(ref brushMesh, new Vector3(-4096, -4096, -4096), new Vector3(4096, 4096, 4096), in go.definition.surfaceDefinition); // prepare for uv calculations of clip planes after cutting. var planes = new float4[brush.Sides.Count]; var planeSurfaces = new ChiselSurface[brush.Sides.Count]; // compute all the sides of the brush that will be clipped. for (int j = brush.Sides.Count; j-- > 0;) { MapBrushSide side = brush.Sides[j]; // detect excluded polygons. //if (IsExcludedMaterial(side.Material)) //polygon.UserExcludeFromFinal = true; // detect collision-only brushes. //if (IsInvisibleMaterial(side.Material)) //pr.IsVisible = false; // find the material in the unity project automatically. Material material; string materialName = side.Material.Replace("*", "#"); material = materialSearcher.FindMaterial(new string[] { materialName }); if (material == null) { material = ChiselMaterialManager.DefaultFloorMaterial; } // create chisel surface for the clip. ChiselSurface surface = new ChiselSurface(); surface.brushMaterial = ChiselBrushMaterial.CreateInstance(material, ChiselMaterialManager.DefaultPhysicsMaterial); surface.surfaceDescription = SurfaceDescription.Default; // detect collision-only polygons. if (IsInvisibleMaterial(side.Material)) { surface.brushMaterial.LayerUsage &= ~LayerUsageFlags.RenderReceiveCastShadows; } // detect excluded polygons. if (IsExcludedMaterial(side.Material)) { surface.brushMaterial.LayerUsage &= LayerUsageFlags.CastShadows; surface.brushMaterial.LayerUsage |= LayerUsageFlags.Collidable; } // calculate the clipping planes. Plane clip = new Plane(go.transform.InverseTransformPoint(new Vector3(side.Plane.P1.X, side.Plane.P1.Z, side.Plane.P1.Y) * _conversionScale), go.transform.InverseTransformPoint(new Vector3(side.Plane.P2.X, side.Plane.P2.Z, side.Plane.P2.Y) * _conversionScale), go.transform.InverseTransformPoint(new Vector3(side.Plane.P3.X, side.Plane.P3.Z, side.Plane.P3.Y) * _conversionScale)); planes[j] = new float4(clip.normal, clip.distance); planeSurfaces[j] = surface; } // cut all the clipping planes out of the brush in one go. brushMesh.Cut(planes, planeSurfaces); // now iterate over the planes to calculate UV coordinates. int[] indices = new int[brush.Sides.Count]; for (int k = 0; k < planes.Length; k++) { var plane = planes[k]; int closestIndex = 0; float closestDistance = math.lengthsq(plane - brushMesh.planes[0]); for (int j = 1; j < brushMesh.planes.Length; j++) { float testDistance = math.lengthsq(plane - brushMesh.planes[j]); if (testDistance < closestDistance) { closestIndex = j; closestDistance = testDistance; } } indices[k] = closestIndex; } for (int j = 0; j < indices.Length; j++) { brushMesh.planes[indices[j]] = planes[j]; } for (int j = brush.Sides.Count; j-- > 0;) { MapBrushSide side = brush.Sides[j]; var surface = brushMesh.polygons[indices[j]].surface; var material = surface.brushMaterial.RenderMaterial; // calculate the texture coordinates. int w = 256; int h = 256; if (material.mainTexture != null) { w = material.mainTexture.width; h = material.mainTexture.height; } var clip = new Plane(planes[j].xyz, planes[j].w); if (world.valveFormat) { var uAxis = new VmfAxis(side.t1, side.Offset.X, side.Scale.X); var vAxis = new VmfAxis(side.t2, side.Offset.Y, side.Scale.Y); CalculateTextureCoordinates(go, surface, clip, w, h, uAxis, vAxis); } else { if (GetTextureAxises(clip, out MapVector3 t1, out MapVector3 t2)) { var uAxis = new VmfAxis(t1, side.Offset.X, side.Scale.X); var vAxis = new VmfAxis(t2, side.Offset.Y, side.Scale.Y); CalculateTextureCoordinates(go, surface, clip, w, h, uAxis, vAxis); } } } try { // finalize the brush by snapping planes and centering the pivot point. go.transform.position += brushMesh.CenterAndSnapPlanes(); } catch { // Brush failed, destroy brush GameObject.DestroyImmediate(go); } } } #if UNITY_EDITOR UnityEditor.EditorUtility.ClearProgressBar(); #endif }
public void SetUp() { _Container = new EntityContainer(new ISystem[0], Substitute.For <ILogger>()); _Entity = _Container.CreateEntity(); }
private bool FindContainer(IEntity entity, out EntityContainer container) { return(_entitys.TryGetValue(entity, out container)); }
void Awake() { if (ec == null) { var go = GameObject.FindWithTag("EntityContainer"); if (go != null) { ec = go.GetComponent<EntityContainer>(); } } }
/// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="cacheKey">Cache key.</param> public ContextCacheSet(string cacheKey) { _container = CacheFactory.GetOrCreate <T>(); _cacheKey = cacheKey; }
protected override void SaveContainer(EntityContainer container) { logger.LogDebug("Saving Container (In main class) {0}", container.Key.ToString()); contentTypeService.SaveContainer(container); }
/// <summary> /// Change the entity container without doing fixup in the entity set collection /// </summary> internal void ChangeEntityContainerWithoutCollectionFixup(EntityContainer newEntityContainer) { _entityContainer = newEntityContainer; }
public Attempt <OperationResult> SaveContainer(EntityContainer container, int userId = -1) { throw new NotImplementedException(); }
/// <summary> /// Spawn this new into the live world into a specified container /// </summary> /// <param name="spawnTo">the location/container this should spawn into</param> public override void SpawnNewInWorld(IContains spawnTo) { //We can't even try this until we know if the data is there if (DataTemplate<IInanimateData>() == null) throw new InvalidOperationException("Missing backing data store on object spawn event."); var bS = DataTemplate<IInanimateData>(); BirthMark = LiveCache.GetUniqueIdentifier(bS); Keywords = new string[] { bS.Name.ToLower() }; Birthdate = DateTime.Now; if (spawnTo == null) { throw new NotImplementedException("Objects can't spawn to nothing"); } InsideOf = spawnTo; spawnTo.MoveInto<IInanimate>(this); Contents = new EntityContainer<IInanimate>(); LiveCache.Add(this); }
// <summary> // Constructs an EntityContainerRelationshipSet // </summary> // <param name="parentElement"> Reference to the schema element. </param> public EntityContainerRelationshipSet(EntityContainer parentElement) : base(parentElement) { }
// <summary> // Constructs an EntityContainerEntitySet // </summary> // <param name="parentElement"> Reference to the schema element. </param> public EntityContainerEntitySet(EntityContainer parentElement) : base(parentElement) { }