Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Inverse Kinematics
  2. // This sample demonstrates how to use the IK solver to create "grounders" for a walking character on a slope.
  3.  
  4. #include "Scripts/Utilities/Sample.as"
  5.  
  6. Node@ cameraRotateNode_;
  7. Node@ floorNode_;
  8. float floorPitch_ = 0.0f;
  9. float floorRoll_ = 0.0f;
  10. bool drawDebug_ = false;
  11.  
  12. class NPC
  13. {
  14.     void Setup(Scene@ scene)
  15.     {
  16.         // Load Jack animated model
  17.         node_ = scene.CreateChild("Jack");
  18.         node_.rotation = Quaternion(0.0f, 270.0f, 0.0f);
  19.         AnimatedModel@ jack = node_.CreateComponent("AnimatedModel");
  20.         jack.model = cache.GetResource("Model", "Models/Jack.mdl");
  21.         jack.material = cache.GetResource("Material", "Materials/Jack.xml");
  22.         jack.castShadows = true;
  23.  
  24.         // Create animation controller and play walk animation
  25.         jackAnimCtrl_ = node_.CreateComponent("AnimationController");
  26.         jackAnimCtrl_.PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.0f);
  27.  
  28.         // We need to attach two inverse kinematic effectors to Jack's feet to
  29.         // control the grounding.
  30.         Node@ leftFoot  = node_.GetChild("Bip01_L_Foot", true);
  31.         Node@ rightFoot = node_.GetChild("Bip01_R_Foot", true);
  32.         leftEffector_   = leftFoot.CreateComponent("IKEffector");
  33.         rightEffector_  = rightFoot.CreateComponent("IKEffector");
  34.         // Control 2 segments up to the hips
  35.         leftEffector_.chainLength = 2;
  36.         rightEffector_.chainLength = 2;
  37.  
  38.         // For the effectors to work, an IKSolver needs to be attached to one of
  39.         // the parent nodes. Typically, you want to place the solver as close as
  40.         // possible to the effectors for optimal performance. Since in this case
  41.         // we're solving the legs only, we can place the solver at the spine.
  42.         Node@ spine = node_.GetChild("Bip01_Spine", true);
  43.         solver_ = spine.CreateComponent("IKSolver");
  44.  
  45.         // Two-bone solver is more efficient and more stable than FABRIK (but only
  46.         // works for two bones, obviously).
  47.         solver_.algorithm = IKAlgorithm::TWO_BONE;
  48.  
  49.         // Disable auto-solving, which means we can call Solve() manually.
  50.         solver_.SetFeature(IKFeature::AUTO_SOLVE, false);
  51.  
  52.         // Only enable this so the debug draw shows us the pose before solving.
  53.         // This should NOT be enabled for any other reason (it does nothing and is
  54.         // a waste of performance).
  55.         solver_.SetFeature(IKFeature::UPDATE_ORIGINAL_POSE, true);
  56.  
  57.         SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  58.         SubscribeToEvent("SceneDrawableUpdateFinished", "HandleSceneDrawableUpdateFinished");
  59.     }
  60.  
  61.     void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  62.     {
  63.         if (drawDebug_)
  64.             solver_.DrawDebugGeometry(false);
  65.     }
  66.  
  67.     void HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData)
  68.     {
  69.         Vector3 leftFootPosition = leftEffector_.node.worldPosition;
  70.         Vector3 rightFootPosition = rightEffector_.node.worldPosition;
  71.  
  72.         // Cast ray down to position NPC on ground
  73.         PhysicsRaycastResult result = scene_.physicsWorld.RaycastSingle(Ray(node_.position + Vector3(0, 5, 0), Vector3(0, -1, 0)), 10);
  74.         if (result.body !is null)
  75.         {
  76.             node_.position = result.position;
  77.         }
  78.  
  79.         // Cast ray down to get the normal of the underlying surface
  80.         result = scene_.physicsWorld.RaycastSingle(Ray(leftFootPosition + Vector3(0, 1, 0), Vector3(0, -1, 0)), 2);
  81.         if (result.body !is null)
  82.         {
  83.             // Cast again, but this time along the normal. Set the target position
  84.             // to the ray intersection
  85.             result = scene_.physicsWorld.RaycastSingle(Ray(leftFootPosition + result.normal, -result.normal), 2);
  86.             // The foot node has an offset relative to the root node
  87.             float footOffset = leftEffector_.node.worldPosition.y - node_.worldPosition.y;
  88.             leftEffector_.targetPosition = result.position + result.normal * footOffset;
  89.             // Rotate foot according to normal
  90.             leftEffector_.node.Rotate(Quaternion(Vector3(0, 1, 0), result.normal), TS_WORLD);
  91.         }
  92.  
  93.         // Same deal with the right foot
  94.         result = scene_.physicsWorld.RaycastSingle(Ray(rightFootPosition + Vector3(0, 1, 0), Vector3(0, -1, 0)), 2);
  95.         if (result.body !is null)
  96.         {
  97.             result = scene_.physicsWorld.RaycastSingle(Ray(rightFootPosition + result.normal, -result.normal), 2);
  98.             float footOffset = rightEffector_.node.worldPosition.y - node_.worldPosition.y;
  99.             rightEffector_.targetPosition = result.position + result.normal * footOffset;
  100.             rightEffector_.node.Rotate(Quaternion(Vector3(0, 1, 0), result.normal), TS_WORLD);
  101.         }
  102.  
  103.         solver_.Solve();
  104.     }
  105.  
  106.     AnimationController@ jackAnimCtrl_;
  107.     Node@ node_;
  108.     IKEffector@ leftEffector_;
  109.     IKEffector@ rightEffector_;
  110.     IKSolver@ solver_;
  111. }
  112.  
  113. Array<NPC> npcs_;
  114.  
  115. void Start()
  116. {
  117.     cache.autoReloadResources = true;
  118.  
  119.     // Execute the common startup for samples
  120.     SampleStart();
  121.  
  122.     // Create the scene content
  123.     CreateScene();
  124.  
  125.     // Create the UI content
  126.     CreateInstructions();
  127.  
  128.     // Setup the viewport for displaying the scene
  129.     SetupViewport();
  130.  
  131.     // Set the mouse mode to use in the sample
  132.     SampleInitMouseMode(MM_RELATIVE);
  133.  
  134.     // Hook up to the frame update events
  135.     SubscribeToEvents();
  136. }
  137.  
  138. void CreateScene()
  139. {
  140.     scene_ = Scene();
  141.  
  142.     // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  143.     scene_.CreateComponent("Octree");
  144.     scene_.CreateComponent("DebugRenderer");
  145.     scene_.CreateComponent("PhysicsWorld");
  146.  
  147.     // Create scene node & StaticModel component for showing a static plane
  148.     floorNode_ = scene_.CreateChild("Plane");
  149.     floorNode_.scale = Vector3(50.0f, 1.0f, 50.0f);
  150.     StaticModel@ planeObject = floorNode_.CreateComponent("StaticModel");
  151.     planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  152.     planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  153.  
  154.     // Set up collision, we need to raycast to determine foot height
  155.     floorNode_.CreateComponent("RigidBody");
  156.     CollisionShape@ col = floorNode_.CreateComponent("CollisionShape");
  157.     col.SetBox(Vector3(1, 0, 1));
  158.  
  159.     // Create a directional light to the world.
  160.     Node@ lightNode = scene_.CreateChild("DirectionalLight");
  161.     lightNode.direction = Vector3(0.6f, -1.0f, 0.8f); // The direction vector does not need to be normalized
  162.     Light@ light = lightNode.CreateComponent("Light");
  163.     light.lightType = LIGHT_DIRECTIONAL;
  164.     light.castShadows = true;
  165.     light.shadowBias = BiasParameters(0.00005f, 0.5f);
  166.     // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  167.     light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  168.  
  169.     npcs_.Resize(25);
  170.     for (int x = 0; x < 5; x++)
  171.     {
  172.         for (int y = 0; y < 5; y++)
  173.         {
  174.             npcs_[x*5+y].Setup(scene_);
  175.             npcs_[x*5+y].node_.position = Vector3((x-2), 0, (y-2));
  176.         }
  177.     }
  178.  
  179.     // Create the camera.
  180.     cameraRotateNode_ = scene_.CreateChild("CameraRotate");
  181.     cameraNode = cameraRotateNode_.CreateChild("Camera");
  182.     cameraNode.CreateComponent("Camera");
  183.  
  184.     // Set an initial position for the camera scene node above the plane
  185.     cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
  186.     cameraRotateNode_.position = Vector3(0.0f, 0.4f, 0.0f);
  187.     pitch = 20.0f;
  188.     yaw = 50.0f;
  189. }
  190.  
  191. void CreateInstructions()
  192. {
  193.     // Construct new Text object, set string to display and font to use
  194.     Text@ instructionText = ui.root.CreateChild("Text");
  195.     instructionText.text = "Left-Click and drag to look around\nRight-Click and drag to change incline\nPress space to reset floor\nPress D to draw debug geometry";
  196.     instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  197.  
  198.     // Position the text relative to the screen center
  199.     instructionText.horizontalAlignment = HA_CENTER;
  200.     instructionText.verticalAlignment = VA_CENTER;
  201.     instructionText.SetPosition(0, ui.root.height / 4);
  202. }
  203.  
  204. void SetupViewport()
  205. {
  206.     // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
  207.     // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  208.     // use, but now we just use full screen and default render path configured in the engine command line options
  209.     Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  210.     renderer.viewports[0] = viewport;
  211. }
  212.  
  213. void UpdateCameraAndFloor(float timeStep)
  214. {
  215.     // Do not move if the UI has a focused element (the console)
  216.     if (ui.focusElement !is null)
  217.         return;
  218.  
  219.     // Mouse sensitivity as degrees per pixel
  220.     const float MOUSE_SENSITIVITY = 0.1f;
  221.  
  222.     // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  223.     if (input.mouseButtonDown[MOUSEB_LEFT])
  224.     {
  225.         IntVector2 mouseMove = input.mouseMove;
  226.         yaw += MOUSE_SENSITIVITY * mouseMove.x;
  227.         pitch += MOUSE_SENSITIVITY * mouseMove.y;
  228.         pitch = Clamp(pitch, -90.0f, 90.0f);
  229.     }
  230.  
  231.     if (input.mouseButtonDown[MOUSEB_RIGHT])
  232.     {
  233.         IntVector2 mouseMoveInt = input.mouseMove;
  234.         Vector2 mouseMove = Matrix2(
  235.             -Cos(yaw), Sin(yaw),
  236.             Sin(yaw),  Cos(yaw)
  237.         ) * Vector2(mouseMoveInt.y, -mouseMoveInt.x);
  238.         floorPitch_ += MOUSE_SENSITIVITY * mouseMove.x;
  239.         floorPitch_ = Clamp(floorPitch_, -90.0f, 90.0f);
  240.         floorRoll_ += MOUSE_SENSITIVITY * mouseMove.y;
  241.     }
  242.  
  243.     if (input.keyPress[KEY_SPACE])
  244.     {
  245.         floorPitch_ = 0.0f;
  246.         floorRoll_ = 0.0f;
  247.     }
  248.  
  249.     if (input.keyPress[KEY_D])
  250.     {
  251.         drawDebug_ = !drawDebug_;
  252.     }
  253.  
  254.     // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  255.     cameraRotateNode_.rotation = Quaternion(pitch, yaw, 0.0f);
  256.     floorNode_.rotation = Quaternion(floorPitch_, 0.0f, floorRoll_);
  257. }
  258.  
  259. void SubscribeToEvents()
  260. {
  261.     // Subscribe HandleUpdate() function for processing update events
  262.     SubscribeToEvent("Update", "HandleUpdate");
  263.     SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  264.     SubscribeToEvent("SceneDrawableUpdateFinished", "HandleSceneDrawableUpdateFinished");
  265. }
  266.  
  267. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  268. {
  269.     // Take the frame time step, which is stored as a float
  270.     float timeStep = eventData["TimeStep"].GetFloat();
  271.  
  272.     // Move the camera, scale movement with time step
  273.     UpdateCameraAndFloor(timeStep);
  274. }
  275.  
  276. // Create XML patch instructions for screen joystick layout specific to this sample app
  277. String patchInstructions = "";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement