/***************************************************/ private static Element ToRevitElement(this ModelInstance modelInstance, FamilySymbol familySymbol, RevitSettings settings) { Document doc = familySymbol.Document; if (AdaptiveComponentInstanceUtils.IsAdaptiveFamilySymbol(familySymbol)) { List <IGeometry> pts = (modelInstance.Location as CompositeGeometry)?.Elements; if (pts == null || !pts.All(x => x is BH.oM.Geometry.Point)) { BH.Engine.Reflection.Compute.RecordError($"A family could not be created based on the given ModelInstance because its family type is adaptive, but location was not a collection of points. BHoM_Guid: {modelInstance.BHoM_Guid}"); return(null); } return(Create.AdaptiveComponent(doc, familySymbol, pts.Select(x => ((BH.oM.Geometry.Point)x).ToRevit()).ToList(), settings)); } if (modelInstance.Location is BH.oM.Geometry.Point) { return(Create.FamilyInstance(doc, familySymbol, ((BH.oM.Geometry.Point)modelInstance.Location).ToRevit(), modelInstance.Orientation.ToRevit(), doc.GetElement(new ElementId(modelInstance.HostId)), settings)); } else if (modelInstance.Location is ICurve) { return(Create.FamilyInstance(doc, familySymbol, ((ICurve)modelInstance.Location).IToRevit(), doc.GetElement(new ElementId(modelInstance.HostId)), settings)); } else { BH.Engine.Reflection.Compute.RecordError($"A family could not be created based on the given ModelInstance because its location was neither a point nor a curve. BHoM_Guid: {modelInstance.BHoM_Guid}"); return(null); } }
private static AxisAlignedBoundingBox GetEnclosingBoundingBox(ModelInstance modelInstance) { var boundingBox = default(AxisAlignedBoundingBox); var first = true; foreach (var subObject in modelInstance.Model.SubObjects) { var transformedBoundingBox = AxisAlignedBoundingBox.Transform(subObject.RenderObject.BoundingBox, modelInstance.ModelBoneInstances[subObject.Bone.Index].Matrix); if (first) { boundingBox = transformedBoundingBox; first = false; } else { boundingBox = AxisAlignedBoundingBox.CreateMerged( boundingBox, transformedBoundingBox); } } return(boundingBox); }
/// <summary> /// Enumerates over the set of instances represented by the current step. /// </summary> /// <param name="instance"></param> /// <returns></returns> public IEnumerable<ModelInstance> GetInstances(ModelInstance instance) { // Exit immediately if the property is not valid for the specified instance if (!DeclaringType.IsInstanceOfType(instance)) throw new ArgumentException("The current property is not valid for the specified instance."); // Return each instance exposed by a list property if (IsList) { ModelInstanceList children = instance.GetList(this); if (children != null) { foreach (ModelInstance child in children) yield return child; } } // Return the instance exposed by a reference property else { ModelInstance child = instance.GetReference(this); if (child != null) yield return child; } }
public void SetUp() { _materialCache = new MaterialCache(); _parentMtl = _materialCache.Add("testmtl1"); _childMtl = _materialCache.Add("testmtl2"); _epicModel = new EpicModel(); _parentCuboid = Cuboid.CreateCuboid(); _parentCuboid.Size = new Vector3(2, 2, 2); _parentCuboid.Rotation = new Vector3(0, 0, -(float)Math.PI / 4.0f); _parentCuboid.MaterialId = _parentMtl.Id; _connector = _parentCuboid.AddAnchor("Connector"); _connector.Position = new Vector3(1, 1, 0); _childCuboid = Cuboid.CreateCuboid(); _childCuboid.Position = new Vector3(-1, -1, 0); _childCuboid.Rotation = new Vector3(0, 0, -(float)Math.PI / 2.0f); _childCuboid.MaterialId = _childMtl.Id; _epicModel.ModelParts.Add(_parentCuboid); _childCuboid.Pivot.SetParent(_connector); _compiler = new EpicModelCompiler(_epicModel); _compiledModel = _compiler.Compile(); _modelInstance = new ModelInstance(_compiledModel, _materialCache); _modelInstance.Update(1 / 24.0f); }
internal ConditionTarget(Condition condition, ModelInstance target, params string[] properties) { this.Condition = condition; this.target = new WeakReference(target); this.properties = properties; target.GetExtension<RuleManager>().SetCondition(this); }
/// <summary> /// Enumerates over the set of instances represented by the current step. /// </summary> /// <param name="instance"></param> /// <returns></returns> public IEnumerable<ModelInstance> GetInstances(ModelInstance instance) { // Stop loading if the step is null or represents a value if (Property is ModelValueProperty || !((ModelReferenceProperty)Property).DeclaringType.IsInstanceOfType(instance)) yield break; // Cast the property to the correct type var reference = (ModelReferenceProperty)Property; // Return each instance exposed by a list property if (reference.IsList) { ModelInstanceList children = instance.GetList(reference); if (children != null) { foreach (ModelInstance child in instance.GetList(reference)) { if (Filter == null || Filter.IsInstanceOfType(child)) yield return child; } } } // Return the instance exposed by a reference property else { ModelInstance child = instance.GetReference(reference); if (child != null && (Filter == null || Filter.IsInstanceOfType(child))) yield return child; } }
internal JsonInstance(ModelType type, string id) { this.Type = type; this.Id = id; this.instance = new ModelInstance(this); instanceProperties = new object[Type.Properties.Count]; }
/// <summary> /// Gets the model for the specified root object including all objects on the path. /// </summary> /// <param name="root"></param> /// <returns></returns> public HashSet <ModelInstance> GetInstances(ModelInstance root) { var model = new HashSet <ModelInstance>(); GetInstances(root, FirstSteps, model); return(model); }
protected override void SaveInstance(ModelInstance modelInstance) { if (_entityContext.Save((IJsonEntity)modelInstance.Instance)) { OnSave(modelInstance); } }
internal static void OnBeforeCreateAdapter(Binding binding, ModelInstance source, ModelProperty property) { if (BeforeCreateAdapter != null) { BeforeCreateAdapter(binding, new CreateAdapterEventArgs(binding, source, property)); } }
/// <summary> /// Notify path subscribers that the path has changed. /// </summary> /// <param name="instance"></param> internal void Notify(ModelInstance instance) { if (change != null) { change(this, new ModelPathChangeEvent(instance, this)); } }
internal ModelMethodEvent(ModelInstance instance, ModelMethod method, object[] args, string[] include) { this.Instance = instance; this.method = method; this.Include = include; this.args = args; }
internal void LoadRoots(ModelTransaction transaction) { // Exit immediately if roots have already been loaded if (Roots != null) { return; } // Create an array of roots to be loaded Roots = new ModelInstance[Ids == null ? 0 : Ids.Length]; // Get the root instances for (int i = 0; i < Roots.Length; i++) { // Create the root instance Roots[i] = transaction == null?From.Create(Ids[i]) : transaction.GetInstance(From, Ids[i]); } // Access a property to force the instance to initialize. Do a seperate pass so batched loading will work. for (int i = 0; i < Roots.Length; i++) { var initProp = Roots[i].Type.Properties.FirstOrDefault(p => p is ModelValueProperty) ?? Roots[i].Type.Properties.FirstOrDefault(p => p is ModelReferenceProperty); if (initProp == null) { throw new Exception(string.Format("Type \"{0}\" cannot be forced to initialize because it has no properties.", Roots[i].Type.Name)); } Roots[i].OnPropertyGet(initProp); } }
public override void Bind(Entity entity, Main main, bool creating = false) { entity.CannotSuspend = true; Transform transform = entity.GetOrCreate <Transform>("Transform"); PhysicsBlock physics = entity.GetOrCreate <PhysicsBlock>("Physics"); ModelInstance model = entity.GetOrCreate <ModelInstance>("Model"); physics.Add(new TwoWayBinding <Matrix>(transform.Matrix, physics.Transform)); Property <Vector3> scale = new Property <Vector3> { Value = new Vector3(0.5f) }; model.Add(new Binding <Matrix>(model.Transform, () => Matrix.CreateScale(scale) * transform.Matrix, scale, transform.Matrix)); entity.Add("Fade", new Animation ( new Animation.Delay(5.0f), new Animation.Vector3MoveTo(scale, Vector3.Zero, 1.0f), new Animation.Execute(entity.Delete) )); this.SetMain(entity, main); PhysicsBlock.CancelPlayerCollisions(physics); }
public virtual void SaveTest() { ModelInstance userInstance = null; ModelSaveEvent saveEvent = null; // Start a transaction to track identity changes that occur new ModelTransaction().Record(() => { // Create a new user var user = CreateNewUser(); // Get the model instance for the new user userInstance = ModelContext.Current.GetModelType(user).GetModelInstance(user); // Set the username for the new user user.UserName = "******"; // Ensure that the model instance is new Assert.IsTrue(userInstance.IsNew, "Newly created instance was not marked as new."); // Save the new user instance saveEvent = Perform <ModelSaveEvent>(() => userInstance.Save()).FirstOrDefault(); }); // Ensure that the model instance has been saved correctly Assert.IsFalse(userInstance.IsNew, "New instance was not saved."); Assert.IsTrue(saveEvent != null && saveEvent.Instance == userInstance && saveEvent.Added.Count() == 1, "The save event was not correctly raised during a save operation."); }
public bool SetValue(ModelInstance root, object value, Func <ModelInstance, ModelReferenceProperty, int, bool> whenNull, Action <ModelInstance, ModelReferenceProperty, int, ModelInstance> whenNotNull) { IModelPropertySource sourceInstance = GetSource(root, whenNull, whenNotNull); sourceInstance[SourceProperty] = value; return(true); }
/// <summary> /// Determines whether the value of the property along the source path has a value or not. /// </summary> /// <param name="root"></param> /// <returns>True if the source path has an assigned value, otherwise false.</returns> /// <remarks> /// If any value along the source path is null, false will be returned. /// If the source property is a list, false will be returned if the list is empty. /// </remarks> public bool HasValue(ModelInstance root) { // Get the source IModelPropertySource source = GetSource(root); // Return false if the source is null if (source == null) { return(false); } // Get the property off of the source to evaluate ModelProperty property = source.Properties[SourceProperty]; // If the property is a list, determine if the list has items if (property is ModelReferenceProperty && property.IsList) { return(source.GetList((ModelReferenceProperty)property).Count > 0); } // Otherwise, just determine if the property has an assigned value else { return(source[property] != null); } }
internal W3dFloorDraw(W3dFloorDrawModuleData moduleData, GameContext context, GameObject gameObject) { _gameObject = gameObject; _gameContext = context; _moduleData = moduleData; _modelInstance = AddDisposable(_moduleData.Model.Value.CreateInstance(_gameContext.AssetLoadContext)); }
public override void Bind(Entity entity, Main main, bool creating = false) { entity.CannotSuspend = true; ModelInstance model = entity.GetOrCreate <ModelInstance>("Model"); ImplodeBlock implodeBlock = entity.GetOrCreate <ImplodeBlock>("ImplodeBlock"); model.Add(new Binding <Matrix>(model.Transform, implodeBlock.Transform)); implodeBlock.Add(new CommandBinding(implodeBlock.Delete, entity.Delete)); this.SetMain(entity, main); IBinding offsetBinding = null; model.Add(new NotifyBinding(delegate() { if (offsetBinding != null) { model.Remove(offsetBinding); } offsetBinding = new Binding <Vector3>(model.GetVector3Parameter("Offset"), implodeBlock.Offset); model.Add(offsetBinding); }, model.FullInstanceKey)); if (implodeBlock.StateId != Voxel.t.Empty) { Voxel.States.All[implodeBlock.StateId].ApplyToEffectBlock(model); } }
/// <summary> /// Passed as a delegate to List.Sort, to sort transparent instances by view-space depth /// </summary> private int CompareByDepth(ModelInstance a, ModelInstance b) { float aDepth = -Vector3.Transform(a.Position, camera.ViewMatrix).Z; float bDepth = -Vector3.Transform(b.Position, camera.ViewMatrix).Z; return((int)Math.Sign(aDepth - bDepth)); }
public void SetModelName(string modelName) { var model = _gameContext.AssetLoadContext.AssetStore.Models.GetByName(modelName); _modelInstance = AddDisposable(model.CreateInstance(_gameContext.AssetLoadContext)); _modelInstance.Update(TimeInterval.Zero); }
public ModelView(DiagnosticViewContext context, Model model) : base(context) { _modelInstance = AddDisposable(model.CreateInstance(context.Game.AssetStore.LoadContext)); _modelInstance.Update(TimeInterval.Zero); var enclosingBoundingBox = GetEnclosingBoundingBox(_modelInstance); _renderedView = AddDisposable(new RenderedView( context, enclosingBoundingBox.GetCenter(), Vector3.Distance(enclosingBoundingBox.Min, enclosingBoundingBox.Max))); void OnBuildingRenderList(object sender, BuildingRenderListEventArgs e) { _modelInstance.SetWorldMatrix(Matrix4x4.Identity); _modelInstance.BuildRenderList( e.RenderList, e.Camera, true, new MeshShaderResources.RenderItemConstantsPS { HouseColor = Vector3.One, Opacity = 1.0f }); } _renderedView.RenderPipeline.BuildingRenderList += OnBuildingRenderList; AddDisposeAction(() => _renderedView.RenderPipeline.BuildingRenderList -= OnBuildingRenderList); }
private static BoundingBox GetEnclosingBoundingBox(ModelInstance modelInstance) { var boundingBox = default(BoundingBox); var first = true; foreach (var mesh in modelInstance.Model.Meshes) { var transformedBoundingBox = mesh.BoundingBox.Transform( modelInstance.ModelBoneInstances[mesh.ParentBone.Index].Matrix); if (first) { boundingBox = transformedBoundingBox; first = false; } else { boundingBox = BoundingBox.CreateMerged( boundingBox, transformedBoundingBox); } } return(boundingBox); }
/// <summary> /// Initializes null list properties when updated via a call to <see cref="ModelInstanceList.Add"/> or <see cref="ModelInstanceList.Update"/>. /// </summary> /// <param name="instance"></param> /// <param name="property"></param> /// <returns></returns> protected override void InitializeList(ModelInstance instance, ModelReferenceProperty property) { if (property is ReflectionReferenceProperty) { // Ensure the property is a writable BusinessObjectList property var propertyInfo = ((ReflectionReferenceProperty)property).PropertyInfo; var listType = propertyInfo.PropertyType; if (!listType.IsGenericType || listType.GetGenericTypeDefinition() != typeof(ICollection <>)) { throw new NotSupportedException("List initialization is only supported for lists of type ICollection<T>."); } if (!propertyInfo.CanWrite) { throw new NotSupportedException("List initialization is only supported for writeable properties."); } var itemType = ((ReflectionModelType)property.PropertyType).UnderlyingType; // Create the list var list = typeof(ObservableCollection <>).MakeGenericType(itemType).GetConstructor(Type.EmptyTypes).Invoke(null); // Assign the list to the property propertyInfo.SetValue(instance.Instance, list, null); } else { throw new NotSupportedException("List initialization is only supported for reflection-based properties."); } }
internal Meta(ScriptEngine engine, ModelInstance instance) : base(engine, engine.Object.InstancePrototype) { this.PopulateFunctions(); this.instance = instance; this.typeWrapper = new TypeWrapper(engine, instance.Type); }
internal JsonInstance(ModelType type, string id) { this.Type = type; this.Id = id; this.instance = new ModelInstance(this); instanceProperties = new object[Type.Properties.Count]; }
/// <summary> /// Returns true if the step has references all the way to the root. /// </summary> /// <param name="instance">Instance to check</param> /// <param name="checkIfPropertyAccessed">Check if property has been accessed on the instance.</param> /// <returns></returns> internal bool IsReferencedToRoot(ModelInstance instance, bool checkIfPropertyAccessed) { // Exit immediately if the instance is not valid for the current step filter if (Filter != null && !Filter.IsInstanceOfType(instance)) { return(false); } // Check if the current property has been accessed on the instance if (checkIfPropertyAccessed && !instance.HasBeenAccessed(Property)) { return(false); } //if there's no previous steps then the step directly applies to the instance if (PreviousStep == null) { return(true); } //unless the previous step has references the step is not relevant to the instance. foreach (ModelReference parentReference in instance.GetInReferences((ModelReferenceProperty)PreviousStep.Property)) { if (PreviousStep.IsReferencedToRoot(parentReference.In, false)) { return(true); } } return(false); }
protected override void OnInit() { var direction = Tile.GetDirection(Level, Location); var behaviour = (TelepadTileBehaviour)Tile.Behaviour; var model = behaviour.GetModel(Level, Location); var transform = Tile.BuildTransform(Location, direction); if (model != null) { m_model = new ModelInstance(model, transform); } Level.Telepads.AddTelepad(behaviour.Colour, Location); if (behaviour.Animation != null) { if (m_model != null) { m_model.Animation = LuaAnimation.Get(behaviour.Animation); m_model.AnimTime = Level.TimeMachine.RealTime; } } if (behaviour.PFX != null) { if (m_model != null) { m_emitter = Level.Particles.Create(ParticleStyle.Get(behaviour.PFX), false, true); m_emitter.Transform = transform; } } }
public AnimationInstance(ModelInstance modelInstance, W3DAnimation animation, AnimationMode mode, AnimationFlags flags) { _animation = animation; _mode = mode; _flags = flags; _boneInstances = modelInstance.ModelBoneInstances; _keyframeIndices = new int[animation.Clips.Length]; if (_flags.HasFlag(AnimationFlags.StartFrameFirst) || _flags == AnimationFlags.None) { _currentTimeValue = TimeSpan.Zero; } else if (_flags.HasFlag(AnimationFlags.StartFrameLast)) { _currentTimeValue = _animation.Duration; } else { //TODO: implement other flags //throw new NotImplementedException(); } }
public void TestContextCreationGetInstance() { ModelType outType; IList <string> propertyNames = new List <string>(); propertyNames.Add("Employee Id"); propertyNames.Add("Location"); propertyNames.Add("FirstName"); propertyNames.Add("LastName"); provider.CreateType(propertyNames, out outType, "TypeName"); //load a new instance string employeeId = "1"; IList <string> instanceValues = new List <string>(); instanceValues.Add(employeeId); instanceValues.Add("23"); instanceValues.Add("John"); instanceValues.Add("Doe"); provider.CreateInstance(outType, instanceValues); RowInstance instance = provider.GetInstance(outType, employeeId); //now that the type has been created, try to retrieve the type from the context ModelInstance contextInstance = ModelContext.Current.GetModelInstance(instance); Assert.AreEqual(instance["_Employee_Id"], contextInstance["_Employee_Id"]); }
internal ConditionTarget(Condition condition, ModelInstance target, params string[] properties) { this.Condition = condition; this.target = new WeakReference(target); this.properties = properties; target.GetExtension <RuleManager>().SetCondition(this); }
public void Render(ModelInstance modelInstance, IEffect effect) { foreach (var meshInstance in modelInstance.MeshInstances) { var renderer = GetRendererFor(meshInstance); var dataStream = renderer.LockVertexBuffer(); dataStream.WriteRange(meshInstance.VertexBuffer); renderer.UnlockVertexBuffer(); if (meshInstance.TextureArea == null) { meshInstance.TextureArea = _graphicsContext.GetTexture(meshInstance.TextureName); } if (meshInstance.TextureName != _lastTextureName) { _lastTextureName = meshInstance.TextureName; effect.SetTexture("tex0", meshInstance.TextureArea); effect.CommitChanges(); } renderer.RenderForShader(PrimitiveType.TriangleList, 0, meshInstance.TriangleCount); } }
internal W3dTreeDraw(W3dTreeDrawModuleData moduleData, GameContext context) { _gameContext = context; _moduleData = moduleData; _modelInstance = AddDisposable(_moduleData.Model.Value.CreateInstance(_gameContext.AssetLoadContext)); //TODO: overwrite texture somehow & take care of other fields }
/***************************************************/ private static Element ToRevitElement(this ModelInstance modelInstance, WallType wallType, RevitSettings settings) { if (wallType == null || modelInstance == null) { return(null); } if (!(modelInstance.Location is ICurve)) { Compute.InvalidFamilyPlacementTypeError(modelInstance, wallType); return(null); } Document document = wallType.Document; ICurve curve = (ICurve)modelInstance.Location; Level level = document.LevelBelow(curve, settings); if (level == null) { return(null); } Curve revitCurve = curve.IToRevit(); return(Wall.Create(document, revitCurve, level.Id, false)); }
private bool worldMatrixDirty = true; // set to true if worldMatrix is no longer valid, see 'UpdateWorldMatrix()' //create the actor public Actor(ContentRegister content, UpdateManager updateManager, MaterialLightCollection lights, float groundRadius) { this.groundRadius = groundRadius; model = new ModelInstance(); model.LightCollection = lights; //force the model to render using spherical harmonic lighting //this will significantly improve performance on some hardware when GPU limited model.ShaderProvider = new Xen.Ex.Graphics.Provider.LightingDisplayShaderProvider(LightingDisplayModel.ForceSphericalHarmonic, model.ShaderProvider); //random starting position position = GetRandomPosition(); //initially target the current position //the 'move to next target' timer will wind down and then the actor will move target = position; //randomize a bit lookAngle = (float)random.NextDouble() * MathHelper.TwoPi; moveSpeed = (float)random.NextDouble() * 0.9f + 0.1f; content.Add(this); updateManager.Add(this); InitaliseAnimations(updateManager); }
/// <summary> /// /// </summary> /// <param name="fxPlayback"></param> public void UpdateRenderState(FXPlayback fxPlayback, ModelManager modelManager) { if (sfxDirty) { sfxDirty = false; FXInstance?.Kill(); FXInstance = null; if (sfx > 0) { var fxe = new FXEvent(sfx, ID, Position, LinearVelocity, Rotation); FXInstance = fxPlayback.RunFX(fxe, true); } } if (modelDirty) { modelDirty = false; ModelInstance?.Kill(); ModelInstance = null; if (model > 0) { ModelInstance = modelManager.AddModel(model, this); } } }
/// <summary> /// Calls tool use and fires use event from current entity state /// </summary> public IToolImpact ToolUse(ITool tool) { var arg = EntityUseEventArgs.FromState(this); arg.Tool = tool; if (tool != null) { using (new PerfLimit("Tool use logic " + tool.Name)) arg.Impact = tool.Use(this); } else { arg.Impact = new ToolImpact { Message = "Null tool" }; } OnUse(arg); if (ModelInstance != null) { ModelInstance.TryPlay("Use"); } return(arg.Impact); }
protected override bool ConditionApplies(ModelInstance root) { var value = root[Property] as string; if (String.IsNullOrEmpty(value)) return false; return (Maximum > 0 && value.Length > Maximum) || (Minimum > 0 && value.Length < Minimum); }
public ModelListChangeEvent(ModelInstance instance, ModelReferenceProperty property, IEnumerable<ModelInstance> added, IEnumerable<ModelInstance> removed) : base(instance) { this.Property = property; this.Added = added.ToArray(); this.AddedIds = this.Added.Select(i => i.Id).ToArray(); this.Removed = removed.ToArray(); this.RemovedIds = this.Removed.Select(i => i.Id).ToArray(); }
public ModelReferenceChangeEvent(ModelInstance instance, ModelReferenceProperty property, ModelInstance oldValue, ModelInstance newValue) : base(instance) { this.Property = property; this.OldValue = oldValue; this.OldValueId = (oldValue != null) ? oldValue.Id : null; this.NewValue = newValue; this.NewValueId = (newValue != null) ? newValue.Id : null; }
public Skydome(ContentRegister content, Vector3 position, float scale) { model = new ModelInstance(); Matrix.CreateTranslation(ref position, out worldMatrix); Matrix.CreateScale(scale, out scaleMatrix); content.Add(this); }
/// <summary> /// Gets the formatted value of the property for the specified instance. /// </summary> protected internal override string GetFormattedValue(ModelInstance instance, string format, IFormatProvider provider) { if (IsList) return instance.GetList(this).ToString(format ?? Format, provider); else { var reference = instance.GetReference(this); return reference != null ? reference.ToString(format ?? Format, provider) : ""; } }
public void RenderNoTexture(ModelInstance modelInstance) { foreach (var meshInstance in modelInstance.MeshInstances) { var vertexRenderer = GetRendererFor(meshInstance); var dataStream = vertexRenderer.LockVertexBuffer(); dataStream.WriteRange(meshInstance.VertexBuffer); vertexRenderer.UnlockVertexBuffer(); vertexRenderer.RenderForShader(PrimitiveType.TriangleList, 0, meshInstance.TriangleCount); } }
/// <summary> /// create a new actor /// </summary> /// <param name="content"></param> /// <param name="modelfile">model file to be loaded</param> /// <param name="position">position</param> /// <param name="scale_factor">scale</param> public Actor(ContentRegister content,String modelfile, Vector3 position, float scale_factor) { this.scale = scale_factor; this.position = position; Matrix.CreateTranslation(ref position, out this.worldMatrix); Matrix.CreateScale(scale_factor,out this.scaleMatrix); this.filename = modelfile; this.model = new ModelInstance(); content.Add(this); }
public Actor(ContentRegister content) { //A ModelInstance can be created without any content... //However it cannot be used until the content is set model = new ModelInstance(); content.Add(this); //play an animation model.GetAnimationController().PlayLoopingAnimation(3); //This method creates a Cube for each bone in the mesh BuildBoundingBoxGeometry(); }
public ModelValueChangeEvent(ModelInstance instance, ModelValueProperty property, object oldValue, object newValue) : base(instance) { this.Property = property; if (property.AutoConvert) { this.OldValue = oldValue == null ? null : property.Converter.ConvertTo(oldValue, typeof(object)); this.NewValue = newValue == null ? null : property.Converter.ConvertTo(newValue, typeof(object)); } else { this.OldValue = oldValue; this.NewValue = newValue; } }
private void ModelChanged(ModelInstance model) { if (model != null && model.Model != null && model.Model.SkinningData != null) { _worldTransforms = new Matrix4x4[_model.Model.SkinningData.BindPose.Length]; _skinTransforms = new Matrix4x4[_model.Model.SkinningData.BindPose.Length]; var skinning = _model.Model.SkinningData; AnimationHelpers.CalculateWorldTransformsFromBoneTransforms(skinning.SkeletonHierarchy, skinning.BindPose, _worldTransforms); } else { _worldTransforms = null; _skinTransforms = null; } }
public SimpleTerrain(ContentRegister content, Vector3 position, string modelDataName) { this.modelDataName = modelDataName; //Matrix.CreateTranslation(ref position, out this.worldMatrix); this.worldMatrix = Matrix.CreateTranslation(position);// *Matrix.CreateScale(2.0f); // needed for physics //A ModelInstance can be created without any content... //However it cannot be used until the content is set this.model = new ModelInstance(); this.terrainShader = new Shaders.SimpleTerrain(); PickingDrawer = new LightSourceDrawer(Vector3.Zero, new Xen.Ex.Geometry.Sphere(new Vector3(3), 8, true, false, false), Color.Red); //add to the content register and load textures/etc content.Add(this); }
public override Entity Create(Main main) { Entity result = new Entity(main, "Block"); Transform transform = new Transform(); result.Add("Transform", transform); PhysicsBlock physics = new PhysicsBlock(); result.Add("Physics", physics); Property<string> cue = new Property<string> { Value = "ConcreteRubble" }; result.Add("CollisionSoundCue", cue); ModelInstance model = new ModelInstance(); result.Add("Model", model); model.Scale.Value = new Vector3(0.5f); return result; }
internal void RunPendingPropertyGetRules(ModelInstance instance, Func<ModelProperty, bool> when) { // First run all rules for return values associated with properties that have not yet been accessed foreach (Rule rule in instance.GetRules() .Where(rule => (rule.InvocationTypes & RuleInvocationType.PropertyGet) > 0 && rule.ReturnValues.Select(p => rule.RootType.Properties[p]) .Any(p => when(p) && !instance.HasBeenAccessed(p)))) rule.Invoke(instance, null); // Then run any property get rules that are pending invocation due to changes in the model pendingInvocation.RemoveWhere(rule => { if ((rule.InvocationTypes & RuleInvocationType.PropertyGet) > 0 && rule.ReturnValues.Select(p => rule.RootType.Properties[p]).Any(when)) { rule.Invoke(instance, null); return true; } return false; }); }
public Actor(ContentRegister content, Vector3 position) { //set the world matrix Matrix.CreateTranslation(ref position, out this.worldMatrix); //A ModelInstance can be created without any content... //However it cannot be used until the content is set this.model = new ModelInstance(); //Note: // When a model is drawn, by default it will bind and use a MaterialShader. // This shader uses the material properties stored in the original mesh. // If you don't want to use the MaterialShader, simply set the property // model.ShaderProvider to null. //add to the content register content.Add(this); }
//NEW CODE public Actor(ContentRegister content, MaterialLightCollection lights) { //A ModelInstance can be created without any content... //However it cannot be used until the content is set model = new ModelInstance(); model.LightCollection = lights; //this class is reused by later tutorials, which require lights //get and create the animation controller for this model. animationController = model.GetAnimationController(); //NOTE: Animations cannot be played until the model data has been loaded... content.Add(this); //At this point in this tutorial, the model is now loaded. //get the index of the walk animation //this model has 4 animations, Wave, Jog, Walk and Loiter //The animations are stored in model.ModelData.Animations int animationIndex = animationController.AnimationIndex("Walk"); //begin playing the animation, looping animation = animationController.PlayLoopingAnimation(animationIndex); //as many animations as you want can be played at any one time //to blend between animations, adjust their weighting with: //animation.Weighting = ...; //Combined weightings usually should add up to 1.0 //A weighting of 0 means the animation has no effect, 1 has normal effect. //Values outside the 0-1 range usually produces undesirable results. //Note: //Animations in xen are lossy compressed. //For the model used here, the animation data is reduced from nearly 2mb //down to around 200kb. (The model geometry is less than 300kb) //The amount of compression change can be configured in the content's properties //The 'Animation Compression Tolerance' value is a percentage //The default is .5%. This means the animation will always be within .5% //of the source. Setting this value to 0 will save a lossless animation. }
protected override bool ConditionApplies(ModelInstance root) { // First, get the string value to validate var value = root[Property] as string; if (String.IsNullOrEmpty(value)) return false; // Then get the regular expression to use Regex exp = FormatExpression; if (exp == null) return false; // Indicate that the value is invalid if the regular expression does not match if (!exp.IsMatch(value)) return true; // Reformat if necessary var reformat = ReformatExpression; if (reformat != null) root[Property] = exp.Replace(value, reformat); // Indicate that the value is valid return false; }
public override Entity Create(Main main) { Entity result = new Entity(main, "EffectBlock"); Transform transform = new Transform(); result.Add("Transform", transform); ModelInstance model = new ModelInstance(); result.Add("Model", model); result.Add("Offset", new Property<Vector3> { Editable = false }); result.Add("Lifetime", new Property<float> { Editable = false }); result.Add("TotalLifetime", new Property<float> { Editable = true }); result.Add("StartPosition", new Property<Vector3> { Editable = true }); result.Add("StartOrientation", new Property<Matrix> { Editable = false }); result.Add("TargetMap", new Property<Entity.Handle> { Editable = true }); result.Add("TargetCoord", new Property<Map.Coordinate> { Editable = false }); result.Add("TargetCellStateID", new Property<int> { Editable = true }); result.Add("Scale", new Property<bool> { Editable = true, Value = true }); return result; }
/// <summary> /// Gets the formatted value of the property for the specified instance. /// </summary> protected internal override string GetFormattedValue(ModelInstance instance, string format, IFormatProvider provider) { return FormatValue(GetValue(instance.Instance), format ?? Format, provider); }
/// <summary> /// Gets the formatted value of the property for the specified instance. /// </summary> protected internal override string GetFormattedValue(ModelInstance instance, string format) { return FormatValue(GetValue(instance.Instance), format, null); }
protected override bool ConditionApplies(ModelInstance root) { object value = root[Property]; if (value == null || (value is double && double.IsNaN((double)value))) return false; // min <= value <= max // CompareTo = 0: equal, >0: instance > value if (Minimum != null && Maximum != null) return Minimum.CompareTo(value) > 0 && Maximum.CompareTo(value) < 0; else if (Minimum != null) return Minimum.CompareTo(value) > 0; else if (Maximum != null) return Maximum.CompareTo(value) < 0; else return false; }
protected override bool ConditionApplies(ModelInstance root) { var value = root[Property]; // Exit immediately if the target property has a value if (RequiredValue == null && (value != null && (!(Property is ModelReferenceProperty) || !Property.IsList || root.GetList((ModelReferenceProperty)Property).Count > 0))) return false; // If the required value is specified then the value must equal the required value var requiredValueCondition = RequiredValue == null || !RequiredValue.Equals(value); // Invoke the ModelExpression if it exists if (RequiredExpression != null) { try { return (bool)RequiredExpression.Invoke(root) && requiredValueCondition; } catch { return false; } } // If the value to compare is null, then evaluate whether the compare source has a value else if (CompareValue == null) return (CompareOperator == CompareOperator.Equal ? !compareSource.HasValue(root) : compareSource.HasValue(root)) && requiredValueCondition; // Otherwise, perform a comparison of the compare source relative to the compare value bool? result = CompareRule.Compare(compareSource.GetValue(root), CompareOperator, CompareValue); return result.HasValue && result.Value && requiredValueCondition; }
private ModelStep FirstApplicableStep(ModelInstance instance, ModelStepList steps) { if (instance == null) return steps.FirstOrDefault(); else return steps.Where(s => s.Property.DeclaringType.IsInstanceOfType(instance)).FirstOrDefault(); }
protected override void SaveInstance(ModelInstance modelInstance) { throw new NotImplementedException(); }