Git Product home page Git Product logo

unity-fracture's Introduction

Unity Fracture

preview_github.mp4

FractureThis.cs script takes all meshes in its gameobject and merges them. This global mesh is send to nvblast for fracturing into chunks. The inside part of the chunk has new UVs generated for material to be applied. Original gameobject is hidden and each chunk mesh is converted to gameobject with rigibody. Neighboring chunks are tethered with fixedjoints.

Requirements

How does this work?

  1. Cut the mesh into smaller meshes chunks
  2. Add rigidbody component to each chunk
  3. Connect chunks with fixed joints that break with force

1) Cut the mesh into smaller meshes chunks

I stumbled upon this forum thread https://forum.unity.com/threads/nvidia-blast.472623 where someone figured out how to use Nvidia blast library in the Unity. Feed the library with mesh (must have vertices, triangles, uvs and closed without missing any faces) to this library and receive mesh chunks.

2) Add rigidbody component to each chunk

Convert each mesh chunk into a gameobject with rigidbody. Without anything holding the chunks together they crumble to the ground. Connect the chunks with fixed joints, so they stay in place. Take each chunk and its neighbors (chunks that are in close proximity or in touch) and connect them with fixed joints.

Issue #1 - Structure is wobbly

This is not ideal, the joints are not 100% fixed in place due to how PhysX resolves collisions. There is a big deal of springiness within the joints. The structure ripples when force is applied and acts like a it is made out of jello.

Solution #1 - Freeze rigidbodies

https://answers.unity.com/questions/230995/fixed-joint-not-really-fixed.html advised to freeze the rigidbody. Freezing the rigidbodies makes them stay in place (they drift apart after some time #1) and the rigidbodies still register impact and the joints can be broken.

Issue #2 - Rigidbodies float in the air

Rigidbodies will stay in place even though there is no support under them. They will only resume movement when all joints are broken.

Solution #2 - Introduce anchors

Let's create a graph of connected chunks. Traverse graph each frame and unfreeze chunks disconnected from anchors (kinematic body)

Chunk Graph Anchored chunks are red

unity-fracture's People

Contributors

elasticsea avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unity-fracture's Issues

Using Custom Mesh

Hi,

I am trying to adapt the code to use my own custom mesh with NvBlast. I imported in Unity a mesh made with an external 3D modelling package and then I fed it to the CreateWall object in the scene (basically my own mesh is fed as the cubeMesh in the script). Unfortunately Unity crashes.
On the other hand, if I try to feed one of Unity's built-in meshes (cube, sphere, capsule..), everything works fine.

After debugging for a while I realised that the crash occurs when the Fracture object calls setSourceMesh(nvMesh), so exactly inside the Bake method.

Any idea what is preventing my own meshes from working?

Thanks in advance

Batching

Hi,

In my custom scene, if I generate a wall with 500 chunks (each with a blue outer material and white inner material), I roughly get 2000 batches.
Now, I am still learning about graphics so it may easily be a misunderstanding from my side, but I would expect the number of batches to be 1000, since there are 2 different materials per chunk, thus 2*500 = 1000.

Moreover, since they are sharing the two repeated materials, shouldn't batching actually be much lower, thus actually saving ms?

What rendering concepts am I missing?

Thanks in advance

Event System missing from the test level

If you shoot anything in the level, Unity will raise null ref exception because Event System is missing. After manually adding it to the scene, the sample runs :)

Some meshes do not get fractured

I'm using Unity 2022.2.4f1.
The blend files in the demo are not supported so I exported them as FBX, like the dragon. Unfortunately they do not get fragmented into chunks. What could be the issue?

Android Build Problems

This works really well in the unity editor and with x64 windows builds, however, when I build to android I run into problems.

I used android logcat to pinpoint exactly what was happening. Here is the output from the log file.

image

Essentially the NvBlastExtUnity_x64.dll isn't getting included in the build. Do you have any thoughts on how to fix this?

Any way to remove chunks rather than send chunks flying?

Thank you for publishing this awesome project.

I'm trying to use this to remove chunks instead of blast them away. So, I modified the ChunkNode.cs script to try to Destroy the pieces when they're clicked (added void OnMouseDown, for example) but this caused problems with the script still trying to access Rigidbodies. I also tried to add logic like "if (rb)" instead of running Rigidbody-accessing codeblocks by default.

