1 //
2 // Copyright (c) 2008-2017 the Urho3D project.
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21 //
22
23 #include <Urho3D/Core/CoreEvents.h>
24 #include <Urho3D/Engine/Engine.h>
25 #include <Urho3D/Graphics/AnimatedModel.h>
26 #include <Urho3D/Graphics/Animation.h>
27 #include <Urho3D/Graphics/AnimationState.h>
28 #include <Urho3D/Graphics/Camera.h>
29 #include <Urho3D/Graphics/DebugRenderer.h>
30 #include <Urho3D/Graphics/Graphics.h>
31 #include <Urho3D/Graphics/Light.h>
32 #include <Urho3D/Graphics/Material.h>
33 #include <Urho3D/Graphics/Octree.h>
34 #include <Urho3D/Graphics/Renderer.h>
35 #include <Urho3D/Graphics/Zone.h>
36 #include <Urho3D/Input/Input.h>
37 #include <Urho3D/Resource/ResourceCache.h>
38 #include <Urho3D/Scene/Scene.h>
39 #include <Urho3D/UI/Font.h>
40 #include <Urho3D/UI/Text.h>
41 #include <Urho3D/UI/UI.h>
42
43 #include "Mover.h"
44 #include "SkeletalAnimation.h"
45
46 #include <Urho3D/DebugNew.h>
47
URHO3D_DEFINE_APPLICATION_MAIN(SkeletalAnimation)48 URHO3D_DEFINE_APPLICATION_MAIN(SkeletalAnimation)
49
50 SkeletalAnimation::SkeletalAnimation(Context* context) :
51 Sample(context),
52 drawDebug_(false)
53 {
54 // Register an object factory for our custom Mover component so that we can create them to scene nodes
55 context->RegisterFactory<Mover>();
56 }
57
Start()58 void SkeletalAnimation::Start()
59 {
60 // Execute base class startup
61 Sample::Start();
62
63 // Create the scene content
64 CreateScene();
65
66 // Create the UI content
67 CreateInstructions();
68
69 // Setup the viewport for displaying the scene
70 SetupViewport();
71
72 // Hook up to the frame update and render post-update events
73 SubscribeToEvents();
74
75 // Set the mouse mode to use in the sample
76 Sample::InitMouseMode(MM_ABSOLUTE);
77 }
78
CreateScene()79 void SkeletalAnimation::CreateScene()
80 {
81 ResourceCache* cache = GetSubsystem<ResourceCache>();
82
83 scene_ = new Scene(context_);
84
85 // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
86 // Also create a DebugRenderer component so that we can draw debug geometry
87 scene_->CreateComponent<Octree>();
88 scene_->CreateComponent<DebugRenderer>();
89
90 // Create scene node & StaticModel component for showing a static plane
91 Node* planeNode = scene_->CreateChild("Plane");
92 planeNode->SetScale(Vector3(50.0f, 1.0f, 50.0f));
93 StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
94 planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
95 planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
96
97 // Create a Zone component for ambient lighting & fog control
98 Node* zoneNode = scene_->CreateChild("Zone");
99 Zone* zone = zoneNode->CreateComponent<Zone>();
100 zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
101 zone->SetAmbientColor(Color(0.5f, 0.5f, 0.5f));
102 zone->SetFogColor(Color(0.4f, 0.5f, 0.8f));
103 zone->SetFogStart(100.0f);
104 zone->SetFogEnd(300.0f);
105
106 // Create a directional light to the world. Enable cascaded shadows on it
107 Node* lightNode = scene_->CreateChild("DirectionalLight");
108 lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
109 Light* light = lightNode->CreateComponent<Light>();
110 light->SetLightType(LIGHT_DIRECTIONAL);
111 light->SetCastShadows(true);
112 light->SetColor(Color(0.5f, 0.5f, 0.5f));
113 light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
114 // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
115 light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
116
117 // Create animated models
118 const unsigned NUM_MODELS = 30;
119 const float MODEL_MOVE_SPEED = 2.0f;
120 const float MODEL_ROTATE_SPEED = 100.0f;
121 const BoundingBox bounds(Vector3(-20.0f, 0.0f, -20.0f), Vector3(20.0f, 0.0f, 20.0f));
122
123 for (unsigned i = 0; i < NUM_MODELS; ++i)
124 {
125 Node* modelNode = scene_->CreateChild("Jill");
126 modelNode->SetPosition(Vector3(Random(40.0f) - 20.0f, 0.0f, Random(40.0f) - 20.0f));
127 modelNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
128
129 AnimatedModel* modelObject = modelNode->CreateComponent<AnimatedModel>();
130 modelObject->SetModel(cache->GetResource<Model>("Models/Kachujin/Kachujin.mdl"));
131 modelObject->SetMaterial(cache->GetResource<Material>("Models/Kachujin/Materials/Kachujin.xml"));
132 modelObject->SetCastShadows(true);
133
134 // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
135 // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
136 // but we need to update the model's position manually in any case
137 Animation* walkAnimation = cache->GetResource<Animation>("Models/Kachujin/Kachujin_Walk.ani");
138
139 AnimationState* state = modelObject->AddAnimationState(walkAnimation);
140 // The state would fail to create (return null) if the animation was not found
141 if (state)
142 {
143 // Enable full blending weight and looping
144 state->SetWeight(1.0f);
145 state->SetLooped(true);
146 state->SetTime(Random(walkAnimation->GetLength()));
147 }
148
149 // Create our custom Mover component that will move & animate the model during each frame's update
150 Mover* mover = modelNode->CreateComponent<Mover>();
151 mover->SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
152 }
153
154 // Create the camera. Limit far clip distance to match the fog
155 cameraNode_ = scene_->CreateChild("Camera");
156 Camera* camera = cameraNode_->CreateComponent<Camera>();
157 camera->SetFarClip(300.0f);
158
159 // Set an initial position for the camera scene node above the plane
160 cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
161 }
162
CreateInstructions()163 void SkeletalAnimation::CreateInstructions()
164 {
165 ResourceCache* cache = GetSubsystem<ResourceCache>();
166 UI* ui = GetSubsystem<UI>();
167
168 // Construct new Text object, set string to display and font to use
169 Text* instructionText = ui->GetRoot()->CreateChild<Text>();
170 instructionText->SetText(
171 "Use WASD keys and mouse/touch to move\n"
172 "Space to toggle debug geometry"
173 );
174 instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
175 // The text has multiple rows. Center them in relation to each other
176 instructionText->SetTextAlignment(HA_CENTER);
177
178 // Position the text relative to the screen center
179 instructionText->SetHorizontalAlignment(HA_CENTER);
180 instructionText->SetVerticalAlignment(VA_CENTER);
181 instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
182 }
183
SetupViewport()184 void SkeletalAnimation::SetupViewport()
185 {
186 Renderer* renderer = GetSubsystem<Renderer>();
187
188 // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
189 SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
190 renderer->SetViewport(0, viewport);
191 }
192
SubscribeToEvents()193 void SkeletalAnimation::SubscribeToEvents()
194 {
195 // Subscribe HandleUpdate() function for processing update events
196 SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(SkeletalAnimation, HandleUpdate));
197
198 // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
199 // done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
200 // rendering during that event
201 SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(SkeletalAnimation, HandlePostRenderUpdate));
202 }
203
MoveCamera(float timeStep)204 void SkeletalAnimation::MoveCamera(float timeStep)
205 {
206 // Do not move if the UI has a focused element (the console)
207 if (GetSubsystem<UI>()->GetFocusElement())
208 return;
209
210 Input* input = GetSubsystem<Input>();
211
212 // Movement speed as world units per second
213 const float MOVE_SPEED = 20.0f;
214 // Mouse sensitivity as degrees per pixel
215 const float MOUSE_SENSITIVITY = 0.1f;
216
217 // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
218 IntVector2 mouseMove = input->GetMouseMove();
219 yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
220 pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
221 pitch_ = Clamp(pitch_, -90.0f, 90.0f);
222
223 // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
224 cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
225
226 // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
227 if (input->GetKeyDown(KEY_W))
228 cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
229 if (input->GetKeyDown(KEY_S))
230 cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
231 if (input->GetKeyDown(KEY_A))
232 cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
233 if (input->GetKeyDown(KEY_D))
234 cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
235
236 // Toggle debug geometry with space
237 if (input->GetKeyPress(KEY_SPACE))
238 drawDebug_ = !drawDebug_;
239 }
240
HandleUpdate(StringHash eventType,VariantMap & eventData)241 void SkeletalAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
242 {
243 using namespace Update;
244
245 // Take the frame time step, which is stored as a float
246 float timeStep = eventData[P_TIMESTEP].GetFloat();
247
248 // Move the camera, scale movement with time step
249 MoveCamera(timeStep);
250 }
251
HandlePostRenderUpdate(StringHash eventType,VariantMap & eventData)252 void SkeletalAnimation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
253 {
254 // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
255 // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
256 // bones properly
257 if (drawDebug_)
258 GetSubsystem<Renderer>()->DrawDebugGeometry(false);
259 }
260