1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma version(1)
18#pragma rs java_package_name(com.example.android.rs.vr.engine)
19#pragma rs_fp_relaxed
20
21int size;
22int z;
23rs_allocation volume;
24
25/* Unused function:
26static float3 nylander(float3 p, int n) {
27    float3 out;
28    float r = length(p);
29    float phi = atan2(p.y, p.x);
30    float theta = acos(p.z / r);
31    float rn = pow(r, n);
32    out.x = sin(n * theta) * cos(n * phi);
33    out.y = sin(n * theta) * sin(n * phi);
34    out.z = cos(n * theta);
35    return out * rn;
36}
37*/
38
39/**
40* 8 x faster than the above for n = 3
41*/
42static float3 nylander3(float3 p) {
43    float3 out = (float3){0.f, 0.f, 0.f};
44    float xy2 = p.x * p.x + p.y * p.y;
45    if (xy2 == 0) return out;
46    float z23x2y2 = (3 * p.z * p.z - p.x * p.x - p.y * p.y);
47    out.x = (z23x2y2 * p.x * (p.x * p.x - 3 * p.y * p.y)) / xy2;
48    out.y = (z23x2y2 * p.y * (3 * p.x * p.x - p.y * p.y)) / xy2;
49    out.z = p.z * (p.z * p.z - 3 * p.x * p.x - 3 * p.y * p.y);
50    return out;
51}
52
53short __attribute__((kernel)) mandelbulb(uint32_t x, uint32_t y) {
54    int size2 = size / 2;
55     if (z < size2) {
56          return 256-4*(size2-z+4)*hypot((float)x-size2,(float)y-size2) / size2 ;
57    }
58    float3 c = (float3) {(float) x, (float) y, (float) z};
59    c = ((c - size2) / (size2 * .9f));
60
61    int loop = 25;
62    float3 p = c;
63    float len;
64    for (int i = 0; i < loop; i++) {
65        //    p = nylander(p, 3) + c;
66        p = nylander3(p) + c;
67        len = fast_length(p);
68        if (len > 2.f) return 255 - loop*10;
69        if (len < .3f) return loop*10;
70
71    }
72    len = length(p);
73    return (short) (255 - (len * 255) / 4);
74}
75
76void __attribute__((kernel)) copy(short in, uint32_t x, uint32_t y) {
77    rsSetElementAt_short(volume, in, x, y, z);
78}
79