I'm not that comfortable with C#, honestly, so I was wondering if anyone could take a look and let me know the correct way to modify this script's behavior to simply remove Mouse-clicked chunks, rather than blast them flying away?

My poorly changed code:

using System.Collections.Generic;
using System.Linq;
using Project.Scripts.Utils;
using UnityEngine;

namespace Project.Scripts.Fractures
{
    public class ChunkNode : MonoBehaviour
    {
        public HashSet<ChunkNode> Neighbours = new HashSet<ChunkNode>();
        public ChunkNode[] NeighboursArray = new ChunkNode[0];
        private Dictionary<Joint, ChunkNode> JointToChunk = new Dictionary<Joint, ChunkNode>();
        private Dictionary<ChunkNode, Joint> ChunkToJoint = new Dictionary<ChunkNode, Joint>();
        private Rigidbody rb;
        private Vector3 frozenPos;
        private Quaternion forzenRot;
        private bool frozen;        
        public bool IsStatic => rb.isKinematic;
        
        public Color Color { get; set; } = Color.black;
        public bool HasBrokenLinks { get; private set; }
        
        void OnMouseDown()
        {
            
            Destroy(this.gameObject);
            return;

        }

        private bool Contains(ChunkNode chunkNode)
        {
            return Neighbours.Contains(chunkNode);
        }

        private void FixedUpdate()
        {
             
            // Kinda hacky, but otherwise the chunks slowly drift apart.
            if (frozen)
            {
                transform.position = frozenPos;
                transform.rotation = forzenRot;
            }

            


        }

        public void Setup()
        {
            rb = GetComponent<Rigidbody>();
            Freeze();

            JointToChunk.Clear();
            ChunkToJoint.Clear();
            foreach (var joint in GetComponents<Joint>())
            {
                var chunk = joint.connectedBody.GetOrAddComponent<ChunkNode>();
                JointToChunk[joint] = chunk;
                ChunkToJoint[chunk] = joint;
            }

            foreach (var chunkNode in ChunkToJoint.Keys)
            {
                Neighbours.Add(chunkNode);

                if (chunkNode.Contains(this) == false)
                {
                    chunkNode.Neighbours.Add(this);
                }
            }

            NeighboursArray = Neighbours.ToArray();
        }

        private void OnJointBreak(float breakForce)
        {
            HasBrokenLinks = true;
        }

        public void CleanBrokenLinks()
        {
            var brokenLinks = JointToChunk.Keys.Where(j => j == false).ToList();
            foreach (var link in brokenLinks)
            {
                var body = JointToChunk[link];

                JointToChunk.Remove(link);
                ChunkToJoint.Remove(body);

                body.Remove(this);
                Neighbours.Remove(body);
            }

            NeighboursArray = Neighbours.ToArray();
            HasBrokenLinks = false;
        }

        private void Remove(ChunkNode chunkNode)
        {
            ChunkToJoint.Remove(chunkNode);
            Neighbours.Remove(chunkNode);
            NeighboursArray = Neighbours.ToArray();
        }

        public void Unfreeze()
        {
            frozen = false;
            rb.constraints = RigidbodyConstraints.None;
            rb.useGravity = true;
            rb.gameObject.layer = LayerMask.NameToLayer("Default");
        }

        private void Freeze()
        {
            frozen = true;
            rb.constraints = RigidbodyConstraints.FreezeAll;
            rb.useGravity = false;
            rb.gameObject.layer = LayerMask.NameToLayer("FrozenChunks");
            frozenPos = rb.transform.position;
            forzenRot = rb.transform.rotation;
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = Color;
            Gizmos.DrawSphere(transform.TransformPoint(transform.GetComponent<Rigidbody>().centerOfMass), 0.1f);

            foreach (var joint in JointToChunk.Keys)
            {
                if (joint)
                {
                    if (rb)
                    {
                        var from = transform.TransformPoint(rb.centerOfMass);

                        if (joint.connectedBody)
                        {
                            var to = joint.connectedBody.transform.TransformPoint(joint.connectedBody.centerOfMass);
                            Gizmos.DrawLine(from, to);
                        }
                    }
                    
                    
                    
                }
            }
        }

        private void OnDrawGizmosSelected()
        {
            foreach (var node in Neighbours)
            {
                var mesh = node.GetComponent<MeshFilter>().mesh;
                Gizmos.color = Color.yellow.SetAlpha(.2f);
                Gizmos.DrawMesh(mesh, node.transform.position, node.transform.rotation);
            }
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.