├── .gitignore
├── .idea
├── .gitignore
├── compiler.xml
├── gradle.xml
├── jarRepositories.xml
├── misc.xml
└── vcs.xml
├── LICENSE
├── README.md
├── README_EN.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── funny
│ │ └── compose
│ │ └── physicslayout
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── funny
│ │ │ └── compose
│ │ │ └── physicslayout
│ │ │ ├── MainActivity.kt
│ │ │ └── ui
│ │ │ ├── RandomColorBox.kt
│ │ │ └── theme
│ │ │ ├── Color.kt
│ │ │ ├── Shape.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── bg_avatar.jpg
│ │ └── ic_launcher_background.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ ├── backup_rules.xml
│ │ └── data_extraction_rules.xml
│ └── test
│ └── java
│ └── com
│ └── funny
│ └── compose
│ └── physicslayout
│ └── ExampleUnitTest.kt
├── build.gradle
├── demo.apk
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── physics
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
├── repos
│ └── releases
│ │ └── com
│ │ └── funny
│ │ └── compose
│ │ └── physics-layout
│ │ ├── 1.0.0
│ │ ├── physics-layout-1.0.0.aar
│ │ ├── physics-layout-1.0.0.aar.md5
│ │ ├── physics-layout-1.0.0.aar.sha1
│ │ ├── physics-layout-1.0.0.aar.sha256
│ │ ├── physics-layout-1.0.0.aar.sha512
│ │ ├── physics-layout-1.0.0.module
│ │ ├── physics-layout-1.0.0.module.md5
│ │ ├── physics-layout-1.0.0.module.sha1
│ │ ├── physics-layout-1.0.0.module.sha256
│ │ ├── physics-layout-1.0.0.module.sha512
│ │ ├── physics-layout-1.0.0.pom
│ │ ├── physics-layout-1.0.0.pom.md5
│ │ ├── physics-layout-1.0.0.pom.sha1
│ │ ├── physics-layout-1.0.0.pom.sha256
│ │ └── physics-layout-1.0.0.pom.sha512
│ │ ├── maven-metadata.xml
│ │ ├── maven-metadata.xml.md5
│ │ ├── maven-metadata.xml.sha1
│ │ ├── maven-metadata.xml.sha256
│ │ └── maven-metadata.xml.sha512
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── funny
│ │ └── compose
│ │ └── physics
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── funny
│ │ └── compose
│ │ └── physics
│ │ ├── Bound.kt
│ │ ├── LayoutRecomposeTest.kt
│ │ ├── Physics.kt
│ │ ├── PhysicsConfig.kt
│ │ ├── PhysicsLayout.kt
│ │ ├── PhysicsLayoutState.kt
│ │ └── PhysicsParentData.kt
│ └── test
│ └── java
│ └── com
│ └── funny
│ └── compose
│ └── physics
│ └── ExampleUnitTest.kt
├── screen_shot.gif
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 FunnySaltyFish
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Jetpack Compose 自定义布局+物理引擎 = ?
2 | [](https://jitpack.io/#FunnySaltyFish/JetpackComposePhysicsLayout)
3 |
4 | [English](README_EN.md)
5 |
6 | 本库基于`Compose`自定义布局技术 + `JBox2d` 实现了物理引擎布局。其内部`Composable`会由物理引擎不断运动
7 |
8 |
9 | ### 效果
10 |
11 |
12 |
13 | 
14 |
15 |
16 |
17 | 所对应代码大致为:
18 |
19 | ```kotlin
20 | val physicsConfig = PhysicsConfig()
21 |
22 | PhysicsLayout(modifier = modifier, physicsLayoutState = physicsLayoutState, boundSize = boundSize.toFloat()) {
23 | RandomColorBox(modifier = Modifier
24 | .size(40.dp)
25 | .physics(physicsConfig, initialX = 300f, initialY = 500f))
26 | // This one has a circle shape
27 | // so you need to modify it with not only a `clip()` Modifier to make it "looks like" a circle
28 | // but also a `physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE)` Modifier to create a circle Body
29 | RandomColorBox(modifier = Modifier
30 | .clip(CircleShape)
31 | .size(50.dp)
32 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), 300f, 1000f))
33 | RandomColorBox(...)
34 | Checkbox(...)
35 | Card(...) {
36 | ...
37 | }
38 | }
39 | ```
40 |
41 | 这之中的`PhysicsLayout`就是我实现的`物理布局`了
42 |
43 | 如需体验上图的其他功能,可以在仓库下载[demo](demo.apk)
44 |
45 |
46 |
47 | ### 使用
48 |
49 | 库代码位置位于`physics`模块下,故需先依赖此模块。
50 | ```bash
51 | implementation 'com.github.FunnySaltyFish:JetpackComposePhysicsLayout:Tag'
52 | ```
53 |
54 | 布局名为`PhysicsLayout`,基本使用如下:
55 |
56 | ```kotlin
57 | val physicsConfig = PhysicsConfig()
58 | @Composable
59 | fun PhysicsLayoutTest(modifier: Modifier) {
60 | // physicsLayoutState 含有物理模拟相关的 physics 类,并提供了两个方法
61 | // setGravity 和 giveRandomImpulse
62 | val physicsLayoutState by remember {
63 | mutableStateOf(PhysicsLayoutState())
64 | }
65 | var boundSize by remember {
66 | mutableStateOf(20)
67 | }
68 | PhysicsLayout(modifier = modifier, physicsLayoutState = physicsLayoutState, boundSize = boundSize.toFloat()) {
69 | // 使用 .physics Modifier指定物理相关
70 | // initialX/Y 可指定初始位置
71 | RandomColorBox(modifier = Modifier
72 | .size(40.dp)
73 | .physics(physicsConfig, initialX = 300f, initialY = 500f))
74 | // 如果需要指定为圆形的形状
75 | // 你需要先使用`clip()` Modifier 让它“看起来”是个圆
76 | // 再指定`physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE)` Modifier
77 | // 让它在物理世界中是个圆形
78 | RandomColorBox(modifier = Modifier
79 | .clip(CircleShape)
80 | .size(50.dp)
81 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), 300f, 1000f))
82 | }
83 | }
84 | ```
85 |
86 |
87 |
88 | ### 参考
89 |
90 | 正如标题所言,这是一个自定义布局。关于这方面,我已经写了**5篇文章**详细描述了,感兴趣的同学可以点击我的头像查看。本文所用到的无非就是那里的知识加上`JBox2d`而已,看完之后你也写的出来
91 |
92 |
93 |
94 | #### JBox2d
95 |
96 | > JBox2D是开源的2D物理引擎,能够根据开发人员设定的参数,如重力、密度、摩擦系数和弹性系数等,自动进行2D刚体物理运动的模拟。
97 |
98 |
99 |
100 | #### 参考
101 |
102 | 本布局参考自[Jawnnypoo/PhysicsLayout: Android layout that simulates physics using JBox2D (github.com)](https://github.com/Jawnnypoo/PhysicsLayout),其中部分代码也来自于那里,在此表示诚挚的感谢!( 不过我进行了大量的修改,以使原先用于 `View`的代码被用于`Compose`)
103 |
104 |
105 |
106 | ### 实现
107 |
108 | #### 定义
109 |
110 | 首先,我们先来想一个事情:现在每个物体其实都有自己的**位置、大小、形状**这些参数,那么**父布局怎么获得这些值**呢?如果你读过我的[深入Jetpack Compose——布局原理与自定义布局(四)ParentData](https://juejin.cn/post/7073307559792214024),估计可以想到:这是利用`ParentData`传递的。所以咱们先写个自定义的`ParentData`吧
111 |
112 | ```kotlin
113 | class PhysicsParentData(
114 | var physicsConfig: PhysicsConfig = PhysicsConfig(),
115 | var initialX: Float = 0f,
116 | var initialY: Float = 0f,
117 | var width: Int = 0,
118 | var height: Int = 0
119 | )
120 | ```
121 |
122 | `PhysicsConfig`代表基本的物理配置,我们先不细究,其余的就是**初位置和宽高了**。
123 |
124 |
125 |
126 | 有了`ParentData`,那是不是也得有对应的修饰符和作用域啊,所以咱们写一写
127 |
128 | ```kotlin
129 | interface PhysicsLayoutScope {
130 | @Stable
131 | fun Modifier.physics(physicsConfig: PhysicsConfig, initialX : Float = 0f, initialY : Float = 0f) : Modifier
132 | }
133 |
134 | internal object PhysicsLayoutScopeInstance : PhysicsLayoutScope {
135 | @Stable
136 | override fun Modifier.physics(
137 | physicsConfig: PhysicsConfig,
138 | initialX: Float,
139 | initialY: Float
140 | ): Modifier = this.then(PhysicsParentData(physicsConfig, initialX, initialY))
141 | }
142 | ```
143 |
144 | 上面的代码都很简单,属于是自定义`Modifier`的基本操作了,如果你看不懂可以先了解了解再来
145 |
146 |
147 |
148 | #### 使用
149 |
150 | 现在`Modifier`的定义差不多了,接下来就是使用了。其实总结下来就是这个过程
151 |
152 | 1. 初始化各个物体和世界
153 |
154 | 2. 用代码不断模拟一下各个物体的运动过程
155 | 3. 在Layout过程中获取位置并正确摆放出来
156 |
157 | 咱们分别来看*(下面的内容只是我的思路,有些地方可能不太优雅,如果您有更好的想法欢迎指出!)*
158 |
159 | 整体来说,应该有一些代码专门负责物理模拟的过程,这一部分在代码中为`Physics`类,它负责进行具体的`物理世界创造`、`进行物理模拟`等过程。此处不赘述。
160 |
161 |
162 |
163 | ##### 初始化
164 |
165 | 考虑到各子微件的具体信息要到`Layout`才能读取到,所以似乎只能在这里初始化;但是`Layout`又会反复进行,而初始化应该只进行一次。所以用个变量来控制吧
166 |
167 | ```kotlin
168 | var initialized by remember {
169 | mutableStateOf(false)
170 | }
171 | ```
172 |
173 | 然后第一次`Layout`时读取各`ParentData`并存起来
174 |
175 | ```kotlin
176 | val placeables = measurables.mapIndexed { index, measurable ->
177 | val physicsParentData = (measurable.parentData as? PhysicsParentData) ?: PhysicsParentData()
178 | if (!initialized){
179 | parentDataList.add(index, physicsParentData)
180 | }
181 | measurable.measure(childConstraints)
182 | }
183 | ```
184 |
185 | 然后开个副作用,在所有**物体信息**初始化好后创建世界并创建**Body**(在`JBox2d`中代表`刚体`的类)
186 |
187 | ```kotlin
188 | // 初始化世界
189 | LaunchedEffect(initialized){
190 | if (!initialized) return@LaunchedEffect
191 | physics.createWorld { body, i ->
192 | parentDataList[i].body = body
193 | }
194 | }
195 | ```
196 |
197 | 其中`createWord`方法负责创建`Body`并在每个`Body`创建完后回调
198 |
199 |
200 |
201 | ##### 不断模拟
202 |
203 | 模拟的工作交给`JBox2d`,我们要做的就是`不断`就行。所以`while`循环吧
204 |
205 | ```kotlin
206 | LaunchedEffect(key1 = Unit){
207 | while (true){
208 | delay(16)
209 | physics.step() // 模拟 16ms
210 | }
211 | }
212 | ```
213 |
214 |
215 |
216 | ##### 读取并正确放置
217 |
218 | 这个就很简单了,在`Layout`方法里`layout()`中读一下各个`Body`的位置并`place`就行
219 |
220 | 不过这里注意,因为`Body`有旋转角度,所以在`place`的时候需要使用`placeWithLayer`,该方法签名如下:
221 |
222 | ```kotlin
223 | fun Placeable.placeWithLayer(
224 | position: IntOffset,
225 | zIndex: Float = 0f,
226 | layerBlock: GraphicsLayerScope.() -> Unit = DefaultLayerBlock
227 | )
228 | ```
229 |
230 | 其中第三个参数`layerBlock`就提供了`缩放、选择`等方法。具体代码是:
231 |
232 | ```kotlin
233 | layout(constraints.maxWidth, constraints.maxHeight){
234 | placeables.forEachIndexed { i, placeable: Placeable ->
235 | val x = physics.metersToPixels(parentDataList[i].x).toInt() - placeable.width / 2
236 | val y = physics.metersToPixels(parentDataList[i].y).toInt() - placeable.height / 2
237 |
238 | placeable.placeWithLayer(IntOffset(x,y), zIndex = 0f, layerBlock = {
239 | rotationZ = parentDataList[i].rotation
240 | })
241 | }
242 | }
243 | ```
244 |
245 | 上面的`metersToPixels`用于将**物理世界的坐标映射到现实**
246 |
247 | 完工!
248 |
249 |
250 |
251 | ### 后续
252 |
253 | 其实目前来看,代码里还有些地方感觉不大对劲,比如,为了触发`Layout`过程,我实际使用了一个并无任何用处的`state`。因为在我的尝试里,只要`layout`块里不出现`state`的变化,它就不会重新触发(这点当然符合Compose的感觉喽);我想不到什么好点子,只好这么处理了。如果大家有什么好想法,欢迎探讨和PR
254 |
255 | 如果你好奇有什么用……额,我也不知道有什么实际用处。我就是觉得很好玩儿,很早之前就想做了,最近下定决心,两天完成,感觉效果还不错。
256 |
257 | 如果你对Compose完整项目感兴趣,欢迎看看我的开源项目[FunnySaltyFish/FunnyTranslation: 基于Jetpack Compose开发的翻译软件,支持多引擎、插件化~](https://github.com/FunnySaltyFish/FunnyTranslation)
258 |
--------------------------------------------------------------------------------
/README_EN.md:
--------------------------------------------------------------------------------
1 | ## Jetpack Compose Custom Layout + Physical Engine = ?
2 | [](https://jitpack.io/#FunnySaltyFish/JetpackComposePhysicsLayout)
3 |
4 | This library is based on Jetpack Compose custom layout + physical engine(JBox2d).
5 |
6 | Especially thanks to [Jawnnypoo/PhysicsLayout: Android layout that simulates physics using JBox2D (github.com)](https://github.com/Jawnnypoo/PhysicsLayout).
7 |
8 |
9 |
10 | ### Demo
11 |
12 |
13 |
14 | 
15 |
16 | (These three buttons are "give random impulse", "set random gravity" and "set random border size" )
17 |
18 | The corresponding codes are roughly as follows:
19 |
20 |
21 | ```kotlin
22 | val physicsConfig = PhysicsConfig()
23 |
24 | PhysicsLayout(modifier = modifier, physicsLayoutState = physicsLayoutState, boundSize = boundSize.toFloat()) {
25 | RandomColorBox(modifier = Modifier
26 | .size(40.dp)
27 | .physics(physicsConfig, initialX = 300f, initialY = 500f))
28 | // This one has a circle shape
29 | // so you need to modify it with not only a `clip()` Modifier to make it "looks like" a circle
30 | // but also a `physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE)` Modifier to create a circle Body
31 | RandomColorBox(modifier = Modifier
32 | .clip(CircleShape)
33 | .size(50.dp)
34 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), 300f, 1000f))
35 | RandomColorBox(...)
36 | Checkbox(...)
37 | Card(...)
38 | }
39 | ```
40 |
41 | To experience additional features above, you can download the demo [here](demo.apk).
42 |
43 |
44 |
45 | ### Usage
46 |
47 | The code of core library code is located in module `physics`. You can implement by using:
48 | ```bash
49 | implementation 'com.github.FunnySaltyFish:JetpackComposePhysicsLayout:Tag'
50 | ```
51 |
52 | The basically usage is as follows:
53 |
54 |
55 | ```kotlin
56 | val physicsConfig = PhysicsConfig()
57 | @Composable
58 | fun PhysicsLayoutTest(modifier: Modifier) {
59 | // physicsLayoutState contains the class about physics, providing two methods
60 | // setGravity and giveRandomImpulse
61 | val physicsLayoutState by remember {
62 | mutableStateOf(PhysicsLayoutState())
63 | }
64 | var boundSize by remember {
65 | mutableStateOf(20)
66 | }
67 | PhysicsLayout(modifier = modifier, physicsLayoutState = physicsLayoutState, boundSize = boundSize.toFloat()) {
68 | // use `Modifier.physics` to specify the config of physics
69 | // initialX/Y is the initial position of the body
70 | RandomColorBox(modifier = Modifier
71 | .size(40.dp)
72 | .physics(physicsConfig, initialX = 300f, initialY = 500f))
73 | // This one has a circle shape
74 | // so you need to modify it with not only a `clip()` Modifier to make it "looks like" a circle
75 | // but also a `physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE)` Modifier to create a circle Body
76 | RandomColorBox(modifier = Modifier
77 | .clip(CircleShape)
78 | .size(50.dp)
79 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), 300f, 1000f))
80 | }
81 | }
82 | ```
83 |
84 |
85 |
86 | ### Reference
87 |
88 | #### JBox2d
89 |
90 | > JBox2D is an open-source 2D physical engine, which can automatically simulate the physical motion of 2D rigid body according to the parameters set by developers, such as gravity, density, friction coefficient and elastic coefficient.
91 |
92 |
93 |
94 | ### How It Works?
95 |
96 | #### definition
97 |
98 | First, consider one thing: now each object actually has its own **location, size, shape** , so how does **parent layout get these values**? If you've read some related blogs, you can know it: we may use `ParentData`. So let's write a custom `ParentDataModifier` first.
99 |
100 |
101 | ```kotlin
102 | class PhysicsParentData(
103 | var physicsConfig: PhysicsConfig = PhysicsConfig(),
104 | var initialX: Float = 0f,
105 | var initialY: Float = 0f,
106 | var width: Int = 0,
107 | var height: Int = 0
108 | ) : ParentDataModifier
109 | ```
110 |
111 | `PhysicsConfig` stands for the basic physical configuration, and the rest is the **initial position and the size**.
112 |
113 |
114 |
115 | Well. let's write corresponding scope then.
116 |
117 |
118 | ```kotlin
119 | interface PhysicsLayoutScope {
120 | @Stable
121 | fun Modifier.physics(physicsConfig: PhysicsConfig, initialX : Float = 0f, initialY : Float = 0f) : Modifier
122 | }
123 |
124 | internal object PhysicsLayoutScopeInstance : PhysicsLayoutScope {
125 | @Stable
126 | override fun Modifier.physics(
127 | physicsConfig: PhysicsConfig,
128 | initialX: Float,
129 | initialY: Float
130 | ): Modifier = this.then(PhysicsParentData(physicsConfig, initialX, initialY))
131 | }
132 | ```
133 |
134 | The code above is basic operations to define a custom layout. If you don't understand, you can learn first before reading.
135 |
136 |
137 |
138 | #### Use It
139 |
140 | Now we've finished basic definition. Let's start to implement the layout. Here are my process.
141 |
142 | 1. Initialize objects and the world
143 |
144 | 2. Use the code to simulate the movement of each object
145 | 3. Get the location and place it correctly during Layout
146 |
147 | Let's do them one after another! *(Here are just my thoughts, and some of them may not be so elegant, if you have better ideas please point them out! )*
148 |
149 | In general, there should be some code dedicated to the physical simulation process, this part of the code is class `Physics`, which is responsible for `creating the world`, `simulate`, and so on. We just pass it here.
150 |
151 |
152 |
153 | ##### initialization
154 |
155 | Considering that the specific information of each sub-component is not readable until `Layout` , so it seems that we can only initialize here; but cause the `Layout` process will be done repeatedly, and initialization should only be done once. So we use a variable to control it.
156 |
157 |
158 | ```kotlin
159 | var initialized by remember {
160 | mutableStateOf(false)
161 | }
162 | ```
163 |
164 | They we store these`ParentData` at the first time.
165 |
166 |
167 | ```kotlin
168 | val placeables = measurables.mapIndexed { index, measurable ->
169 | val physicsParentData = (measurable.parentData as? PhysicsParentData) ?: PhysicsParentData()
170 | if (!initialized){
171 | parentDataList.add(index, physicsParentData)
172 | }
173 | measurable.measure(childConstraints)
174 | }
175 | ```
176 |
177 | And then, with a side effect, after all the object information is initialized, create the world and create **Body** (the class representing `rigid body` in JBox2d)
178 |
179 |
180 | ```kotlin
181 | // 初始化世界
182 | LaunchedEffect(initialized){
183 | if (!initialized) return@LaunchedEffect
184 | physics.createWorld { body, i ->
185 | parentDataList[i].body = body
186 | }
187 | }
188 | ```
189 |
190 | where method `createWorld` is responsible for creating `World` and do callback after each creation.
191 |
192 |
193 |
194 | ##### continuous simulation
195 |
196 | Simulating is the duty of `JBox2d` . All we have to do is call it repeatedly.
197 |
198 |
199 | ```kotlin
200 | LaunchedEffect(key1 = Unit){
201 | while (true){
202 | delay(16)
203 | physics.step() // 模拟 16ms
204 | }
205 | }
206 | ```
207 |
208 |
209 |
210 | ##### Read and place correctly
211 |
212 | This is not difficult,just reading each `Body`'s position and place it in `Layout`.
213 |
214 | A special thing is,because `Body` has its rotation angle,so we need to use method`placeWithLayer`, whose signature is as below:
215 |
216 |
217 | ```kotlin
218 | fun Placeable.placeWithLayer(
219 | position: IntOffset,
220 | zIndex: Float = 0f,
221 | layerBlock: GraphicsLayerScope.() -> Unit = DefaultLayerBlock
222 | )
223 | ```
224 |
225 | where the third parameter `layerBlock` provides the way to `rotate`, `transform` and so on. The corresponding code is as below:
226 |
227 |
228 | ```kotlin
229 | layout(constraints.maxWidth, constraints.maxHeight){
230 | placeables.forEachIndexed { i, placeable: Placeable ->
231 | val x = physics.metersToPixels(parentDataList[i].x).toInt() - placeable.width / 2
232 | val y = physics.metersToPixels(parentDataList[i].y).toInt() - placeable.height / 2
233 |
234 | placeable.placeWithLayer(IntOffset(x,y), zIndex = 0f, layerBlock = {
235 | rotationZ = parentDataList[i].rotation
236 | })
237 | }
238 | }
239 | ```
240 |
241 | The function `metersToPixels` used above is to map **physical world coordinates to reality coordinates**
242 |
243 | Done!
244 |
245 |
246 |
247 |
248 |
249 | ### Follow-up
250 |
251 | Actually, there's something not so perfect with the code right now, like, to trigger `Layout` , I actually used a state that wasn't useful... Because in my attempts, as long as `state` never appears to change, it won't be triggered (which is what Compose should behave); I can't think of any good ideas, so if you have any good ideas, please discuss them with PRs.
252 |
253 | If you're wondering what it can be used for......Well, I don't know, neither. I just thought it was fun. I've been thinking of doing it for a long time. and finally spent two days finishing it. It looks well, I think :)
254 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | compileSdk 31
8 |
9 | defaultConfig {
10 | applicationId "com.funny.compose.physicslayout"
11 | minSdk 21
12 | targetSdk 32
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | vectorDrawables {
18 | useSupportLibrary true
19 | }
20 | }
21 |
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 | compileOptions {
29 | sourceCompatibility JavaVersion.VERSION_1_8
30 | targetCompatibility JavaVersion.VERSION_1_8
31 | }
32 | kotlinOptions {
33 | jvmTarget = '1.8'
34 | }
35 | buildFeatures {
36 | compose true
37 | }
38 | composeOptions {
39 | kotlinCompilerExtensionVersion compose_version
40 | }
41 | packagingOptions {
42 | resources {
43 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
44 | }
45 | }
46 | }
47 |
48 | dependencies {
49 | implementation 'androidx.core:core-ktx:1.7.0'
50 | implementation "androidx.compose.ui:ui:$compose_version"
51 | implementation "androidx.compose.material:material:$compose_version"
52 | implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
53 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
54 | implementation 'androidx.activity:activity-compose:1.4.0'
55 |
56 | // 提供 MaterialColors
57 | implementation "com.github.FunnySaltyFish:CMaterialColors:1.0.21"
58 |
59 | implementation project(path : ":physics")
60 | testImplementation 'junit:junit:4.13.2'
61 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
62 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
63 | androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
64 | debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
65 | debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
66 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/funny/compose/physicslayout/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.funny.compose.physicslayout", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
16 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout
2 |
3 | import android.content.Intent
4 | import android.net.Uri
5 | import android.os.Bundle
6 | import androidx.activity.ComponentActivity
7 | import androidx.activity.compose.setContent
8 | import androidx.compose.foundation.Image
9 | import androidx.compose.foundation.background
10 | import androidx.compose.foundation.layout.*
11 | import androidx.compose.foundation.lazy.LazyColumn
12 | import androidx.compose.foundation.shape.CircleShape
13 | import androidx.compose.foundation.text.ClickableText
14 | import androidx.compose.material.*
15 | import androidx.compose.runtime.*
16 | import androidx.compose.ui.Modifier
17 | import androidx.compose.ui.draw.clip
18 | import androidx.compose.ui.graphics.Color
19 | import androidx.compose.ui.platform.LocalContext
20 | import androidx.compose.ui.res.painterResource
21 | import androidx.compose.ui.text.SpanStyle
22 | import androidx.compose.ui.text.buildAnnotatedString
23 | import androidx.compose.ui.text.font.FontWeight
24 | import androidx.compose.ui.text.style.TextDecoration
25 | import androidx.compose.ui.text.withStyle
26 | import androidx.compose.ui.unit.dp
27 | import androidx.compose.ui.unit.sp
28 | import com.funny.cmaterialcolors.MaterialColors
29 | import com.funny.compose.physics.PhysicsConfig
30 | import com.funny.compose.physics.PhysicsLayout
31 | import com.funny.compose.physics.PhysicsLayoutState
32 | import com.funny.compose.physics.PhysicsShape
33 | import com.funny.compose.physicslayout.ui.RandomColorBox
34 | import com.funny.compose.physicslayout.ui.theme.JetpackComposePhysicsLayoutTheme
35 | import kotlin.random.Random
36 |
37 | class MainActivity : ComponentActivity() {
38 | override fun onCreate(savedInstanceState: Bundle?) {
39 | super.onCreate(savedInstanceState)
40 | setContent {
41 | JetpackComposePhysicsLayoutTheme {
42 | Surface(
43 | modifier = Modifier.fillMaxSize(),
44 | color = MaterialTheme.colors.background
45 | ) {
46 | Column(
47 | Modifier
48 | .fillMaxSize()
49 | .padding(8.dp)) {
50 | val physicsLayoutState by remember {
51 | mutableStateOf(PhysicsLayoutState())
52 | }
53 | var boundSize by remember {
54 | mutableStateOf(20)
55 | }
56 | PhysicsLayoutTest(
57 | Modifier
58 | .fillMaxWidth()
59 | .fillMaxHeight(0.8f),
60 | physicsLayoutState,
61 | boundSize
62 | )
63 | Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround) {
64 | Button(onClick = { physicsLayoutState.giveRandomImpulse() }) {
65 | Text(text = "随机给个冲量")
66 | }
67 | Button(onClick = {
68 | physicsLayoutState.setGravity(
69 | Random.nextDouble(-5.0,5.0).toFloat(),
70 | Random.nextDouble(-9.8,9.8).toFloat()
71 | )
72 | }) {
73 | Text(text = "随机重力")
74 | }
75 | Button(onClick = {
76 | boundSize = Random.nextInt(5,20)
77 | }) {
78 | Text(text = "随机边框大小")
79 | }
80 | }
81 |
82 | }
83 | }
84 | }
85 | }
86 | }
87 | }
88 |
89 | val physicsConfig = PhysicsConfig()
90 | @Composable
91 | fun PhysicsLayoutTest(modifier: Modifier, physicsLayoutState: PhysicsLayoutState, boundSize : Int) {
92 | PhysicsLayout(modifier = modifier, physicsLayoutState = physicsLayoutState, boundSize = boundSize.toFloat()) {
93 | RandomColorBox(modifier = Modifier
94 | .size(40.dp)
95 | .physics(physicsConfig, initialX = 300f, initialY = 500f))
96 | // This one has a circle shape
97 | // so you need to modify it with not only a `clip()` Modifier to make it "looks like" a circle
98 | // but also a `physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE)` Modifier to create a circle Body
99 | RandomColorBox(modifier = Modifier
100 | .clip(CircleShape)
101 | .size(50.dp)
102 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), 300f, 1000f))
103 | RandomColorBox(modifier = Modifier
104 | .size(60.dp)
105 | .physics(physicsConfig))
106 | var checked by remember {
107 | mutableStateOf(false)
108 | }
109 | Checkbox(checked = checked, onCheckedChange = { checked = it })
110 | Card(modifier = Modifier
111 | .clip(CircleShape)
112 | .physics(physicsConfig.copy(shape = PhysicsShape.CIRCLE), initialX = 200f)) {
113 | Image(painter = painterResource(id = R.drawable.bg_avatar), contentDescription = "avatar", modifier = Modifier.size(100.dp))
114 | }
115 | val context = LocalContext.current
116 | LazyColumn(modifier = Modifier
117 | .width(200.dp)
118 | .height(100.dp)
119 | .background(MaterialColors.Orange200)
120 | .physics(physicsConfig, initialY = 300f)){
121 | item {
122 | ClickableText(text = buildAnnotatedString {
123 | withStyle(
124 | style = SpanStyle(
125 | color = Color.Blue,
126 | fontWeight = FontWeight.Bold,
127 | textDecoration = TextDecoration.Underline
128 | )
129 | ) {
130 | append("Github/JetpackComposePhysicsLayout")
131 | }
132 | }){
133 | Intent().apply {
134 | action = Intent.ACTION_VIEW
135 | data = Uri.parse("https://github.com/FunnySaltyFish/JetpackComposePhysicsLayout")
136 | }.also {
137 | context.startActivity(it)
138 | }
139 | }
140 | }
141 | items(10){
142 | Text(text = "FunnySaltyFish", modifier = Modifier.padding(8.dp), fontWeight = FontWeight.W500, fontSize = 18.sp)
143 | }
144 | }
145 | }
146 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/ui/RandomColorBox.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout.ui
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.runtime.saveable.Saver
7 | import androidx.compose.runtime.saveable.rememberSaveable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.graphics.Color
10 | import androidx.compose.ui.graphics.toArgb
11 | import kotlin.random.Random
12 |
13 | fun randomColor() = Color(Random.nextInt(255), Random.nextInt(255), Random.nextInt(255))
14 |
15 | @Composable
16 | fun rememberRandomColor() = rememberSaveable(
17 | saver = Saver(
18 | save = { value ->
19 | value.toArgb()
20 | },
21 | restore = {
22 | Color(it)
23 | }
24 | )
25 | ) {
26 | randomColor()
27 | }
28 |
29 | @Composable
30 | fun RandomColorBox(modifier: Modifier) {
31 | Box(modifier = modifier.background(rememberRandomColor()))
32 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple200 = Color(0xFFBB86FC)
6 | val Purple500 = Color(0xFF6200EE)
7 | val Purple700 = Color(0xFF3700B3)
8 | val Teal200 = Color(0xFF03DAC5)
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/ui/theme/Shape.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout.ui.theme
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.material.Shapes
5 | import androidx.compose.ui.unit.dp
6 |
7 | val Shapes = Shapes(
8 | small = RoundedCornerShape(4.dp),
9 | medium = RoundedCornerShape(4.dp),
10 | large = RoundedCornerShape(0.dp)
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material.MaterialTheme
5 | import androidx.compose.material.darkColors
6 | import androidx.compose.material.lightColors
7 | import androidx.compose.runtime.Composable
8 |
9 | private val DarkColorPalette = darkColors(
10 | primary = Purple200,
11 | primaryVariant = Purple700,
12 | secondary = Teal200
13 | )
14 |
15 | private val LightColorPalette = lightColors(
16 | primary = Purple500,
17 | primaryVariant = Purple700,
18 | secondary = Teal200
19 |
20 | /* Other default colors to override
21 | background = Color.White,
22 | surface = Color.White,
23 | onPrimary = Color.White,
24 | onSecondary = Color.Black,
25 | onBackground = Color.Black,
26 | onSurface = Color.Black,
27 | */
28 | )
29 |
30 | @Composable
31 | fun JetpackComposePhysicsLayoutTheme(
32 | darkTheme: Boolean = isSystemInDarkTheme(),
33 | content: @Composable () -> Unit
34 | ) {
35 | val colors = if (darkTheme) {
36 | DarkColorPalette
37 | } else {
38 | LightColorPalette
39 | }
40 |
41 | MaterialTheme(
42 | colors = colors,
43 | typography = Typography,
44 | shapes = Shapes,
45 | content = content
46 | )
47 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/funny/compose/physicslayout/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout.ui.theme
2 |
3 | import androidx.compose.material.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | body1 = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp
15 | )
16 | /* Other default text styles to override
17 | button = TextStyle(
18 | fontFamily = FontFamily.Default,
19 | fontWeight = FontWeight.W500,
20 | fontSize = 14.sp
21 | ),
22 | caption = TextStyle(
23 | fontFamily = FontFamily.Default,
24 | fontWeight = FontWeight.Normal,
25 | fontSize = 12.sp
26 | )
27 | */
28 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_avatar.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/drawable/bg_avatar.jpg
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | JetpackComposePhysicsLayout
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/test/java/com/funny/compose/physicslayout/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physicslayout
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | compose_version = '1.2.0-beta02'
4 | kotlin_version = "1.6.21"
5 | version_name = "1.0.0"
6 | }
7 | repositories {
8 | mavenLocal()
9 | //maven { url 'https://repo.huaweicloud.com/repository/maven/'}
10 | maven { url 'https://maven.aliyun.com/repository/public/' }
11 | maven { url 'https://maven.aliyun.com/repository/google/'}
12 | maven { url 'https://maven.aliyun.com/repository/jcenter/'}
13 | maven { url "https://jitpack.io" }
14 | google()
15 | }
16 | dependencies {
17 | classpath "com.android.tools.build:gradle:7.1.1"
18 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
19 |
20 | // NOTE: Do not place your application dependencies here; they belong
21 | // in the individual module build.gradle files
22 | }
23 | }
24 | task clean(type: Delete) {
25 | delete rootProject.buildDir
26 | }
--------------------------------------------------------------------------------
/demo.apk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/demo.apk
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue May 31 12:22:51 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk11
--------------------------------------------------------------------------------
/physics/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/physics/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | id 'maven-publish'
5 | }
6 |
7 | task generateSourcesJar(type: Jar) {
8 | from android.sourceSets.main.java.srcDirs
9 | classifier 'sources'
10 | }
11 |
12 | android {
13 | compileSdk 31
14 |
15 | defaultConfig {
16 | minSdk 21
17 | targetSdk 32
18 |
19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
20 | consumerProguardFiles "consumer-rules.pro"
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | compileOptions {
30 | sourceCompatibility JavaVersion.VERSION_1_8
31 | targetCompatibility JavaVersion.VERSION_1_8
32 | }
33 | kotlinOptions {
34 | jvmTarget = '1.8'
35 | }
36 | buildFeatures {
37 | compose true
38 | }
39 | composeOptions {
40 | kotlinCompilerExtensionVersion compose_version
41 | }
42 | packagingOptions {
43 | resources {
44 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
45 | }
46 | }
47 |
48 | publishing {
49 | singleVariant("release")
50 | }
51 | }
52 |
53 | afterEvaluate {
54 | publishing {
55 | def versionName = version_name
56 | publications {
57 | // Creates a Maven publication called "release".
58 | release(MavenPublication) {
59 | // Applies the component for the release build variant.
60 | from components.release
61 |
62 | // You can then customize attributes of the publication as shown below.
63 | groupId = 'com.funny.compose'
64 | artifactId = 'physics-layout'
65 | version = versionName
66 | }
67 | }
68 | repositories {
69 | maven {
70 | // change URLs to point to your repos, e.g. http://my.org/repo
71 | def baseUrl = buildDir.getParent()
72 | def releasesRepoUrl = "$baseUrl/repos/releases"
73 | def snapshotsRepoUrl = "$baseUrl/repos/snapshots"
74 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
75 | }
76 | }
77 | }
78 | }
79 |
80 | dependencies {
81 | implementation 'androidx.core:core-ktx:1.7.0'
82 | implementation "androidx.compose.ui:ui:$compose_version"
83 |
84 | // kotlin
85 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
86 |
87 | api 'org.jbox2d:jbox2d-library:2.2.1.1'
88 |
89 | testImplementation 'junit:junit:4.13.2'
90 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
91 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
92 | }
--------------------------------------------------------------------------------
/physics/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/physics/consumer-rules.pro
--------------------------------------------------------------------------------
/physics/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar.md5:
--------------------------------------------------------------------------------
1 | bfc44af9479de8bdae1217c90126cc55
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar.sha1:
--------------------------------------------------------------------------------
1 | af35e0385849cb67fc2e35b2d8d738986dda24bc
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar.sha256:
--------------------------------------------------------------------------------
1 | becff5c82630160313c53082a85efa911dddde738add370d6adcf5f055dd6ba2
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.aar.sha512:
--------------------------------------------------------------------------------
1 | cc72bc184332517f72adbdbd7b70c03db7bdb9fba8e866b52bab30fc95b677e5c80452e93c6d4ecd320dc0885972e08312a31a7e28d989b4f45eaf97e5941b7a
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.module:
--------------------------------------------------------------------------------
1 | {
2 | "formatVersion": "1.1",
3 | "component": {
4 | "group": "com.funny.compose",
5 | "module": "physics-layout",
6 | "version": "1.0.0",
7 | "attributes": {
8 | "org.gradle.status": "release"
9 | }
10 | },
11 | "createdBy": {
12 | "gradle": {
13 | "version": "7.3"
14 | }
15 | },
16 | "variants": [
17 | {
18 | "name": "releaseVariantReleaseApiPublication",
19 | "attributes": {
20 | "org.gradle.category": "library",
21 | "org.gradle.dependency.bundling": "external",
22 | "org.gradle.libraryelements": "aar",
23 | "org.gradle.usage": "java-api"
24 | },
25 | "dependencies": [
26 | {
27 | "group": "org.jbox2d",
28 | "module": "jbox2d-library",
29 | "version": {
30 | "requires": "2.2.1.1"
31 | }
32 | }
33 | ],
34 | "files": [
35 | {
36 | "name": "physics-layout-1.0.0.aar",
37 | "url": "physics-layout-1.0.0.aar",
38 | "size": 66932,
39 | "sha512": "cc72bc184332517f72adbdbd7b70c03db7bdb9fba8e866b52bab30fc95b677e5c80452e93c6d4ecd320dc0885972e08312a31a7e28d989b4f45eaf97e5941b7a",
40 | "sha256": "becff5c82630160313c53082a85efa911dddde738add370d6adcf5f055dd6ba2",
41 | "sha1": "af35e0385849cb67fc2e35b2d8d738986dda24bc",
42 | "md5": "bfc44af9479de8bdae1217c90126cc55"
43 | }
44 | ]
45 | },
46 | {
47 | "name": "releaseVariantReleaseRuntimePublication",
48 | "attributes": {
49 | "org.gradle.category": "library",
50 | "org.gradle.dependency.bundling": "external",
51 | "org.gradle.libraryelements": "aar",
52 | "org.gradle.usage": "java-runtime"
53 | },
54 | "dependencies": [
55 | {
56 | "group": "org.jbox2d",
57 | "module": "jbox2d-library",
58 | "version": {
59 | "requires": "2.2.1.1"
60 | }
61 | },
62 | {
63 | "group": "androidx.core",
64 | "module": "core-ktx",
65 | "version": {
66 | "requires": "1.7.0"
67 | }
68 | },
69 | {
70 | "group": "androidx.compose.ui",
71 | "module": "ui",
72 | "version": {
73 | "requires": "1.2.0-beta02"
74 | }
75 | },
76 | {
77 | "group": "org.jetbrains.kotlin",
78 | "module": "kotlin-stdlib-jdk8",
79 | "version": {
80 | "requires": "1.6.21"
81 | }
82 | }
83 | ],
84 | "files": [
85 | {
86 | "name": "physics-layout-1.0.0.aar",
87 | "url": "physics-layout-1.0.0.aar",
88 | "size": 66932,
89 | "sha512": "cc72bc184332517f72adbdbd7b70c03db7bdb9fba8e866b52bab30fc95b677e5c80452e93c6d4ecd320dc0885972e08312a31a7e28d989b4f45eaf97e5941b7a",
90 | "sha256": "becff5c82630160313c53082a85efa911dddde738add370d6adcf5f055dd6ba2",
91 | "sha1": "af35e0385849cb67fc2e35b2d8d738986dda24bc",
92 | "md5": "bfc44af9479de8bdae1217c90126cc55"
93 | }
94 | ]
95 | }
96 | ]
97 | }
98 |
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.module.md5:
--------------------------------------------------------------------------------
1 | ecb0b837cf7f9575a2a48066c6e29476
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.module.sha1:
--------------------------------------------------------------------------------
1 | 0acf2c27563f11c85e4cd8f88d8ff7e6cb7be230
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.module.sha256:
--------------------------------------------------------------------------------
1 | 94fbfa82db847cb92f210c4721df0fcd878d96548b7a36f331c1b5cfd1bf8198
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.module.sha512:
--------------------------------------------------------------------------------
1 | 243f26467522b65f054110869965022b2e08235030c7d003de84826feffcf8d913322028d19677241c5082206508499886007b75f7cb90374b631d6be5db5f0f
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.pom:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 | 4.0.0
10 | com.funny.compose
11 | physics-layout
12 | 1.0.0
13 | aar
14 |
15 |
16 | org.jbox2d
17 | jbox2d-library
18 | 2.2.1.1
19 | compile
20 |
21 |
22 | androidx.core
23 | core-ktx
24 | 1.7.0
25 | runtime
26 |
27 |
28 | androidx.compose.ui
29 | ui
30 | 1.2.0-beta02
31 | runtime
32 |
33 |
34 | org.jetbrains.kotlin
35 | kotlin-stdlib-jdk8
36 | 1.6.21
37 | runtime
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.pom.md5:
--------------------------------------------------------------------------------
1 | b451c573d6ae0a5e185795f39bec609a
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.pom.sha1:
--------------------------------------------------------------------------------
1 | da769f051eeefe9e9134d29ac2e889d99942116b
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.pom.sha256:
--------------------------------------------------------------------------------
1 | 2a3d4e49a73bce3fdbecb008b29502b343b01098d80de2f24bd6fd01b02c56d0
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/1.0.0/physics-layout-1.0.0.pom.sha512:
--------------------------------------------------------------------------------
1 | 0df18421509b0ef21a5a4e7e64e9e1f89cbc95ae85aabe01d16a7020aa3331e74fda786196ef2878e4acd74e3752b76566692157ce2cafa05f55a49c8090453a
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/maven-metadata.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | com.funny.compose
4 | physics-layout
5 |
6 | 1.0.0
7 | 1.0.0
8 |
9 | 1.0.0
10 |
11 | 20220611111343
12 |
13 |
14 |
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/maven-metadata.xml.md5:
--------------------------------------------------------------------------------
1 | 6880410f72433442ba133e4b5e3fe335
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/maven-metadata.xml.sha1:
--------------------------------------------------------------------------------
1 | 864c93c1d44a6fa21de68aafa20e2598cb2c059c
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/maven-metadata.xml.sha256:
--------------------------------------------------------------------------------
1 | e2d0dfbcbdbe7adc8c245899a1945cf0b1c6cc888f9acf1d0a7f5b7344dd1fee
--------------------------------------------------------------------------------
/physics/repos/releases/com/funny/compose/physics-layout/maven-metadata.xml.sha512:
--------------------------------------------------------------------------------
1 | 870e02cce447851662bdfca3720227ae446df74a7830c1a516e1d474196a7f6e84ae5b238a780ec7dcf7c2c4297bbbc14ba4c23a500aee69bf790895b7be009e
--------------------------------------------------------------------------------
/physics/src/androidTest/java/com/funny/compose/physics/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.funny.compose.physics.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/physics/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/Bound.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import org.jbox2d.dynamics.Body
4 |
5 | /**
6 | * A bound around the edge of the view
7 | */
8 | data class Bound(
9 | val widthInPixels: Float,
10 | val heightInPixels: Float,
11 | val body: Body,
12 | val side: Side
13 | ) {
14 | enum class Side {
15 | TOP,
16 | LEFT,
17 | RIGHT,
18 | BOTTOM
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/LayoutRecomposeTest.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import android.util.Log
4 | import androidx.compose.runtime.*
5 | import androidx.compose.ui.Modifier
6 | import androidx.compose.ui.layout.Layout
7 | import androidx.compose.ui.layout.Measurable
8 | import androidx.compose.ui.unit.Constraints
9 | import kotlinx.coroutines.delay
10 |
11 | // this file DOSE NOT BELONG TO THE LIBRARY
12 | // it is just used for test
13 | data class Point(var x : Int, var y : Int)
14 | private const val TAG = "LayoutRecomposeTest"
15 | @Composable
16 | fun LayoutRecomposeTest(
17 | modifier: Modifier = Modifier,
18 | content: @Composable () -> Unit
19 | ) {
20 | val positions = remember {
21 | mutableStateListOf(
22 | Point(0,0), Point(50,50)
23 | )
24 | }
25 |
26 | var yy by remember {
27 | mutableStateOf(0)
28 | }
29 |
30 | LaunchedEffect(key1 = Unit){
31 | Log.d(TAG, "LayoutRecomposeTest: Recompose")
32 | while (true){
33 | delay(400)
34 | positions.forEach {
35 | it.x += 1
36 | it.y += 1
37 | yy += 1
38 | // Log.d(TAG, "LayoutRecomposeTest: $it")
39 | }
40 | }
41 | }
42 |
43 | Layout(
44 | modifier = modifier,
45 | content = content
46 | ) { measurables: List, constraints: Constraints ->
47 | val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)
48 | val placeables = measurables.map { it.measure(childConstraints) }
49 | // 宽度:最宽的一项
50 | val width = placeables.maxOf { it.width }
51 | // 高度:所有子微件高度之和
52 | val height = placeables.sumOf { it.height }
53 | layout(width, height) {
54 | // yy 为 mutableStateOf 可以
55 | val y = yy
56 | // Log.d(TAG, "LayoutRecomposeTest: $y")
57 | placeables.forEachIndexed { i , placeable ->
58 | placeable.placeRelative(0, derivedStateOf { positions[i].y }.value)
59 | }
60 | }
61 | }
62 | }
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/Physics.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import android.graphics.Color
4 | import android.graphics.Paint
5 | import android.util.Log
6 | import android.view.MotionEvent
7 | import android.view.View
8 | import com.funny.compose.physics.Bound
9 | import org.jbox2d.callbacks.ContactImpulse
10 | import org.jbox2d.callbacks.ContactListener
11 | import org.jbox2d.collision.Manifold
12 | import org.jbox2d.collision.shapes.CircleShape
13 | import org.jbox2d.collision.shapes.PolygonShape
14 | import org.jbox2d.common.Vec2
15 | import org.jbox2d.dynamics.*
16 | import org.jbox2d.dynamics.contacts.Contact
17 | import java.util.*
18 | import kotlin.collections.ArrayList
19 | import kotlin.math.max
20 | import kotlin.properties.Delegates
21 |
22 | class ComposableGroup(var physicsParentDatas: ArrayList){
23 | val childCount : Int
24 | get() = physicsParentDatas.size
25 | fun getChildAt(index : Int) = physicsParentDatas[index]
26 | }
27 |
28 | /**
29 | * This file originally comes from [Here](https://github.com/Jawnnypoo/PhysicsLayout)
30 | *
31 | * I modified some to make it suitable for Compose
32 | *
33 | * -- original comment is as below --
34 | *
35 | * Implementation for physics layout is found here, since we want to offer the main
36 | * layouts without requiring further extension (LinearLayout, RelativeLayout, etc.)
37 | */
38 | @Suppress("unused", "MemberVisibilityCanBePrivate")
39 | class Physics constructor(val composableGroup: ComposableGroup) {
40 |
41 | companion object {
42 | private val TAG = Physics::class.java.simpleName
43 | const val NO_GRAVITY = 0.0f
44 | const val MOON_GRAVITY = 1.6f
45 | const val EARTH_GRAVITY = 9.8f
46 | const val JUPITER_GRAVITY = 24.8f
47 |
48 | // Size in DP of the bounds (world walls) of the view
49 | private const val BOUND_SIZE_DP = 20
50 | private const val FRAME_RATE = 1 / 60f
51 |
52 | const val ID_BOUND_TOP = 0
53 | const val ID_BOUND_LEFT = 1
54 | const val ID_BOUND_RIGHT = 2
55 | const val ID_BOUND_BOTTOM = 3
56 |
57 | }
58 |
59 | private val debugDraw = false
60 | private val debugLog = false
61 |
62 | /**
63 | * Set the number of velocity iterations the world will perform at each step.
64 | * Default is 8
65 | */
66 | var velocityIterations = 8
67 |
68 | /**
69 | * Set the number of position iterations the world will perform at each step.
70 | * Default is 3
71 | */
72 | var positionIterations = 3
73 |
74 | /**
75 | * Set the number of pixels per meter. Basically makes the world feel bigger or smaller
76 | * Default is 20dp. More pixels per meter = ui feeling bigger in the world (faster movement)
77 | */
78 | var pixelsPerMeter = 0f
79 |
80 | /**
81 | * Get the current Box2D [World] controlling the physics of this view
82 | */
83 | var world: World? = null
84 | private set
85 |
86 | /**
87 | * Enable/disable physics on the view
88 | */
89 | var isPhysicsEnabled = true
90 |
91 | /**
92 | * Enable/disable fling for this View
93 | */
94 | var isFlingEnabled = false
95 |
96 | /**
97 | * Enables/disables if the view has bounds or not
98 | */
99 | var hasBounds = true
100 |
101 | var boundsSizeInPixel = 1f
102 | val bounds = mutableListOf()
103 | private var gravityX = 0.0f
104 | private var gravityY = EARTH_GRAVITY
105 |
106 | private val debugPaint: Paint by lazy {
107 | val paint = Paint()
108 | paint.color = Color.MAGENTA
109 | paint.style = Paint.Style.STROKE
110 | paint
111 | }
112 |
113 | var density = 0f
114 | var width = 0
115 | var height = 0
116 |
117 | private var viewBeingDragged: View? = null
118 | private var onFlingListener: OnFlingListener? = null
119 | private var onCollisionListener: OnCollisionListener? = null
120 | private var onPhysicsProcessedListeners = mutableListOf()
121 |
122 | private val contactListener: ContactListener = object : ContactListener {
123 | override fun beginContact(contact: Contact) {
124 | if (onCollisionListener != null) {
125 | onCollisionListener!!.onCollisionEntered(contact.fixtureA.m_userData as Int,
126 | contact.fixtureB.m_userData as Int)
127 | }
128 | }
129 |
130 | override fun endContact(contact: Contact) {
131 | if (onCollisionListener != null) {
132 | onCollisionListener!!.onCollisionExited(contact.fixtureA.m_userData as Int,
133 | contact.fixtureB.m_userData as Int)
134 | }
135 | }
136 |
137 | override fun preSolve(contact: Contact, oldManifold: Manifold) {}
138 | override fun postSolve(contact: Contact, impulse: ContactImpulse) {}
139 | }
140 |
141 | fun step(){
142 | world?.step(FRAME_RATE, velocityIterations, positionIterations)
143 | }
144 |
145 | fun metersToPixels(meters: Float): Float {
146 | return meters * pixelsPerMeter
147 | }
148 |
149 | fun pixelsToMeters(pixels: Float): Float {
150 | return pixels / pixelsPerMeter
151 | }
152 |
153 | private fun radiansToDegrees(radians: Float): Float {
154 | return radians / 3.14f * 180f
155 | }
156 |
157 | private fun degreesToRadians(degrees: Float): Float {
158 | return degrees / 180f * 3.14f
159 | }
160 |
161 | /**
162 | * Call this every time your view gets a call to onSizeChanged so that the world can
163 | * respond to this change.
164 | */
165 | fun setSize(width: Int, height: Int) {
166 | this.width = width
167 | this.height = height
168 | }
169 |
170 | /**
171 | * Call this in your ViewGroup if you plan on using fling
172 | * @return true if consumed, false otherwise
173 | */
174 | fun onTouchEvent(ev: MotionEvent): Boolean {
175 | if (!isFlingEnabled) {
176 | return false
177 | }
178 | return true
179 | }
180 |
181 | /**
182 | * Recreate the physics world. Will traverse all views in the hierarchy, get their current
183 | * PhysicsConfigs and create a body in the world. This will override the current world if it exists.
184 | */
185 | fun createWorld(onBodyCreatedListener : (Body, Int) -> Unit) {
186 | // Null out all the bodies
187 | val oldBodiesArray = ArrayList()
188 | for (i in 0 until composableGroup.childCount) {
189 | val body = composableGroup.getChildAt(i).body
190 | oldBodiesArray.add(body)
191 | composableGroup.getChildAt(i).body = null
192 | }
193 | bounds.clear()
194 | if (debugLog) {
195 | Log.d(TAG, "createWorld")
196 | }
197 | world = World(Vec2(gravityX, gravityY)).apply {
198 | setContactListener(contactListener)
199 | }
200 | if (hasBounds) {
201 | enableBounds()
202 | }
203 | for (i in 0 until composableGroup.childCount) {
204 | val body = createBody(composableGroup.getChildAt(i), oldBodiesArray[i])
205 | onBodyCreatedListener(body, i)
206 | }
207 | }
208 |
209 | private fun enableBounds() {
210 | hasBounds = true
211 | createBounds()
212 | }
213 |
214 | private fun disableBounds() {
215 | hasBounds = false
216 | for (body in bounds) {
217 | world?.destroyBody(body.body)
218 | }
219 | bounds.clear()
220 | }
221 |
222 | private fun createBounds() {
223 | val top = createBound(
224 | widthInPixels = width.toFloat(),
225 | heightInPixels = boundsSizeInPixel,
226 | id = ID_BOUND_TOP,
227 | side = Bound.Side.TOP
228 | )
229 | bounds.add(top)
230 |
231 | val bottom = createBound(
232 | widthInPixels = width.toFloat(),
233 | heightInPixels = boundsSizeInPixel,
234 | id = ID_BOUND_BOTTOM,
235 | side = Bound.Side.BOTTOM
236 | )
237 | bounds.add(bottom)
238 |
239 | val left = createBound(
240 | widthInPixels = boundsSizeInPixel,
241 | heightInPixels = height.toFloat(),
242 | id = ID_BOUND_LEFT,
243 | side = Bound.Side.LEFT
244 | )
245 | bounds.add(left)
246 |
247 | val right = createBound(
248 | widthInPixels = boundsSizeInPixel,
249 | heightInPixels = height.toFloat(),
250 | id = ID_BOUND_RIGHT,
251 | side = Bound.Side.RIGHT
252 | )
253 | bounds.add(right)
254 | }
255 |
256 | private fun createBound(widthInPixels: Float, heightInPixels: Float, id: Int, side: Bound.Side): Bound {
257 | val bodyDef = BodyDef()
258 | bodyDef.type = BodyType.STATIC
259 | val box = PolygonShape()
260 | val boxWidthMeters = pixelsToMeters(widthInPixels)
261 | val boxHeightMeters = pixelsToMeters(heightInPixels)
262 | box.setAsBox(boxWidthMeters / 2, boxHeightMeters / 2)
263 | val fixtureDef = createBoundFixtureDef(box, id)
264 | val pair = when (side) {
265 | Bound.Side.TOP -> Pair(boxWidthMeters / 2, boxHeightMeters / 2)
266 | Bound.Side.BOTTOM -> Pair(boxWidthMeters / 2, pixelsToMeters(height.toFloat()) - boxHeightMeters / 2)
267 | Bound.Side.LEFT -> Pair(boxWidthMeters / 2, pixelsToMeters(height.toFloat()) / 2)
268 | Bound.Side.RIGHT -> Pair(pixelsToMeters(width.toFloat()) - boxWidthMeters / 2, pixelsToMeters(height.toFloat()) / 2)
269 | }
270 | bodyDef.position = Vec2(pair.first, pair.second)
271 | val body = world!!.createBody(bodyDef)
272 | body.createFixture(fixtureDef)
273 | return Bound(
274 | widthInPixels = widthInPixels,
275 | heightInPixels = heightInPixels,
276 | body = body,
277 | side = side
278 | )
279 | }
280 |
281 | private fun createBoundFixtureDef(box: PolygonShape, id: Int): FixtureDef {
282 | val fixtureDef = FixtureDef()
283 | fixtureDef.shape = box
284 | fixtureDef.density = 0.5f
285 | fixtureDef.friction = 0.3f
286 | fixtureDef.restitution = 0.5f
287 | fixtureDef.userData = id
288 | return fixtureDef
289 | }
290 |
291 | private fun createBody(physicsParentData: PhysicsParentData, oldBody: Body?): Body {
292 | val config = physicsParentData.physicsConfig
293 | val bodyDef = config.bodyDef
294 | bodyDef.position[pixelsToMeters(physicsParentData.initialX + physicsParentData.width / 2)] = pixelsToMeters(physicsParentData.initialY + physicsParentData.height / 2)
295 |
296 | // Log.d(TAG, "createBody: position: ${bodyDef.position}")
297 |
298 | if (oldBody != null) {
299 | bodyDef.angle = oldBody.angle
300 | bodyDef.angularVelocity = oldBody.angularVelocity
301 | bodyDef.linearVelocity = oldBody.linearVelocity
302 | bodyDef.angularDamping = oldBody.angularDamping
303 | bodyDef.linearDamping = oldBody.linearDamping
304 | } else {
305 | bodyDef.angularVelocity = degreesToRadians(physicsParentData.rotation)
306 | }
307 | val fixtureDef = config.fixtureDef
308 | fixtureDef.shape = if (config.shape == PhysicsShape.RECTANGLE) createBoxShape(physicsParentData) else createCircleShape(physicsParentData, config)
309 | fixtureDef.userData = physicsParentData.id
310 | val body = world!!.createBody(bodyDef)
311 | body.createFixture(fixtureDef)
312 | physicsParentData.body = body
313 | return body
314 | }
315 |
316 | private fun createBoxShape(physicsParentData: PhysicsParentData): PolygonShape {
317 | val box = PolygonShape()
318 | val boxWidth = pixelsToMeters(physicsParentData.width / 2.toFloat())
319 | val boxHeight = pixelsToMeters(physicsParentData.height / 2.toFloat())
320 | box.setAsBox(boxWidth, boxHeight)
321 | return box
322 | }
323 |
324 | private fun createCircleShape(physicsParentData: PhysicsParentData, config: PhysicsConfig): CircleShape {
325 | val circle = CircleShape()
326 | //radius was not set, set it to max of the width and height
327 | if (config.radius == -1f) {
328 | config.radius = max(physicsParentData.width / 2f, physicsParentData.height / 2f)
329 | }
330 | circle.m_radius = pixelsToMeters(config.radius)
331 | return circle
332 | }
333 |
334 | /**
335 | * Gives a random impulse to all the view bodies in the layout. Really just useful for testing,
336 | * but try it out if you want :)
337 | */
338 | fun giveRandomImpulse() {
339 | var body: Body?
340 | var impulse: Vec2
341 | val random = Random()
342 | for (i in 0 until composableGroup.childCount) {
343 | impulse = Vec2((random.nextInt(1000) - 1000).toFloat(), (random.nextInt(1000) - 1000).toFloat())
344 | body = composableGroup.getChildAt(i).body
345 | // Log.d(TAG, "giveRandomImpulse: pody's position : ${body?.position}")
346 | body?.applyLinearImpulse(impulse, body.position)
347 | }
348 | }
349 |
350 | private fun translateBodyToView(body: Body, view: View) {
351 | body.setTransform(
352 | Vec2(pixelsToMeters(view.x + view.width / 2),
353 | pixelsToMeters(view.y + view.height / 2)),
354 | body.angle)
355 | }
356 |
357 | /**
358 | * Sets the fling listener
359 | *
360 | * @param onFlingListener listener that will respond to fling events
361 | */
362 | fun setOnFlingListener(onFlingListener: OnFlingListener?) {
363 | this.onFlingListener = onFlingListener
364 | }
365 |
366 | /**
367 | * Sets the collision listener
368 | *
369 | * @param onCollisionListener listener that will listen for collisions
370 | */
371 | fun setOnCollisionListener(onCollisionListener: OnCollisionListener?) {
372 | this.onCollisionListener = onCollisionListener
373 | }
374 |
375 | /**
376 | * Sets the size of the bounds and enables the bounds
377 | *
378 | * @param size the size of the bounds in dp
379 | */
380 | fun setBoundsSize(size: Float) {
381 | boundsSizeInPixel = size * density
382 | if (hasBounds) {
383 | disableBounds()
384 | }
385 | enableBounds()
386 | }
387 |
388 | /**
389 | * Sets the gravity in the x direction for the world. Positive is right, negative is left.
390 | */
391 | fun setGravityX(newGravityX: Float) {
392 | setGravity(newGravityX, gravityY)
393 | }
394 |
395 | /**
396 | * The gravity in the x direction for the world. Positive is right, negative is left.
397 | */
398 | fun getGravityX(): Float {
399 | return gravityX
400 | }
401 |
402 | /**
403 | * Sets the gravity in the y direction for the world. Positive is down, negative is up.
404 | */
405 | fun setGravityY(newGravityY: Float) {
406 | setGravity(gravityX, newGravityY)
407 | }
408 |
409 | /**
410 | * The gravity in the x direction for the world. Positive is right, negative is left.
411 | */
412 | fun getGravityY(): Float {
413 | return gravityY
414 | }
415 |
416 | /**
417 | * Sets the gravity for the world. Positive x is right, negative is left. Positive
418 | * y is down, negative is up.
419 | */
420 | fun setGravity(gravityX: Float, gravityY: Float) {
421 | this.gravityX = gravityX
422 | this.gravityY = gravityY
423 | world?.gravity = Vec2(gravityX, gravityY)
424 | }
425 |
426 | /**
427 | * Returns the gravity of the world. Returns null if the world doesn't exist yet (view hasn't
428 | * called onLayout)
429 | */
430 | fun getGravity(): Vec2? {
431 | return world?.gravity
432 | }
433 |
434 | /**
435 | * Add a physics process listener
436 | */
437 | fun addOnPhysicsProcessedListener(listener: OnPhysicsProcessedListener) {
438 | onPhysicsProcessedListeners.add(listener)
439 | }
440 |
441 | /**
442 | * Remove a physics process listener
443 | */
444 | fun removeOnPhysicsProcessedListener(listener: OnPhysicsProcessedListener?) {
445 | onPhysicsProcessedListeners.remove(listener)
446 | }
447 |
448 | /**
449 | * Interface that allows hooks into the layout so that you can process or modify physics bodies each time that JBox2D processes physics
450 | */
451 | interface OnPhysicsProcessedListener {
452 |
453 | /**
454 | * Physics has been processed. Commence doing things that you want to do such as applying additional forces
455 | * @param physics the [Physics] that belongs to the view
456 | * @param world the Box2d world
457 | */
458 | fun onPhysicsProcessed(physics: Physics, world: World)
459 | }
460 |
461 | /**
462 | * A controller that will receive the drag events.
463 | */
464 | interface OnFlingListener {
465 | fun onGrabbed(grabbedView: View?)
466 | fun onReleased(releasedView: View?)
467 | }
468 |
469 | /**
470 | * Alerts you to collisions between views within the layout
471 | */
472 | interface OnCollisionListener {
473 | /**
474 | * Called when a collision is entered between two bodies. ViewId can also be
475 | * R.id.physics_layout_bound_top,
476 | * R.id.physics_layout_bound_bottom, R.id.physics_layout_bound_left, or
477 | * R.id.physics_layout_bound_right.
478 | * If view was not assigned an id, the return value will be [View.NO_ID].
479 | *
480 | * @param viewIdA view id of body A
481 | * @param viewIdB view id of body B
482 | */
483 | fun onCollisionEntered(viewIdA: Int, viewIdB: Int)
484 |
485 | /**
486 | * Called when a collision is exited between two bodies. ViewId can also be
487 | * R.id.physics_layout_bound_top,
488 | * R.id.physics_layout_bound_bottom, R.id.physics_layout_bound_left, or
489 | * R.id.physics_layout_bound_right.
490 | * If view was not assigned an id, the return value will be [View.NO_ID].
491 | *
492 | * @param viewIdA view id of body A
493 | * @param viewIdB view id of body B
494 | */
495 | fun onCollisionExited(viewIdA: Int, viewIdB: Int)
496 | }
497 | }
498 |
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/PhysicsConfig.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import org.jbox2d.dynamics.BodyDef
4 | import org.jbox2d.dynamics.BodyType
5 | import org.jbox2d.dynamics.FixtureDef
6 |
7 | enum class PhysicsShape {
8 | RECTANGLE,
9 | CIRCLE
10 | }
11 |
12 | /**
13 | * Configuration used when creating the [org.jbox2d.dynamics.Body] for each of the views in the view group
14 | */
15 | data class PhysicsConfig(
16 | /**
17 | * The shape of the physics body, either rectangle or circle. This changes how the body will
18 | * collide with other bodies.
19 | */
20 | var shape: PhysicsShape = PhysicsShape.RECTANGLE,
21 | /**
22 | * The fixture definition. Leave alone if you want the defaults. Learn more: [FixtureDef]
23 | */
24 | var fixtureDef: FixtureDef = createDefaultFixtureDef(),
25 | /**
26 | * The body definition. Leave alone if you want the defaults. Learn more: [BodyDef]
27 | */
28 | var bodyDef: BodyDef = createDefaultBodyDef()
29 | ) {
30 |
31 | /**
32 | * Only used if shape == CIRCLE, otherwise it is ignored. The radius of the circle in pixels.
33 | * Will be processed and set by its view size.
34 | */
35 | internal var radius: Float = -1f
36 |
37 | companion object {
38 |
39 | fun createDefaultFixtureDef(): FixtureDef {
40 | val fixtureDef = FixtureDef()
41 | fixtureDef.friction = 0.3f
42 | fixtureDef.restitution = 0.2f
43 | fixtureDef.density = 0.2f
44 | return fixtureDef
45 | }
46 |
47 | fun createDefaultBodyDef(): BodyDef {
48 | val bodyDef = BodyDef()
49 | bodyDef.type = BodyType.DYNAMIC //movable by default
50 | return bodyDef
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/PhysicsLayout.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import android.util.Log
4 | import androidx.compose.runtime.*
5 | import androidx.compose.ui.Modifier
6 | import androidx.compose.ui.draw.drawWithContent
7 | import androidx.compose.ui.geometry.Offset
8 | import androidx.compose.ui.geometry.Size
9 | import androidx.compose.ui.graphics.Color
10 | import androidx.compose.ui.layout.Layout
11 | import androidx.compose.ui.layout.Placeable
12 | import androidx.compose.ui.platform.LocalDensity
13 | import androidx.compose.ui.unit.IntOffset
14 | import androidx.compose.ui.unit.dp
15 | import kotlinx.coroutines.delay
16 | import org.jbox2d.common.Vec2
17 |
18 | private const val TAG = "PhysicsLayout"
19 |
20 | interface PhysicsLayoutScope {
21 | @Stable
22 | fun Modifier.physics(physicsConfig: PhysicsConfig, initialX : Float = 0f, initialY : Float = 0f) : Modifier
23 | }
24 |
25 | internal object PhysicsLayoutScopeInstance : PhysicsLayoutScope {
26 | @Stable
27 | override fun Modifier.physics(
28 | physicsConfig: PhysicsConfig,
29 | initialX: Float,
30 | initialY: Float
31 | ): Modifier = this.then(PhysicsParentData(physicsConfig, initialX, initialY))
32 | }
33 |
34 |
35 | @Composable
36 | fun PhysicsLayout(
37 | modifier: Modifier = Modifier,
38 | physicsLayoutState: PhysicsLayoutState = remember { PhysicsLayoutState() },
39 | boundColor: Color? = Color(121, 85, 72),
40 | boundSize : Float? = 20f,
41 | giveInitialRandomImpulse : Boolean = true,
42 | content : @Composable PhysicsLayoutScope.()->Unit
43 | ){
44 | val parentDataList = physicsLayoutState.physics.composableGroup.physicsParentDatas
45 | val physics = physicsLayoutState.physics
46 | val density = LocalDensity.current
47 | var initialized by remember {
48 | mutableStateOf(false)
49 | }
50 |
51 | LaunchedEffect(key1 = density){
52 | physics.density = density.density
53 | physics.pixelsPerMeter = with(density){
54 | 10.dp.toPx()
55 | }
56 | }
57 |
58 | var recompose by remember {
59 | mutableStateOf(0)
60 | }
61 |
62 | // 初始化世界
63 | LaunchedEffect(initialized){
64 | Log.d(TAG, "PhysicsLayout: launchedEffect ${parentDataList.size} ${physics.width}")
65 | if (!initialized) return@LaunchedEffect
66 | if (parentDataList.isEmpty()) return@LaunchedEffect
67 | if (physics.width * physics.height == 0) return@LaunchedEffect
68 | physics.createWorld { body, i ->
69 | parentDataList[i].body = body
70 | // Log.d(TAG, "PhysicsLayout: createBody: $body")
71 | }
72 | if(giveInitialRandomImpulse) physics.giveRandomImpulse()
73 | }
74 |
75 | LaunchedEffect(key1 = boundSize){
76 | if (boundSize != null && boundSize > 0){
77 | physics.setBoundsSize(boundSize)
78 | }
79 | }
80 |
81 | LaunchedEffect(key1 = Unit){
82 | while (true){
83 | delay(16)
84 | physics.step() // 模拟 16ms
85 | recompose++
86 | }
87 | }
88 |
89 | val drawBoundModifier =
90 | Modifier.drawWithContent {
91 | if (physics.hasBounds && boundColor != null && boundSize != null && boundSize > 0){
92 | if(physics.density <= 0) return@drawWithContent
93 | // 绘制 bound
94 | val s = boundSize * physics.density
95 | val w = physics.width.toFloat()
96 | val h = physics.height.toFloat()
97 | drawRect(boundColor, Offset.Zero, Size(w,s))
98 | drawRect(boundColor, Offset(0f, h-s), Size(w,s))
99 | drawRect(boundColor, Offset(0f, s), Size(s, h - 2 * s))
100 | drawRect(boundColor, Offset(w - s, s), Size(s, h - 2 * s))
101 | }
102 | drawContent()
103 | }
104 |
105 | Layout(content = { PhysicsLayoutScopeInstance.content() }, modifier = modifier.then(drawBoundModifier)){ measurables, constraints ->
106 | if (!initialized) {
107 | physics.setSize(constraints.maxWidth, constraints.maxHeight)
108 | }
109 |
110 | val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)
111 | val placeables = measurables.mapIndexed { index, measurable ->
112 | val physicsParentData = (measurable.parentData as? PhysicsParentData) ?: PhysicsParentData()
113 | // Log.d(TAG, "PhysicsLayout: init : $initialized")
114 | if (!initialized){
115 | parentDataList.add(index, physicsParentData)
116 | // Log.d(TAG, "PhysicsLayout: addParentData: (${physicsParentData.initialX}, ${physicsParentData.initialY})")
117 | }
118 | measurable.measure(childConstraints)
119 | }
120 |
121 | layout(constraints.maxWidth, constraints.maxHeight){
122 | placeables.forEachIndexed { i, placeable: Placeable ->
123 | // 正确设置各body大小
124 | parentDataList[i].width = placeable.width
125 | parentDataList[i].height = placeable.height
126 |
127 | val x = physics.metersToPixels(parentDataList[i].x).toInt() - placeable.width / 2
128 | val y = physics.metersToPixels(parentDataList[i].y).toInt() - placeable.height / 2
129 |
130 | val c = recompose // 这行代码什么用也没有,目的是触发重新 Layout
131 |
132 | // Log.d(TAG, "PhysicsLayout: $i -> x : $x y : $y")
133 | // Log.d(TAG, "PhysicsLayout: $recompose")
134 | // placeable.place(x, y)
135 | placeable.placeWithLayer(IntOffset(x,y), zIndex = 0f, layerBlock = {
136 | rotationZ = parentDataList[i].rotation
137 | })
138 | }
139 | }.also {
140 | // 各类初始化只进行一次即可
141 | if (!initialized) {
142 | initialized = true
143 | }
144 | }
145 | }
146 | }
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/PhysicsLayoutState.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import org.jbox2d.common.Vec2
4 |
5 | data class PhysicsLayoutState(val physics: Physics = Physics(ComposableGroup(arrayListOf()))){
6 | /**
7 | * 设置重力
8 | * @param x Float x方向,默认0
9 | * @param y Float y方向,默认9.8
10 | */
11 | fun setGravity(x:Float = 0f, y:Float = 9.8f){
12 | physics.world?.gravity = Vec2(x,y)
13 | }
14 |
15 | /**
16 | * 给所有物体一个随机冲量
17 | */
18 | fun giveRandomImpulse(){
19 | physics.giveRandomImpulse()
20 | }
21 | }
--------------------------------------------------------------------------------
/physics/src/main/java/com/funny/compose/physics/PhysicsParentData.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import androidx.compose.ui.layout.ParentDataModifier
4 | import androidx.compose.ui.unit.Density
5 | import org.jbox2d.dynamics.Body
6 |
7 | class PhysicsParentData(
8 | var physicsConfig: PhysicsConfig = PhysicsConfig(),
9 | var initialX: Float = 0f,
10 | var initialY: Float = 0f,
11 | var width: Int = 0,
12 | var height: Int = 0
13 | ) : ParentDataModifier {
14 | override fun Density.modifyParentData(parentData: Any?): Any = this@PhysicsParentData
15 |
16 | var body : Body? = null
17 |
18 | val rotation
19 | get() = body?.angle?.times(180f)?.div(Math.PI)?.toFloat() ?: 0f
20 |
21 | val id = hashCode()
22 | val x : Float
23 | get() = body?.position?.x ?: 0f
24 | val y : Float
25 | get() = body?.position?.y ?: 0f
26 |
27 | }
--------------------------------------------------------------------------------
/physics/src/test/java/com/funny/compose/physics/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.funny.compose.physics
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/screen_shot.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FunnySaltyFish/JetpackComposePhysicsLayout/f29d1d475dfb2885818ed9141ea41027bee5480e/screen_shot.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | maven { url 'https://maven.aliyun.com/repository/public/' }
12 | maven { url 'https://maven.aliyun.com/repository/google/'}
13 | maven { url 'https://maven.aliyun.com/repository/jcenter/'}
14 | maven { url "https://jitpack.io" }
15 | google()
16 | mavenCentral()
17 | }
18 | }
19 | rootProject.name = "JetpackComposePhysicsLayout"
20 | include ':app'
21 | include ':physics'
22 |
--------------------------------------------------------------------------------