| 1 | // This file is part of Dust Racing 2D. |
| 2 | // Copyright (C) 2017 Jussi Lind <[email protected]> |
| 3 | // |
| 4 | // Dust Racing 2D is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // Dust Racing 2D is distributed in the hope that it will be useful, |
| 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | // GNU General Public License for more details. |
| 12 | // |
| 13 | // You should have received a copy of the GNU General Public License |
| 14 | // along with Dust Racing 2D. If not, see <http://www.gnu.org/licenses/>. |
| 15 | |
| 16 | #include "tree.hpp" |
| 17 | |
| 18 | #include <MCCircleShape> |
| 19 | #include <MCPhysicsComponent> |
| 20 | #include <MCRandom> |
| 21 | #include <MCShape> |
| 22 | #include <MCShapeView> |
| 23 | #include <MCSurface> |
| 24 | |
| 25 | static const float treeBodyRadius = 8; |
| 26 | |
| 27 | Tree::Tree(MCSurfacePtr surface, float r0, float r1, float treeHeight, size_t branches) |
| 28 | : MCObject(std::make_shared<MCCircleShape>(nullptr, treeBodyRadius), "tree") |
| 29 | { |
| 30 | physicsComponent().setMass(1, true); // Stationary |
| 31 | physicsComponent().setRestitution(0.25f); |
| 32 | |
| 33 | setIsPhysicsObject(true); |
| 34 | |
| 35 | shape()->setRadius(treeBodyRadius); |
| 36 | |
| 37 | const float branchHeight = treeHeight / branches; |
| 38 | for (size_t i = 0; i < branches; i++) |
| 39 | { |
| 40 | const auto branch = std::make_shared<MCObject>(surface, i == 0 ? "treeRoot" : "treeBranch"); |
| 41 | |
| 42 | if (i == 0) |
| 43 | { |
| 44 | branch->shape()->view()->setHasShadow(true); |
| 45 | branch->shape()->view()->setHandle("branchShadowEnabled"); // Different handle for the only surface with shadow |
| 46 | branch->setIsPhysicsObject(false); |
| 47 | addChildObject(branch, MCVector3dF(0, 0, branchHeight) * (i + 1)); |
| 48 | } |
| 49 | else |
| 50 | { |
| 51 | branch->shape()->view()->setHasShadow(false); |
| 52 | branch->setIsPhysicsObject(false); |
| 53 | const auto offset = MCRandom::randomVector2d() * 5; |
| 54 | addChildObject(branch, MCVector3dF(0, 0, branchHeight) * (i + 1) + MCVector3dF(offset), MCRandom::getValue() * 360); |
| 55 | } |
| 56 | |
| 57 | const float scale = r0 - (r0 - r1) / branches * i; |
| 58 | branch->shape()->view()->setScale({ scale, scale, 1.0f }); |
| 59 | } |
| 60 | } |